<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Objectives;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignAdSet;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Support\Actor;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Collection;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/**
 * Copy one ad into an ad set.
 *
 * Meta's /{ad_id}/copies endpoint does the copy. The ad set can belong to the
 * campaign in focus or to another published campaign on the same ad account.
 * When the user has not named the ad set, the ad sets are offered.
 */
class DuplicateAd implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly Actor $actor,
        private readonly Choices $choices,
    ) {}

    public function description(): Stringable|string
    {
        return 'Duplicate one ad into an ad set. The ad set can be in the campaign in focus or in another '
            .'published Meta campaign on the same ad account; pass destination_campaign_id for the other '
            .'campaign. Pass ad_id when the user named the ad. Pass ad_set_id when they named the destination '
            .'ad set. If ad_set_id is omitted, the ad sets are put on screen; wait for the user to pick one. '
            .'When the user gives a new primary text, headline, description, URL, or call to action, pass '
            .'those too: the copy is created first, then that wording, URL, and button are written onto '
            .'the new ad. The button is one of '.implode(', ', Objectives::CALLS_TO_ACTION).'. '
            .'Do not refuse a copy into another campaign.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_id' => $schema->string()
                ->description('The ad to copy. A local id or the platform id. Omit only when the campaign has one published ad.'),
            'ad_set_id' => $schema->string()
                ->description('The ad set that should receive the copy. Omit when the user has not named one.'),
            'destination_campaign_id' => $schema->string()
                ->description('The Meta campaign id that should receive the copy. Omit when the copy stays in the campaign in focus.'),
            'ad_account_id' => $schema->string()
                ->description('The Meta ad account that holds the ad, when the user names one. An act_ id or the numeric id.'),
            'primary_text' => $schema->string()->description('New primary text for the copied ad. Omit to keep the source wording.'),
            'headline' => $schema->string()->description('New headline for the copied ad. Omit to keep the source headline.'),
            'description' => $schema->string()->description('New description for the copied ad. Omit to keep the source description.'),
            'url' => $schema->string()->description('New destination URL for the copied ad. Omit to keep the source URL.'),
            'cta' => $schema->string()->description('New call-to-action button for the copied ad. One of '
                .implode(', ', Objectives::CALLS_TO_ACTION).'. Omit to keep the source button.'),
        ];
    }

    /** The user already asked for the copy, and the copy is created paused. */
    protected function needsApproval(Request $request): bool
    {
        return false;
    }

    public function handle(Request $request): Stringable|string
    {
        $focused = $this->focused();
        $destinationExternal = trim((string) ($request['destination_campaign_id'] ?? ''));
        $namedAccount = $this->accountId($request['ad_account_id'] ?? null);
        $adId = trim((string) ($request['ad_id'] ?? ''));
        $adSetId = trim((string) ($request['ad_set_id'] ?? ''));
        $changes = $this->requestedCopy($request);

        if ($refused = $this->refusedCta($changes)) {
            return $this->json(['ok' => false, 'error' => $refused]);
        }

        if ($namedAccount !== '' && $adId !== '' && $adSetId !== '') {
            return $this->copyUsingAccount($focused, $namedAccount, $adId, $adSetId, $destinationExternal, $changes);
        }

        if ($destinationExternal !== '' && $destinationExternal !== (string) ($focused?->external_campaign_id)) {
            return $this->copyIntoOtherCampaign($focused, $destinationExternal, $request);
        }

        if (! $campaign = $focused) {
            return $this->noCampaign();
        }

        if ($campaign->platform !== 'meta' || ! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'Only a published Meta campaign can receive a copied ad.',
            ]);
        }

        $ads = $this->publishedAds($campaign);
        $adSets = $campaign->adSets()->whereNotNull('external_adset_id')->orderBy('position')->get();

        if ($ads->isEmpty()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has no published ad to duplicate.',
            ]);
        }

        if ($adSets->isEmpty()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has no published ad set to put the copy in.',
            ]);
        }

        $source = $this->source($ads, $request['ad_id'] ?? null);

        if ($source === null) {
            $this->offerAds($ads);

            return $this->json([
                'ok' => false,
                'ask' => 'Which ad should be duplicated?',
                'ads' => $ads->map(fn (CampaignAd $ad): array => [
                    'id' => $ad->id,
                    'external_ad_id' => $ad->external_ad_id,
                    'headline' => $ad->headline,
                ])->values()->all(),
            ]);
        }

        $target = $this->target($adSets, $request['ad_set_id'] ?? null);

        if ($target === null) {
            $this->offerAdSets($source, $adSets);

            return $this->json([
                'ok' => false,
                'needs_ad_set' => true,
                'ask' => 'Which ad set should the copied ad go into?',
                'ad_id' => $source->external_ad_id,
            ]);
        }

        $meta = $this->meta->on($campaign->id, $this->actor->describe());

        try {
            $copied = $meta->copyAd(
                (string) $source->external_ad_id,
                (string) $target->external_adset_id,
                $campaign->ad_account_id,
            );
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The ad was not duplicated. Say that plainly.',
            ]);
        }

        $copiedId = $this->copiedAdId($copied);

        if ($copiedId === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Meta did not return the copied ad id.',
            ]);
        }

        try {
            $creativeId = $this->rewriteCopiedAd($meta, $copiedId, (string) $campaign->external_campaign_id, $campaign->ad_account_id, $changes);
        } catch (Throwable $exception) {
            return $this->wordingFailed($copiedId, $exception);
        }

        $ad = $this->rememberCopy($target, $source, $copiedId, $changes, $creativeId);

        $status = strtoupper((string) ($copied['status_option'] ?? 'PAUSED')) === 'ACTIVE' ? 'ACTIVE' : 'PAUSED';

        return $this->json([
            'ok' => true,
            'ad_id' => $ad->id,
            'external_ad_id' => $copiedId,
            'ad_set_id' => $target->external_adset_id,
            'headline' => $changes['headline'] ?? $ad->headline,
            'primary_text' => $changes['primary_text'] ?? null,
            'description' => $changes['description'] ?? null,
            'url' => $changes['url'] ?? null,
            'copy_updated' => $changes !== [],
            'status' => $status,
            'paused' => $status !== 'ACTIVE',
            'note' => $status === 'ACTIVE'
                ? 'The copied ad is active. Say that.'
                : 'The copied ad is paused in the chosen ad set. Say that it is not spending.',
        ]);
    }

    /**
     * Copy the named live ad with the ad account the user named.
     *
     * The campaign open in the chat may not hold that ad. Meta still has it,
     * and the copies call only needs the account, the ad, and the ad set.
     *
     * @param  array<string, string>  $changes
     */
    private function copyUsingAccount(?Campaign $focused, string $account, string $adId, string $adSetId, string $destinationExternal, array $changes): Stringable|string
    {
        $userId = $focused?->user_id ?? auth()->id();
        $source = $this->findAd($adId, $userId);
        $home = $this->campaignOnAccount($userId, $account, $destinationExternal);

        try {
            $copied = $this->meta->on($home?->id ?? $focused?->id, $this->actor->describe())->copyAd(
                (string) ($source?->external_ad_id ?: $adId),
                $adSetId,
                $account,
            );
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The ad was not duplicated. Say that plainly.',
            ]);
        }

        $copiedId = $this->copiedAdId($copied);

        if ($copiedId === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Meta did not return the copied ad id.',
            ]);
        }

        $campaignId = $destinationExternal !== ''
            ? $destinationExternal
            : (string) ($home?->external_campaign_id ?: $focused?->external_campaign_id);
        $meta = $this->meta->on($home?->id ?? $focused?->id, $this->actor->describe());

        try {
            $creativeId = $this->rewriteCopiedAd($meta, $copiedId, $campaignId, $account, $changes);
        } catch (Throwable $exception) {
            return $this->wordingFailed($copiedId, $exception);
        }

        $target = null;

        if ($home !== null && ($destinationExternal === '' || (string) $home->external_campaign_id === $destinationExternal)) {
            $target = $this->target(
                $home->adSets()->whereNotNull('external_adset_id')->orderBy('position')->get(),
                $adSetId,
            );
        }

        $ad = $target instanceof CampaignAdSet
            ? $this->rememberCopy($target, $source, $copiedId, $changes, $creativeId)
            : null;

        $status = strtoupper((string) ($copied['status_option'] ?? 'PAUSED')) === 'ACTIVE' ? 'ACTIVE' : 'PAUSED';

        return $this->json([
            'ok' => true,
            'ad_id' => $ad?->id,
            'external_ad_id' => $copiedId,
            'ad_set_id' => $adSetId,
            'destination_campaign_id' => $destinationExternal,
            'ad_account_id' => $account,
            'headline' => $changes['headline'] ?? ($ad?->headline ?: ($source?->headline ?: 'The ad')),
            'primary_text' => $changes['primary_text'] ?? null,
            'description' => $changes['description'] ?? null,
            'url' => $changes['url'] ?? null,
            'copy_updated' => $changes !== [],
            'status' => $status,
            'paused' => $status !== 'ACTIVE',
            'note' => 'The copied ad is in ad set '.$adSetId.' on '.$account.'. '.$this->copyStatusNote($status),
        ]);
    }

    private function copyStatusNote(string $status): string
    {
        return $status === 'ACTIVE'
            ? 'The copied ad is active. Say that.'
            : 'Say that it is not spending.';
    }

    private function accountId(mixed $account): string
    {
        $account = trim((string) $account);

        if ($account === '') {
            return '';
        }

        return str_starts_with($account, 'act_') ? $account : 'act_'.$account;
    }

    private function campaignOnAccount(mixed $userId, string $account, string $destinationExternal): ?Campaign
    {
        if ($userId === null) {
            return null;
        }

        $campaigns = Campaign::query()
            ->where('user_id', $userId)
            ->where('platform', 'meta')
            ->whereNotNull('ad_account_id')
            ->get()
            ->filter(fn (Campaign $campaign): bool => $this->accountId($campaign->ad_account_id) === $account);

        if ($destinationExternal !== '') {
            $match = $campaigns->first(fn (Campaign $campaign): bool => (string) $campaign->external_campaign_id === $destinationExternal);

            if ($match instanceof Campaign) {
                return $match;
            }
        }

        return $campaigns->sortByDesc('id')->first();
    }

    private function copyIntoOtherCampaign(?Campaign $focused, string $destinationExternal, Request $request): Stringable|string
    {
        $adId = trim((string) ($request['ad_id'] ?? ''));
        $adSetId = trim((string) ($request['ad_set_id'] ?? ''));
        $changes = $this->requestedCopy($request);
        $userId = $focused?->user_id ?? auth()->id();
        $source = $adId !== '' ? $this->findAd($adId, $userId) : null;
        $destination = $this->findCampaign($destinationExternal, $userId);

        if ($source === null && $adId === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Send the ad id to duplicate into the other campaign.',
            ]);
        }

        $externalAdId = (string) ($source?->external_ad_id ?: $adId);

        if ($destination === null) {
            if ($adSetId === '') {
                return $this->json([
                    'ok' => false,
                    'error' => 'Send the ad set id in campaign '.$destinationExternal.' that should receive the ad.',
                ]);
            }

            $accountCampaign = $focused !== null && $focused->platform === 'meta' && filled($focused->ad_account_id)
                ? $focused
                : Campaign::query()->where('user_id', $userId)->where('platform', 'meta')->whereNotNull('ad_account_id')->orderByDesc('id')->first();

            if ($accountCampaign === null) {
                return $this->json([
                    'ok' => false,
                    'error' => 'There is no Meta ad account here to copy with.',
                ]);
            }

            return $this->placeAd($accountCampaign, $externalAdId, $adSetId, $source, $destinationExternal, null, $changes);
        }

        if ($source !== null && (string) $source->campaign->ad_account_id !== (string) $destination->ad_account_id) {
            return $this->json([
                'ok' => false,
                'error' => 'That ad and the destination campaign are on different ad accounts, so the copy was not created.',
            ]);
        }

        $adSets = $destination->adSets()->whereNotNull('external_adset_id')->orderBy('position')->get();
        $target = $adSetId !== ''
            ? $adSets->first(fn (CampaignAdSet $adSet): bool => (string) $adSet->id === $adSetId || (string) $adSet->external_adset_id === $adSetId)
            : ($adSets->count() === 1 ? $adSets->first() : null);

        if ($target === null && $adSetId === '') {
            if ($source instanceof CampaignAd && $adSets->isNotEmpty()) {
                $this->offerAdSets($source, $adSets, $destinationExternal);

                return $this->json([
                    'ok' => false,
                    'needs_ad_set' => true,
                    'ask' => 'Which ad set in campaign '.$destinationExternal.' should the copied ad go into?',
                    'ad_id' => $externalAdId,
                    'destination_campaign_id' => $destinationExternal,
                ]);
            }

            return $this->json([
                'ok' => false,
                'error' => 'Send the ad set id in campaign '.$destinationExternal.' that should receive the ad.',
            ]);
        }

        if ($target instanceof CampaignAdSet) {
            return $this->placeAd($destination, $externalAdId, (string) $target->external_adset_id, $source, $destinationExternal, $target, $changes);
        }

        return $this->placeAd($destination, $externalAdId, $adSetId, $source, $destinationExternal, null, $changes);
    }

    /**
     * @param  array<string, string>  $changes
     */
    private function placeAd(Campaign $home, string $externalAdId, string $adSetId, ?CampaignAd $source, string $destinationExternal, ?CampaignAdSet $target, array $changes): Stringable|string
    {
        try {
            $copied = $this->meta->on($home->id, $this->actor->describe())->copyAd($externalAdId, $adSetId, $home->ad_account_id);
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The ad was not duplicated. Say that plainly.',
            ]);
        }

        $copiedId = $this->copiedAdId($copied);

        if ($copiedId === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Meta did not return the copied ad id.',
            ]);
        }

        if ($target === null && $home->external_campaign_id === $destinationExternal) {
            $target = $home->adSets()->create([
                'position' => ((int) $home->adSets()->max('position')) + 1,
                'name' => 'Ad set '.$adSetId,
                'locations' => ['countries' => []],
                'external_adset_id' => $adSetId,
                'status' => 'published',
            ]);
        }

        $ad = null;

        $meta = $this->meta->on($home->id, $this->actor->describe());

        try {
            $creativeId = $this->rewriteCopiedAd($meta, $copiedId, $destinationExternal !== '' ? $destinationExternal : (string) $home->external_campaign_id, $home->ad_account_id, $changes);
        } catch (Throwable $exception) {
            return $this->wordingFailed($copiedId, $exception);
        }

        if ($target instanceof CampaignAdSet) {
            $ad = $this->rememberCopy($target, $source, $copiedId, $changes, $creativeId);
        }

        $status = strtoupper((string) ($copied['status_option'] ?? 'PAUSED')) === 'ACTIVE' ? 'ACTIVE' : 'PAUSED';

        return $this->json([
            'ok' => true,
            'ad_id' => $ad?->id,
            'external_ad_id' => $copiedId,
            'ad_set_id' => $adSetId,
            'destination_campaign_id' => $destinationExternal,
            'headline' => $changes['headline'] ?? ($ad?->headline ?: 'The ad'),
            'primary_text' => $changes['primary_text'] ?? null,
            'description' => $changes['description'] ?? null,
            'url' => $changes['url'] ?? null,
            'copy_updated' => $changes !== [],
            'status' => $status,
            'paused' => $status !== 'ACTIVE',
            'note' => 'The copied ad is in campaign '.$destinationExternal.'. Say that.',
        ]);
    }

    /**
     * @return array<string, string>
     */
    private function requestedCopy(Request $request): array
    {
        $changes = [];

        foreach (['primary_text', 'headline', 'description', 'url'] as $field) {
            $value = trim((string) ($request[$field] ?? ''));

            if ($value !== '') {
                $changes[$field] = $value;
            }
        }

        $cta = $this->buttonCode((string) ($request['cta'] ?? ''));

        if ($cta !== '') {
            $changes['cta'] = $cta;
        }

        return $changes;
    }

    /**
     * Meta's button code from whatever the user typed.
     *
     * "Learn More", "learn-more", and "LEARN_MORE" are the same button.
     */
    private function buttonCode(string $value): string
    {
        $value = strtoupper(trim($value));
        $value = preg_replace('/[^A-Z]+/', '_', $value) ?? '';

        return trim($value, '_');
    }

    /**
     * @param  array<string, string>  $changes
     */
    private function refusedCta(array $changes): ?string
    {
        if (! isset($changes['cta']) || in_array($changes['cta'], Objectives::CALLS_TO_ACTION, true)) {
            return null;
        }

        return 'Call to action must be one of: '.implode(', ', Objectives::CALLS_TO_ACTION).'.';
    }

    /**
     * Write the supplied wording onto the ad Meta just copied.
     *
     * An empty change list leaves the source creative in place.
     *
     * @param  array<string, string>  $changes
     */
    private function rewriteCopiedAd(Meta $meta, string $adId, string $campaignId, ?string $account, array $changes): ?string
    {
        if ($changes === []) {
            return null;
        }

        if ($campaignId === '') {
            throw new MetaException('The campaign id is missing, so the new wording was not applied.');
        }

        return $meta->replaceAdCopy($adId, $campaignId, $account, $changes)['creative_id'];
    }

    private function wordingFailed(string $copiedId, Throwable $exception): string
    {
        return $this->json([
            'ok' => false,
            'external_ad_id' => $copiedId,
            'error' => 'The ad was copied as '.$copiedId.', but the new wording was not applied. '.$exception->getMessage(),
        ]);
    }

    /**
     * @param  array<string, string>  $changes
     */
    private function rememberCopy(CampaignAdSet $target, ?CampaignAd $source, string $copiedId, array $changes, ?string $creativeId): CampaignAd
    {
        return CampaignAd::create([
            'campaign_id' => $target->campaign_id,
            'ad_set_id' => $target->id,
            'asset_id' => $source?->asset_id,
            'headline' => $changes['headline'] ?? ($source?->headline ?: 'Ad'),
            'primary_text' => $changes['primary_text'] ?? ($source?->primary_text ?: ''),
            'description' => $changes['description'] ?? $source?->description,
            'cta' => $changes['cta'] ?? (filled($source?->cta) ? $source->cta : 'LEARN_MORE'),
            'external_creative_id' => $creativeId,
            'external_ad_id' => $copiedId,
            'status' => 'published',
        ]);
    }

    private function findCampaign(string $externalId, mixed $userId): ?Campaign
    {
        if ($externalId === '' || $userId === null) {
            return null;
        }

        return Campaign::query()
            ->where('platform', 'meta')
            ->where('external_campaign_id', $externalId)
            ->where('user_id', $userId)
            ->first();
    }

    private function findAd(string $adId, mixed $userId): ?CampaignAd
    {
        if ($adId === '' || $userId === null) {
            return null;
        }

        return CampaignAd::query()
            ->whereNotNull('external_ad_id')
            ->where(function ($query) use ($adId): void {
                $query->where('external_ad_id', $adId);

                if (ctype_digit($adId)) {
                    $query->orWhere('id', $adId);
                }
            })
            ->whereHas('campaign', fn ($query) => $query->where('user_id', $userId)->where('platform', 'meta'))
            ->first();
    }

    /** @param  Collection<int, CampaignAd>  $ads */
    private function source($ads, mixed $adId): ?CampaignAd
    {
        $adId = trim((string) $adId);

        if ($adId === '') {
            return $ads->count() === 1 ? $ads->first() : null;
        }

        return $ads->first(fn (CampaignAd $ad): bool => (string) $ad->id === $adId
            || (string) $ad->external_ad_id === $adId);
    }

    /** @param  Collection<int, CampaignAdSet>  $adSets */
    private function target($adSets, mixed $adSetId): ?CampaignAdSet
    {
        $adSetId = trim((string) $adSetId);

        if ($adSetId === '') {
            return null;
        }

        return $adSets->first(fn (CampaignAdSet $adSet): bool => (string) $adSet->id === $adSetId
            || (string) $adSet->external_adset_id === $adSetId);
    }

    /** @param  Collection<int, CampaignAd>  $ads */
    private function offerAds($ads): void
    {
        $this->choices->offer(
            field: 'duplicate_ad_source',
            question: 'Which ad should be duplicated?',
            options: $ads->map(fn (CampaignAd $ad): array => [
                'value' => (string) $ad->external_ad_id,
                'label' => filled($ad->headline) ? (string) $ad->headline : (string) $ad->external_ad_id,
                'sends' => 'Duplicate ad '.$ad->external_ad_id.'.',
            ])->values()->all(),
        );
    }

    /** @param  Collection<int, CampaignAdSet>  $adSets */
    private function offerAdSets(CampaignAd $source, $adSets, ?string $destinationExternalId = null): void
    {
        $this->choices->offer(
            field: 'duplicate_ad_adset',
            question: 'Which ad set should the copied ad go into?',
            options: $adSets->map(fn (CampaignAdSet $adSet): array => [
                'value' => $source->external_ad_id.'|'.$adSet->external_adset_id.($destinationExternalId ? '|'.$destinationExternalId : ''),
                'label' => filled($adSet->name) ? (string) $adSet->name : (string) $adSet->external_adset_id,
                'hint' => (string) $adSet->external_adset_id,
                'sends' => 'Put the copied ad in ad set '.$adSet->external_adset_id.'.',
            ])->values()->all(),
        );
    }

    /** @return Collection<int, CampaignAd> */
    private function publishedAds(Campaign $campaign)
    {
        return $campaign->ads()->whereNotNull('external_ad_id')->orderBy('id')->get();
    }

    /** @param  array<string, mixed>  $copied */
    private function copiedAdId(array $copied): string
    {
        if (filled($copied['copied_ad_id'] ?? null)) {
            return (string) $copied['copied_ad_id'];
        }

        foreach ((array) ($copied['ad_object_ids'] ?? []) as $object) {
            if (is_array($object) && ($object['ad_object_type'] ?? null) === 'ad' && filled($object['copied_id'] ?? null)) {
                return (string) $object['copied_id'];
            }
        }

        return filled($copied['id'] ?? null) ? (string) $copied['id'] : '';
    }
}
