<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Publisher;
use App\Models\CampaignAdSet;
use App\Support\Actor;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/**
 * Put newly written ads onto a campaign that is already live.
 *
 * Publishing created every ad a campaign had and that was the only moment it
 * ever could: writing another afterwards left a draft row that nothing would
 * ever send, and the publisher refuses a second publish outright - correctly,
 * since that made a whole second campaign. So the ads a buyer wrote on day two
 * sat in the chat looking finished and were never on Meta at all.
 *
 * This sends exactly those: the ads of this campaign with no platform id yet.
 * Nothing is written here. Writing an ad is write_ad_copy's job and uploading
 * its image is attach_creatives'; this is the step that was missing at the end.
 *
 * Approvable and created paused, like everything that touches a live account.
 * The campaign above may be spending, and an ad that arrived active would start
 * serving against a creative nobody approved for delivery.
 */
class AddAds implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

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

    public function description(): Stringable|string
    {
        return 'Send the ads that have been written but are not on the platform yet to the published '
            .'campaign in focus. Only for a campaign that is already published - before that, its ads '
            .'go out when it is published. Created paused. This always asks the user to approve first.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_set_id' => $schema->integer()
                ->description('Which ad set to put them in. Omit for the campaign\'s first ad set, '
                    .'which is what "the campaign" means unless the user named another.'),
        ];
    }

    /** Always. This creates ads on a live account. */
    protected function needsApproval(Request $request): bool
    {
        return true;
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->focused()) {
            return $this->noCampaign();
        }

        $adSet = $this->adSetFor($campaign, $request->all()['ad_set_id'] ?? null);

        if ($adSet === null) {
            return $this->json([
                'ok' => false,
                'error' => 'That ad set is not part of this campaign.',
                'ad_sets' => $campaign->adSets()->get(['id', 'position', 'name'])->all(),
            ]);
        }

        $ads = $this->publisher->adsAwaitingPublish($adSet);

        if ($blocking = $this->publisher->addAdsProblems($adSet, $ads)) {
            return $this->json([
                'ok' => false,
                'error' => 'These ads cannot be added: '.implode('; ', $blocking),
                'still_needed' => $blocking,
                'note' => 'Help with the first item. The live campaign and the ads already on it are '
                    .'untouched, so do not describe this as having broken anything.',
            ]);
        }

        try {
            $decision = $this->publisher->approveAds(
                $this->publisher->proposeAds($adSet, $this->actor->describe()),
                $this->actor->describe(),
            );
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'Anything part-made has been removed, and the ads already running are '
                    .'untouched. Say that plainly.',
            ]);
        }

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

        return $this->json([
            'ok' => true,
            'campaign' => $campaign->name,
            'ad_set' => $adSet->name,
            'added' => $ads->map(fn ($ad): array => [
                'ad_id' => $ad->id,
                'headline' => $ad->headline,
                'external_ad_id' => $ad->fresh()->external_ad_id,
            ])->all(),
            'paused' => true,
            'note' => 'They are on the platform and paused, so they are not serving yet even though '
                .'the campaign is. Say how many were added and that starting them is a separate step.',
        ]);
    }

    /**
     * Which ad set these ads go into.
     *
     * Null for an id that belongs to another campaign, which is refused rather
     * than silently redirected to the first ad set: the one thing worse than
     * failing to add an ad is adding it to the wrong audience.
     */
    private function adSetFor($campaign, mixed $id): ?CampaignAdSet
    {
        if (blank($id)) {
            return $campaign->primaryAdSet;
        }

        return $campaign->adSets()->whereKey((int) $id)->first();
    }
}
