<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\LinkedInManagement;
use App\Campaigns\Publisher;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
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;

/**
 * Pause or restart one ad set or ad, rather than the whole campaign.
 *
 * The campaign was the only level anything could reach. A buyer who wanted one
 * losing ad switched off had to do it in Ads Manager, and then - until the
 * restart asymmetry was fixed - watch the chat turn it back on. list_campaign_
 * structure now hands over real ids, and this is what they are for.
 *
 * One tool rather than four, because the surface is already large and the
 * decision is the same in every direction: name an object, name a state. The
 * verbs a buyer uses are in the description so the model still finds it.
 *
 * Two things this refuses to do blindly.
 *
 * It will not act on an id it has not seen under the campaign in focus. The
 * account allow list checks which account may be touched, not which object
 * within it, so without this an id from an earlier turn - or one the model
 * invented in the right shape - could pause a stranger's ad set on a permitted
 * account. Every id is checked against a fresh read first.
 *
 * And restarting a child of a live campaign begins delivery, so it asks. That
 * is the same line the rest of the product draws: approvals stand between a
 * buyer and spending, not between them and stopping. Pausing is never gated,
 * and neither is restarting something under a campaign that is itself paused,
 * because nothing can spend until the campaign is switched on.
 */
class SetEntityStatus implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    /** Most objects one call may change, so a mistake is bounded. */
    private const MOST_PER_CALL = 20;

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

    public function description(): Stringable|string
    {
        return 'Pause, restart, or archive a Meta campaign, ad set, or ad, a Google ad group or ad, or a '
            .'LinkedIn sponsored creative or campaign group inside the focused published campaign. '
            .'On Meta this posts status PAUSED, ACTIVE, or ARCHIVED to that object. ARCHIVED is '
            .'permanent and cannot be turned back on. Pausing a campaign stops '
            .'delivery without changing the ad sets and ads under it. An ad delivers only when the '
            .'campaign, the ad set, and the ad are all ACTIVE; quote effective_status for what Meta '
            .'is actually doing. Activating a staged LinkedIn replacement also pauses its original '
            .'after confirmed activation; explain that swap before approval. LinkedIn supports '
            .'entity_type ad, creative, or campaign_group; use IDs from live structure. Turn off, '
            .'turn on, unpause, resume, stop just one ad. Needs the ids from list_campaign_structure; '
            .'call that first and never guess an id. Pausing takes effect immediately. Restarting '
            .'something under a campaign that is already running begins spending, so the user is '
            .'asked to approve it.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'entity_type' => $schema->string()->enum(['campaign', 'ad_set', 'ad_group', 'ad', 'asset_group', 'creative', 'campaign_group'])
                ->description('Which level to change. campaign, ad_set, and ad are Meta. ad_group is '
                    .'Google\'s word for an ad set. asset_group is Google\'s Performance Max level. '
                    .'creative and campaign_group are LinkedIn\'s.')
                ->required(),
            'ids' => $schema->array()->items($schema->string())
                ->description('The platform ids to change, as returned by list_campaign_structure.')
                ->required(),
            'status' => $schema->string()->enum(['PAUSED', 'ACTIVE', 'ARCHIVED'])
                ->description('PAUSED to stop it delivering, ACTIVE to let it deliver again, ARCHIVED to archive it. Archiving is Meta only and cannot be undone.')
                ->required(),
        ];
    }

    /**
     * Google's word for live, in Meta's.
     *
     * Shared by needsApproval() and handle() on purpose. They each read the
     * argument themselves, and while only handle() translated ENABLED, the two
     * disagreed about what the model had asked for: the gate compared the raw
     * word against ACTIVE and let ENABLED past, then handle() translated it and
     * restarted a live ad group with no approval card. The tool's own
     * description teaches Google's vocabulary, and tool arguments are not
     * validated against the schema at runtime, so ENABLED is a word the model
     * will reach for.
     */
    private static function liveStatus(mixed $status): string
    {
        $status = strtoupper(trim((string) $status));

        return $status === 'ENABLED' ? 'ACTIVE' : $status;
    }

    /**
     * Only when it would start spending, or when it archives.
     *
     * Pausing is never gated. Restarting under a paused campaign spends nothing,
     * because the campaign gates its whole tree. Restarting under a live one
     * puts money on the line, which is the only thing approvals are for here.
     * Archiving is gated because it cannot be undone.
     */
    protected function needsApproval(Request $request): Approval|bool
    {
        $status = self::liveStatus($request->all()['status'] ?? '');

        if ($status === 'ARCHIVED') {
            $campaign = $this->focused();

            if ($campaign === null || $campaign->platform !== 'meta' || ! $campaign->isPublished()) {
                return false;
            }

            return $this->approvalBinding->request(
                $request,
                $campaign,
                'set_entity_status',
                note: 'Archiving is permanent. An archived campaign, ad set, or ad cannot be turned back on.',
            );
        }

        if ($status !== 'ACTIVE') {
            return false;
        }

        $campaign = $this->focused();

        if ($campaign !== null && $campaign->platform === 'linkedin' && ($request->all()['entity_type'] ?? null) === 'campaign_group') {
            return $this->approvalBinding->request($request, $campaign, 'set_entity_status');
        }
        if ($campaign === null || ! $campaign->isPublished()) {
            return false;
        }

        // Null means the platform could not be asked, and null is not "no": a
        // restart that might begin spending is asked about rather than assumed
        // safe. The read is memoised for this request, so handle() does not pay
        // for it twice.
        return ($this->publisher->isLiveOnPlatform($campaign, $this->actor->describe()) ?? true)
            ? $this->approvalBinding->request($request, $campaign, 'set_entity_status')
            : false;
    }

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

        $arguments = $request->all();
        // One internal word for each, so the checks below do not have to carry
        // both platforms' vocabularies. Google says ad group and ENABLED where
        // Meta says ad set and ACTIVE, and a model that has just read a Google
        // structure will reach for Google's words.
        $type = (string) ($arguments['entity_type'] ?? '');
        $type = $type === 'ad_group' ? 'ad_set' : $type;
        $status = self::liveStatus($arguments['status'] ?? '');
        $ids = array_values(array_unique(array_filter(array_map(
            static fn (mixed $id): string => trim((string) $id),
            (array) ($arguments['ids'] ?? []),
        ))));

        if (! in_array($type, ['campaign', 'ad_set', 'ad', 'asset_group', 'creative', 'campaign_group'], true) || ! in_array($status, ['PAUSED', 'ACTIVE', 'ARCHIVED'], true)) {
            return $this->json([
                'ok' => false,
                'error' => 'Choose campaign, ad_set, ad, creative, or campaign_group and status PAUSED, ACTIVE, or ARCHIVED. ARCHIVED is Meta only. LinkedIn supports ad, creative, and campaign_group; Meta supports campaign, ad_set, and ad.',
            ]);
        }

        if ($status === 'ARCHIVED' && $campaign->platform !== 'meta') {
            return $this->json([
                'ok' => false,
                'error' => 'Archiving is only available on Meta, and it cannot be undone.',
            ]);
        }

        if ($type === 'campaign' && $ids === [] && $campaign->platform === 'meta' && filled($campaign->external_campaign_id)) {
            $ids = [(string) $campaign->external_campaign_id];
        }

        if ($ids === []) {
            return $this->json([
                'ok' => false,
                'error' => 'No ids were given. Call list_campaign_structure and use the ids it returns.',
            ]);
        }

        if (count($ids) > self::MOST_PER_CALL) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Change up to %d at a time. This asked for %d.', self::MOST_PER_CALL, count($ids)),
            ]);
        }

        if ($type === 'campaign' && $campaign->platform !== 'meta') {
            return $this->json([
                'ok' => false,
                'error' => 'Pausing this campaign as one object is available on Meta. Use pause_campaign or request_activation for '.$campaign->platform.'.',
            ]);
        }

        if ($campaign->platform === 'linkedin') {
            $management = app(LinkedInManagement::class);
            $actor = $this->actor->describe();
            try {
                foreach ($ids as $id) {
                    $management->entity($campaign, $type, $id, $actor);
                }
            } catch (Throwable $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
            $changed = [];
            $failed = [];
            foreach ($ids as $id) {
                try {
                    $changed[] = $management->update($campaign, $type, $id,
                        [in_array($type, ['ad', 'creative'], true) ? 'intendedStatus' : 'status' => $status], $actor);
                } catch (Throwable $exception) {
                    $failed[$id] = $exception->getMessage();
                }
            }

            return $this->json(['ok' => $failed === [], 'changed' => $changed, 'failed' => $failed,
                'note' => 'Report each confirmed entity and any failure separately. Draft no-ops did not change delivery.']);
        }

        if ($campaign->platform === 'google') {
            return $this->handleGoogle($campaign, $type, $status, $ids);
        }

        if ($campaign->platform !== 'meta') {
            return $this->json([
                'ok' => false,
                'error' => sprintf('Changing a single entity is only available on Meta, Google and LinkedIn. This campaign is on %s.', ucfirst((string) $campaign->platform)),
            ]);
        }

        if (! in_array($type, ['campaign', 'ad_set', 'ad'], true)) {
            return $this->json(['ok' => false, 'error' => 'Meta supports campaign, ad_set, and ad here.']);
        }

        if ($type === 'campaign') {
            $ids = [(string) $campaign->external_campaign_id];
        }

        if (! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has not been published, so it has no ad sets or ads to change.',
            ]);
        }

        try {
            $known = $this->idsUnder($campaign, $type);
        } catch (MetaException $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'The platform could not be read, so nothing was changed. Do not retry blindly.',
            ]);
        }

        // Every id checked before any of them is written, so a bad id in a list
        // of five cannot leave the first two changed and the rest refused.
        if ($unknown = array_values(array_diff($ids, $known))) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%s %s not in this campaign, so nothing was changed.',
                    match ($type) {
                        'campaign' => 'Campaign(s)',
                        'ad_set' => 'Ad set(s)',
                        default => 'Ad(s)',
                    },
                    implode(', ', $unknown),
                ),
                'note' => 'Call list_campaign_structure for the current ids. Do not try these again.',
            ]);
        }

        $meta = $this->meta->on($campaign->id, $this->actor->describe());
        $changed = [];
        $failed = [];
        $effective = '';

        foreach ($ids as $id) {
            try {
                $read = $meta->setObjectStatus($campaign->ad_account_id, $id, $status);
                $changed[] = $id;
                $status = $read['status'] !== '' ? $read['status'] : $status;
                $effective = $effective !== '' ? $effective : $read['effective_status'];
            } catch (Throwable $e) {
                $failed[$id] = $e->getMessage();
            }
        }

        return $this->json(array_filter([
            'ok' => $changed !== [],
            'status' => $status,
            'effective_status' => $effective !== '' ? $effective : null,
            'entity_type' => $type,
            'changed' => $changed,
            'failed' => $failed ?: null,
            // Partial outcomes are named rather than averaged into one word,
            // because the buyer needs to know which of their ads is still running.
            'note' => $this->note($type, $status, $changed, $failed),
        ], static fn (mixed $value): bool => $value !== null));
    }

    /**
     * The same thing on Google, in Google's own levels.
     *
     * Google's word for live is ENABLED, so ACTIVE is translated at the edge
     * rather than carried through the checks above. Every id is verified
     * against the campaign's real structure first, for the reason the Meta path
     * does it: a bad id in a list of five must not leave the first two changed.
     *
     * Asset groups are deliberately not a level here. setLiveStatus has an ad,
     * ad-group and campaign level and nothing for an asset group, so a
     * Performance Max campaign has no individually pausable children - which is
     * why list_campaign_structure tells the model not to offer it.
     *
     * @param  list<string>  $ids
     */
    private function handleGoogle(Campaign $campaign, string $type, string $status, array $ids): Stringable|string
    {
        $connection = GoogleAdsConnection::shared();

        if ($connection === null) {
            return $this->json([
                'ok' => false,
                'error' => ucfirst(GoogleAdsConnection::missingReason()).'.',
                'note' => 'Nothing was changed. This needs an administrator.',
            ]);
        }

        // The account the campaign is on, not the configured default. See
        // GoogleAdsConnection::onCustomer - the allow list still gates it.
        $connection = $connection->onCustomer($campaign->ad_account_id);

        $google = app(GoogleAdsService::class);

        try {
            $structure = $google->readCampaignStructure($connection, (string) $campaign->external_campaign_id);
        } catch (Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => $e->getMessage(),
                'note' => 'The platform could not be read, so nothing was changed. Do not retry blindly.',
            ]);
        }

        // Performance Max keeps its creative in asset groups and has no ad
        // group or ad to address, so those are refused by name. The asset
        // group itself is addressable: it is created PAUSED, and until this
        // existed nothing in the product could ever switch it on.
        if ($type !== 'asset_group' && $structure['asset_groups'] !== [] && $structure['ad_groups'] === []) {
            return $this->json([
                'ok' => false,
                'error' => 'This is a Performance Max campaign, so its creative lives in asset groups '
                    .'and there is no ad group or ad to pause on its own. Use entity_type asset_group, '
                    .'or pause the campaign instead.',
                'note' => 'Say that plainly. Call list_campaign_structure for the asset group ids.',
            ]);
        }

        $known = array_column(match ($type) {
            'ad_set' => $structure['ad_groups'],
            'asset_group' => $structure['asset_groups'],
            default => $structure['ads'],
        }, 'id');

        if ($unknown = array_values(array_diff($ids, $known))) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%s %s not in this campaign, so nothing was changed.',
                    match ($type) {
                        'ad_set' => 'Ad group(s)',
                        'asset_group' => 'Asset group(s)',
                        default => 'Ad(s)',
                    },
                    implode(', ', $unknown),
                ),
                'note' => 'Call list_campaign_structure for the current ids. Do not try these again.',
            ]);
        }

        // An ad is addressed by its ad group as well as itself: Google keys an
        // AdGroupAd as <adGroupId>~<adId>, so the ad id alone cannot name it.
        // Taken from the structure read above rather than from the campaign's
        // external_ids, which holds one ad group and one ad and so cannot
        // answer for a campaign with more than one of either.
        $adGroupOf = collect($structure['ads'])->pluck('ad_group_id', 'id');
        $changed = [];
        $failed = [];

        foreach ($ids as $id) {
            try {
                $google->setChildStatus(
                    $connection,
                    match ($type) {
                        'ad_set' => 'ad_group',
                        'asset_group' => 'asset_group',
                        default => 'ad',
                    },
                    $id,
                    $type === 'ad' ? $adGroupOf->get($id) : null,
                    $status === 'PAUSED' ? 'PAUSED' : 'ENABLED',
                );
                $changed[] = $id;
            } catch (Throwable $e) {
                $failed[$id] = $e->getMessage();
            }
        }

        return $this->json(array_filter([
            'ok' => $changed !== [],
            'status' => $status === 'PAUSED' ? 'PAUSED' : 'ENABLED',
            'entity_type' => match ($type) {
                'ad_set' => 'ad_group',
                'asset_group' => 'asset_group',
                default => 'ad',
            },
            'changed' => $changed,
            'failed' => $failed ?: null,
            'note' => $this->googleNote($type, $status, $changed, $failed),
        ], static fn (mixed $value): bool => $value !== null));
    }

    /**
     * @param  list<string>  $changed
     * @param  array<string,string>  $failed
     */
    private function googleNote(string $type, string $status, array $changed, array $failed): string
    {
        // Named in Google's vocabulary, because the buyer is looking at the
        // Google Ads UI and "ad set" is not a word in it.
        $noun = $type === 'ad_set' ? 'ad group' : 'ad';
        $verb = $status === 'PAUSED' ? 'paused' : 'restarted';

        if ($changed === []) {
            return sprintf('Nothing was %s. Say which %s failed and why, and that the rest are unchanged.', $verb, $noun);
        }

        if ($failed !== []) {
            return sprintf(
                '%d %s(s) %s and %d failed. Name the ones that failed - the buyer needs to know which are '
                    .'still in their old state - and do not describe this as done.',
                count($changed), $noun, $verb, count($failed),
            );
        }

        return $status === 'PAUSED'
            ? sprintf('%d %s(s) paused and no longer delivering. Say so in one line.', count($changed), $noun)
            : sprintf(
                '%d %s(s) restarted. Say so in one line, and that delivery resumes only while the '
                    .'campaign itself is enabled. An ad also needs its approval status to be approved '
                    .'before it serves.',
                count($changed), $noun,
            );
    }

    /**
     * The ids that genuinely sit under this campaign, read fresh.
     *
     * @return list<string>
     */
    private function idsUnder(Campaign $campaign, string $type): array
    {
        $meta = $this->meta->on($campaign->id, $this->actor->describe());
        $external = (string) $campaign->external_campaign_id;

        if ($type === 'campaign') {
            return [$external];
        }

        $rows = $type === 'ad_set'
            ? $meta->adSets($external, $campaign->ad_account_id, fresh: true)
            : $meta->ads($external, $campaign->ad_account_id, fresh: true);

        return array_values(array_filter(array_map(
            static fn (array $row): string => (string) ($row['id'] ?? ''),
            $rows,
        )));
    }

    /**
     * @param  list<string>  $changed
     * @param  array<string,string>  $failed
     */
    private function note(string $type, string $status, array $changed, array $failed): string
    {
        $noun = match ($type) {
            'campaign' => 'campaign',
            'ad_set' => 'ad set',
            default => 'ad',
        };
        $verb = match ($status) {
            'PAUSED' => 'paused',
            'ARCHIVED' => 'archived',
            default => 'restarted',
        };

        if ($changed === []) {
            return sprintf('Nothing was %s. Say which %s failed and why, and that the rest are unchanged.', $verb, $noun);
        }

        if ($failed !== []) {
            return sprintf(
                '%d %s(s) %s and %d failed. Name the ones that failed - the buyer needs to know which are still '
                    .'in their old state - and do not describe this as done.',
                count($changed), $noun, $verb, count($failed),
            );
        }

        if ($status === 'ARCHIVED') {
            return sprintf('%d %s(s) archived. This cannot be undone, and they cannot be turned back on.', count($changed), $noun);
        }

        return $status === 'PAUSED'
            ? sprintf('%d %s(s) paused and no longer delivering. Say so in one line.', count($changed), $noun)
            : sprintf('%d %s(s) restarted. Say so in one line, and that delivery resumes only while the campaign itself is running.', count($changed), $noun);
    }
}
