<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Platforms\Platforms;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\LinkedIn\LinkedInException;
use App\Services\LinkedIn\LinkedInRestApi;
use App\Services\LinkedIn\LinkedInUrn;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Services\Platforms\Support\Guardrails;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * Confirm an ad account exists, is usable, and is one we are allowed to touch.
 *
 * Must succeed before Pages, pixels or uploads: all three are account scoped.
 * Changing the account clears them, because a Page id from one account is
 * meaningless on another and silently keeping it is how an ad ends up posted
 * by the wrong brand.
 */
class VerifyAdAccount implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly ?LinkedInRestApi $linkedInApi = null,
    ) {}

    public function description(): Stringable|string
    {
        return 'Verify an ad account by id and attach it to the campaign in focus. '
            .'Call this directly when the user names an account; only list accounts when they have not.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_account_id' => $schema->string()
                ->description('The ad account id, with or without the act_ prefix.')
                ->required(),
        ];
    }

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

        if (! in_array($campaign->platform, ['meta', 'linkedin', 'google'], true)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%s is not connected yet, so an ad account cannot be verified for it.',
                    app(Platforms::class)->for($campaign)->name(),
                ),
            ]);
        }

        if ($campaign->platform === 'linkedin') {
            return $this->handleLinkedIn($campaign, trim((string) ($request->all()['ad_account_id'] ?? '')));
        }

        if ($campaign->platform === 'google') {
            return $this->handleGoogle($campaign, trim((string) ($request->all()['ad_account_id'] ?? '')));
        }

        $id = trim((string) ($request->all()['ad_account_id'] ?? ''));
        $id = str_starts_with($id, 'act_') ? $id : 'act_'.ltrim($id, '_');

        try {
            $account = $this->meta->on($campaign->id, 'agent')->adAccount($id);
        } catch (MetaException $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        if ((int) ($account['account_status'] ?? 0) !== 1) {
            return $this->json([
                'ok' => false,
                'error' => "Ad account {$id} is not active (status {$account['account_status']}).",
            ]);
        }

        // Active is not the same as usable by us.
        //
        // Kaushal's 7 Oct campaign ran all the way to its first creative upload
        // on act_1184109403257239 and was refused there: "To create or edit ads
        // for ad account 1184109403257239, contact an admin to get permission
        // with an Advertiser role or higher." By then the account, objective,
        // category, Page, pixel, event, bidding, targeting, schedule and copy had
        // all been answered against an account that could never have published.
        //
        // Nothing was wrong with the chooser - list_ad_accounts reads
        // me/adaccounts, which returns 20 accounts and every one of them has
        // ADVERTISE. That account is not in it. It got in because the id can also
        // be typed, which is the route Kaushal said he took ("I didn't get the
        // option to select from all accounts, so I had to enter the account ID
        // manually"), and a typed id was verified for existence and activity but
        // never for whether we may advertise on it. duplicate_campaign then
        // carried it into the copy, which is the campaign that failed.
        //
        // MANAGE as well as ADVERTISE, because full control implies the lesser
        // permission. Absent or empty is refused: Meta omits the field entirely
        // on the account that failed, and returns it populated on all 20 that
        // work, so absence is the signal rather than the lack of one.
        $tasks = array_map('strval', (array) ($account['user_tasks'] ?? []));

        if (! array_intersect($tasks, ['ADVERTISE', 'MANAGE'])) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    'This login cannot create ads on %s (%s). Meta grants it %s. Creating anything '
                    .'there needs an Advertiser role or higher, and a token with ads_management.',
                    $account['name'] ?? $id,
                    $id,
                    $tasks === [] ? 'no role on the account at all' : implode(', ', $tasks),
                ),
                'note' => 'Do not retry and do not continue on this account. Call list_ad_accounts so the '
                    .'user can pick one we can publish to, and say that access to this one has to be '
                    .'granted in Business Manager before it can be used.',
            ]);
        }

        $changed = $campaign->ad_account_id && $campaign->ad_account_id !== $account['id'];
        $budgetCleared = $this->dropBudgetInOtherCurrency($campaign, $account['currency'] ?? null);
        $campaignMeta = (array) $campaign->meta;
        $campaignMeta['ad_account'] = array_filter([
            'id' => (string) $account['id'],
            'name' => $account['name'] ?? null,
            'currency' => $account['currency'] ?? null,
        ], fn (mixed $value): bool => $value !== null && $value !== '');

        if ($changed) {
            unset($campaignMeta['facebook_page'], $campaignMeta['pixel'], $campaignMeta['conversion_action']);
        }

        $campaign->update([
            'ad_account_id' => $account['id'],
            'currency' => $account['currency'] ?? $campaign->currency,
            'meta' => $campaignMeta,
            // Account scoped, so they cannot survive a change of account.
            ...$changed ? ['page_id' => null, 'pixel_id' => null] : [],
        ]);

        $this->workspace->recordSource($campaign, 'ad_account_id', ArtifactFieldSource::PLATFORM_RETURNED);

        if ($changed) {
            $this->workspace->forgetSources($campaign, 'page_id', 'pixel_id');
        }

        return $this->json(array_filter([
            'ok' => true,
            'ad_account_id' => $account['id'],
            'name' => $account['name'] ?? null,
            'currency' => $account['currency'] ?? null,
            'cleared_because_account_changed' => $changed ? ['page_id', 'pixel_id'] : null,
            'budget_cleared' => $budgetCleared ? 'The budget the user chose was in '.$budgetCleared.' but this account bills in '
                .$account['currency'].', so it has been REMOVED. Do not state or convert any amount. Say so in one line and '
                .'call set_campaign_budget with no amount so they pick a new one in '.$account['currency'].'.' : null,
        ], fn ($v) => $v !== null));
    }

    /**
     * An amount typed before the account was known is in the wrong currency once it is.
     *
     * @return string|null the currency the budget was in, when it was cleared
     */
    private function dropBudgetInOtherCurrency($campaign, ?string $accountCurrency): ?string
    {
        $was = $campaign->currency ?: 'USD';

        if ($accountCurrency === null || strtoupper($accountCurrency) === strtoupper($was) || ! ($campaign->budget > 0)) {
            return null;
        }

        $campaign->update(['budget' => null]);
        $this->workspace->forgetSources($campaign, 'budget');

        return $was;
    }

    /**
     * The Google child account the buyer picked.
     *
     * Google was refused here outright, with "Google Ads is not connected yet",
     * because there was nothing to verify: the account came from configuration
     * and list_ad_accounts set it without asking. Now that the children of the
     * manager can be listed, one of them has to be recordable, and this is the
     * half that records it - the same division Meta uses, where list offers and
     * verify writes.
     *
     * Checked against the manager's own children rather than against the allow
     * list alone. The allow list says what this instance may buy on; it does
     * not say the account exists or is reachable, and an id that passes the
     * guard but is not under the manager would be written to the campaign and
     * fail at publish, which is the failure mode this whole step exists to
     * stop. Both have to hold.
     *
     * Recorded as USER_STATED, unlike Meta's PLATFORM_RETURNED, because on
     * Google this genuinely is the buyer's answer to a question rather than an
     * id resolved on their behalf.
     */
    private function handleGoogle(Campaign $campaign, string $rawId): Stringable|string
    {
        $customerId = preg_replace('/\D/', '', $rawId) ?? '';

        if ($customerId === '') {
            return $this->json([
                'ok' => false,
                'error' => $rawId === ''
                    ? 'A Google Ads customer id is required.'
                    : sprintf('[%s] is not a Google Ads customer id. Google ids are ten digits, written '
                        .'either plainly or as 123-456-7890. An act_ prefix is Meta\'s.', $rawId),
                'note' => 'Call list_ad_accounts to put the permitted accounts on screen rather than '
                    .'asking the user to type an id.',
            ]);
        }

        try {
            app(Guardrails::class)->assertAccountAllowed($customerId, 'google');
        } catch (\Throwable $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        $connection = GoogleAdsConnection::shared();

        if ($connection === null) {
            return $this->json([
                'ok' => false,
                'error' => ucfirst(GoogleAdsConnection::missingReason()).'.',
                'note' => 'This needs an administrator, not an answer from the user. Say so and stop.',
            ]);
        }

        try {
            $children = app(GoogleAdsService::class)->childAccountOptions($connection);
        } catch (\Throwable $e) {
            return $this->json([
                'ok' => false,
                'error' => 'The Google Ads accounts under the manager could not be listed: '.$e->getMessage(),
                'note' => 'This is a platform error. Do not write an account id to the campaign anyway.',
            ]);
        }

        $account = collect($children)->firstWhere('customer_id', $customerId);

        if ($account === null) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%s is not one of the accounts under this Google Ads manager. Available: %s.',
                    $customerId,
                    collect($children)->pluck('customer_id')->implode(', ') ?: 'none',
                ),
                'note' => 'Offer the available accounts by name and ask again. Do not retry this id.',
            ]);
        }

        $changed = $campaign->ad_account_id && $campaign->ad_account_id !== $customerId;

        $campaign->update(['ad_account_id' => $customerId]);
        $this->workspace->recordSource($campaign, 'ad_account_id', ArtifactFieldSource::USER_STATED);

        // The conversion action belongs to the account it was read from, so it
        // cannot survive a move to a different one. Cleared rather than left to
        // fail at publish against an account that has never heard of it.
        if ($changed) {
            $campaign->update(['pixel_id' => null]);
            $this->workspace->forgetSources($campaign, 'pixel_id');
        }

        return $this->json(array_filter([
            'ok' => true,
            'ad_account_id' => $customerId,
            'name' => $account['name'],
            'cleared_because_account_changed' => $changed ? ['pixel_id'] : null,
            'note' => 'The account is set. Do not ask about it again.',
        ], fn ($v) => $v !== null));
    }

    private function handleLinkedIn($campaign, string $rawId): Stringable|string
    {
        // Checked here rather than by LinkedIn.
        //
        // bare() returned anything without a colon unchanged, so a Meta-style
        // act_1950320145707342 - or an account name typed instead of an id - was
        // put straight into rest/adAccounts/{id}. LinkedIn replies "Failed to
        // convert ... to java.lang.Long", which reached the chat verbatim: a Java
        // type error, in front of a media buyer, about a value they could have
        // fixed in a second if anything had said which value it was.
        $bareId = LinkedInUrn::numericId($rawId);

        if ($bareId === null) {
            return $this->json([
                'ok' => false,
                'error' => $rawId === ''
                    ? 'A LinkedIn ad account id is required.'
                    : sprintf(
                        '[%s] is not a LinkedIn ad account id. LinkedIn ids are numbers, either on '
                        .'their own or as urn:li:sponsoredAccount:<number>. An act_ prefix is Meta\'s.',
                        $rawId,
                    ),
                'note' => 'Ask the user for the LinkedIn account id, or call list_ad_accounts to put '
                    .'the ones we can reach on screen. Do not repeat this message verbatim.',
            ]);
        }

        // Asked of the guard rather than re-derived here.
        //
        // This enumerated permittedAccounts() and compared ids, and a wildcard
        // is a rule rather than an account: with linkedin:* set the list was
        // ['*'], no real id equals that, and every LinkedIn account was refused
        // on the one platform that had deliberately been opened to all of them.
        // The guard already answers this question, wildcard included, and it is
        // the same answer the publish gate will give later - which the local
        // copy was free to disagree with, and did.
        try {
            app(Guardrails::class)->assertAccountAllowed($bareId, 'linkedin');
        } catch (\Throwable $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        $api = $this->linkedInApi ?? app(LinkedInRestApi::class);

        try {
            $account = $api->adAccount($bareId);
        } catch (LinkedInException|\Throwable $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        if (($account['status'] ?? '') !== 'ACTIVE') {
            return $this->json([
                'ok' => false,
                'error' => "Ad account {$bareId} is not active (status ".($account['status'] ?? 'unknown').').',
            ]);
        }

        $changed = $campaign->ad_account_id && $campaign->ad_account_id !== $bareId;

        $campaign->update([
            'ad_account_id' => $bareId,
            'currency' => $account['currency'] ?? $campaign->currency ?? 'USD',
            ...$changed ? ['page_id' => null, 'pixel_id' => null] : [],
        ]);

        $this->workspace->recordSource($campaign, 'ad_account_id', ArtifactFieldSource::PLATFORM_RETURNED);

        if ($changed) {
            $this->workspace->forgetSources($campaign, 'page_id', 'pixel_id');
        }

        return $this->json(array_filter([
            'ok' => true,
            'ad_account_id' => $bareId,
            'name' => $account['name'] ?? null,
            'currency' => $account['currency'] ?? null,
            'cleared_because_account_changed' => $changed ? ['page_id', 'pixel_id'] : null,
        ], fn ($v) => $v !== null));
    }
}
