<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\PublishedState;
use App\Campaigns\Publisher;
use App\Campaigns\PublishGate;
use App\Support\Actor;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Approvals\Approval;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/**
 * Publish the campaign in focus, from the chat.
 *
 * The only tool that can spend money, and the only one that always pauses for a
 * human. InteractsWithApprovals stops the run before this executes: the user is
 * shown the tool and its arguments and must approve, and a rejection comes back
 * to the model as an ordinary result it can talk about.
 *
 * The approval is a second lock, not the only one. PublishGate still decides
 * whether the campaign may go at all, and it is re-checked inside the publisher
 * after approval, because a campaign can change between the two.
 */
class PublishCampaign implements Approvable, Tool
{
    // The trait supplies the approval methods; the interface is what the run
    // loop actually tests for. With the trait alone the tool looks gated and is
    // executed straight through, which is how publishing ran with no pause.
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly PublishGate $gate,
        private readonly Publisher $publisher,
        private readonly Actor $actor,
        private readonly CampaignApprovalBinding $approvalBinding,
    ) {}

    public function description(): Stringable|string
    {
        return 'Publish the campaign in focus to the advertising platform. Everything is created '
            .'paused, so nothing spends until the user switches it on in the platform. This always '
            .'asks the user to approve first. Only call it when they have clearly asked to publish.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [];
    }

    /** Always. Publishing is never done on the model's say-so alone. */
    protected function needsApproval(Request $request): Approval
    {
        return $this->approvalBinding->request($request, $this->focused(), 'publish_campaign');
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->approvalBinding->consume($request, 'publish_campaign')) {
            return $this->json(['ok' => false, 'error' => 'The approved campaign changed or the approval expired. Review it again.']);
        }

        if ($blocking = $this->gate->check($campaign)) {
            return $this->json([
                'ok' => false,
                'published' => false,
                'still_needed' => $blocking,
            ]);
        }

        // Proposed outside the try so the decision is still in hand if approving
        // throws. It carries what the rollback could not remove, and that is the
        // difference between telling the buyer their account is clean and
        // telling them what is on it.
        $decision = $this->publisher->propose($campaign, $this->actor->describe());

        try {
            $decision = $this->publisher->approve($decision, $this->actor->describe());
        } catch (Throwable $e) {
            // Reported as a result so the model can explain it rather than the
            // turn dying.
            $left = (array) ($decision->fresh()?->result['left_behind'] ?? []);

            return $this->json(array_filter([
                'ok' => false,
                'published' => false,
                'error' => $e->getMessage(),
                'left_on_platform' => $left ?: null,
                // Said from what the rollback actually returned. This used to
                // assert "anything already created was removed" whatever
                // happened, and on 5 Oct that was untrue on production: the
                // campaign object could not be deleted and the buyer was told it
                // had been.
                'note' => $left === []
                    ? 'Nothing was left on the platform. The campaign was not published.'
                    : 'The campaign was not published, and the cleanup could not remove everything it made. '
                        .'Tell the user plainly which ids are still on their ad account and that they will '
                        .'need removing there; do not say it was all undone.',
            ], fn (mixed $value): bool => $value !== null));
        }

        if (! $decision->wasApplied()) {
            // "already published as X" is the double publish guard, and it is
            // not a failure: the campaign the buyer is asking for is live. Said
            // as a refusal it reads as "it did not work", which is what sends
            // somebody round the loop again.
            $already = (string) ($campaign->fresh()->external_campaign_id ?? '');

            if ($already !== '' && str_contains((string) $decision->reason, 'already published')) {
                return $this->json([
                    'ok' => true,
                    'published' => true,
                    'already_published' => true,
                    'campaign_id' => $already,
                    'note' => sprintf(
                        'This campaign is already on the platform as %s, so nothing was published again. '
                        .'Say that it is already live, say the id, and do not offer to publish it again.',
                        $already,
                    ),
                ]);
            }

            return $this->json([
                'ok' => false,
                'published' => false,
                'error' => $decision->reason,
            ]);
        }

        // The id is lifted out of the result and the note names it.
        //
        // Not one of twenty eight production conversations that reached the
        // approval card contains a message telling the buyer a campaign had
        // published, while seven campaigns really did go live. The id was
        // already in `created`, buried a level down, and nothing required the
        // model to say it. Buyers approved the same publish up to five times
        // because silence is indistinguishable from failure, and the second
        // publish is what Meta refuses with "already publishing from an earlier
        // request".
        $created = (array) $decision->result;
        $campaignId = (string) ($created['campaign_id'] ?? '');

        return $this->json(array_filter([
            'ok' => true,
            'published' => true,
            'campaign_id' => $campaignId ?: null,
            'created' => $created,
            'note' => sprintf(
                'Published%s, %s. Say in this reply that it is on the platform%s, created %s, and that '
                .'nothing spends until they start it. Do not end the turn without confirming it '
                .'published - a buyer who is not told assumes it failed and will ask again.',
                $campaignId === '' ? '' : ' as '.$campaignId,
                PublishedState::describe($campaign->platform),
                $campaignId === '' ? '' : ' with id '.$campaignId,
                PublishedState::describe($campaign->platform),
            ),
        ], static fn (mixed $value): bool => $value !== null));
    }
}
