<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Publisher;
use App\Models\ArtifactFieldSource;
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;

/**
 * Add an ad set to a campaign that is already live.
 *
 * The usual reason is to test a second audience, a second geography or a second
 * budget against the same offer, which is most of what media buying is. There
 * was no way to do it: a campaign held one ad set's settings in its own columns,
 * so the second ad set's targeting had nowhere to live, and the buyer went to
 * Ads Manager - at which point our copy of the campaign and Meta's disagreed
 * and nothing here said so.
 *
 * Approvable, like publishing and starting, because it creates objects on a real
 * account under a campaign that may already be spending. It is created paused,
 * for the same reason: the parent is live, so an ad set that arrived active
 * would start spending the moment it existed.
 *
 * Takes its settings as arguments rather than sending the buyer back through the
 * launch flow. The flow's tools write to the campaign, which addresses the first
 * ad set, so set_targeting after this would have edited the wrong one.
 */
class AddAdSet 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 'Add another ad set to the published campaign in focus, for a different audience, '
            .'country or budget against the same campaign. The campaign must already be published: '
            .'before that, extra ad sets simply go out with it. Created paused, so it spends nothing '
            .'until the user starts it. This always asks the user to approve first.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'name' => $schema->string()
                ->description('A short name for the ad set, so the user can tell it apart in reporting. '
                    .'Optional: one is generated from the campaign name and its position.'),
            'countries' => $schema->array()->items($schema->string())
                ->description('Two-letter ISO codes (e.g. ["US", "GB"]). Required: an ad set is who it reaches.'),
            'placements' => $schema->array()->items($schema->string())
                ->description('Where the ads should appear. The accepted values depend on the platform, '
                    .'so omit it to use the same placements as the campaign\'s first ad set.'),
            'age_min' => $schema->integer()->description('Minimum age, 13 to 65.'),
            'age_max' => $schema->integer()->description('Maximum age, 13 to 65.'),
            'budget' => $schema->number()
                ->description('This ad set\'s own amount, as a decimal. Omit to use the campaign\'s. '
                    .'Must be omitted when the campaign holds its budget at campaign level, because '
                    .'Meta moves that money between ad sets itself.'),
            'budget_mode' => $schema->string()
                ->description('daily for an amount per day, lifetime for a total by the end date. '
                    .'Defaults to the campaign\'s.'),
            'optimization_goal' => $schema->string()
                ->description('What this ad set optimises for, if it should differ from the campaign\'s.'),
            'starts_at' => $schema->string()->description('When it should start, as YYYY-MM-DD. Defaults to now.'),
            'ends_at' => $schema->string()->description('When it should stop, as YYYY-MM-DD. Omit to run on.'),
        ];
    }

    /** Always. This creates objects 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();
        }

        $arguments = $request->all();

        if (! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has not been published yet, so there is nothing to add an ad set to.',
                'note' => 'Its ad sets go out when it is published. If they want a second audience now, '
                    .'say that it will be created along with the campaign, and publish when ready.',
            ]);
        }

        $adSet = $this->rowFor($campaign, $arguments);

        // Asked rather than proposed, so a question does not leave a blocked
        // decision behind. The row stays as a draft the user can correct.
        if ($blocking = $this->publisher->adSetProblems($adSet)) {
            return $this->json([
                'ok' => false,
                'error' => 'This ad set cannot be added: '.implode('; ', $blocking),
                'still_needed' => $blocking,
                'ad_set_id' => $adSet->id,
                'note' => 'The ad set has been kept as a draft with what you gave, so help with the '
                    .'first item and call this again. The live campaign is untouched.',
            ]);
        }

        try {
            $decision = $this->publisher->approveAdSet(
                $this->publisher->proposeAdSet($adSet, $this->actor->describe()),
                $this->actor->describe(),
            );
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'Nothing was added and the campaign is unchanged. Whatever was part-made has '
                    .'been removed. Say that plainly.',
            ]);
        }

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

        $adSet->refresh();

        return $this->json([
            'ok' => true,
            'ad_set_id' => $adSet->id,
            'external_adset_id' => $adSet->external_adset_id,
            'name' => $adSet->name,
            'campaign' => $campaign->name,
            'countries' => $adSet->locations['countries'] ?? [],
            'budget' => $adSet->effectiveBudget(),
            'currency' => $campaign->currency,
            'ads' => $adSet->ads()->whereNotNull('external_ad_id')->count(),
            'paused' => true,
            'note' => 'It is on the platform and paused, so it is not spending. Say which audience it '
                .'targets and for how much. If it has no ads yet, say so and offer to write some - an '
                .'ad set with no ads delivers nothing.',
        ]);
    }

    /**
     * The row this call is about: the pending one, or a new one.
     *
     * A published campaign's ad sets are all on the platform, so any unpublished
     * one is an addition that has not gone out yet - an earlier attempt that the
     * gate refused. Updating it rather than adding another is what stops a
     * campaign collecting a draft ad set per correction.
     *
     * @param  array<string, mixed>  $arguments
     */
    private function rowFor($campaign, array $arguments): CampaignAdSet
    {
        $pending = $campaign->adSets()->whereNull('external_adset_id')->latest('id')->first();

        $position = $pending?->position
            ?? ((int) $campaign->adSets()->max('position') + 1);

        $attributes = array_filter([
            'position' => $position,
            'name' => $arguments['name'] ?? null,
            'locations' => $this->locations($campaign, $arguments, $pending),
            'audience' => $this->audience($campaign, $arguments, $pending),
            'placements' => $arguments['placements'] ?? $pending?->placements ?? $campaign->placements,
            'budget' => $arguments['budget'] ?? null,
            'budget_mode' => $arguments['budget_mode'] ?? null,
            'optimization_goal' => $arguments['optimization_goal'] ?? null,
            'starts_at' => $arguments['starts_at'] ?? null,
            'ends_at' => $arguments['ends_at'] ?? null,
        ], fn (mixed $value): bool => $value !== null);

        $attributes['name'] ??= $pending?->name ?: $campaign->name.' - ad set '.$position;

        $adSet = $pending
            ? tap($pending)->update($attributes)
            : $campaign->adSets()->create($attributes);

        // Stamped against the campaign, which is the artifact the panel and the
        // publish gate know about. An ad set is not an artifact in its own right,
        // and the values here came from the buyer asking for this ad set.
        foreach (['locations', 'placements', 'budget'] as $field) {
            if (array_key_exists($field === 'locations' ? 'countries' : $field, $arguments)) {
                $this->workspace->recordSource($campaign, $field, ArtifactFieldSource::USER_STATED);
            }
        }

        return $adSet;
    }

    /**
     * Where this ad set runs.
     *
     * Falls back to the campaign's own countries rather than refusing, because
     * "another ad set, same places, different audience" is an ordinary ask and
     * the gate is what insists on having somewhere to run.
     *
     * @param  array<string, mixed>  $arguments
     * @return array<string, mixed>|null
     */
    private function locations($campaign, array $arguments, ?CampaignAdSet $pending): ?array
    {
        $countries = $arguments['countries'] ?? null;

        if ($countries === null) {
            return $pending?->locations ?? $campaign->locations;
        }

        return [
            ...(array) ($pending?->locations ?? []),
            'countries' => array_values(array_unique(array_map(
                fn (mixed $code): string => strtoupper(trim((string) $code)),
                (array) $countries,
            ))),
        ];
    }

    /**
     * Who it reaches beyond the geography.
     *
     * A different age band is one of the two or three things a second ad set is
     * usually for, so an ad set with no ages of its own takes the campaign's
     * rather than silently reaching everybody - which on a campaign deliberately
     * narrowed to 25-45 would be a quietly wider audience than anyone asked for.
     *
     * @param  array<string, mixed>  $arguments
     * @return array<string, mixed>|null
     */
    private function audience($campaign, array $arguments, ?CampaignAdSet $pending): ?array
    {
        $given = array_filter([
            'age_min' => $arguments['age_min'] ?? null,
            'age_max' => $arguments['age_max'] ?? null,
        ], fn (mixed $value): bool => $value !== null);

        if ($given === []) {
            return $pending?->audience ?? $campaign->audience;
        }

        return [...(array) ($pending?->audience ?? $campaign->audience ?? []), ...$given];
    }
}
