<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\AdSetDuplicator;
use App\Models\Campaign;
use App\Models\CampaignAdSet;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Support\Actor;
use Carbon\Carbon;
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;

/**
 * Duplicate one ad set into a published Meta campaign.
 *
 * Meta copies the ad set and its ads. The destination can be the campaign in
 * focus or another campaign on the same ad account. When more than one ad set
 * could be meant, the reply says which ones to ask about.
 */
class DuplicateAdSet implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

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

    public function description(): Stringable|string
    {
        return 'Duplicate an ad set, including its targeting and its ads, into a published Meta campaign. '
            .'The destination is the campaign in focus unless destination_campaign_id names another one on '
            .'the same ad account. Call this as soon as the user asks to duplicate an ad set, including '
            .'from one campaign into another. Do not refuse a cross-campaign copy, and do not describe a '
            .'missed approval instead of calling it. If the reply contains ask, ask the user which ad set '
            .'and call again.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_set_id' => $schema->string()
                ->description('The ad set to copy. A local id or the platform id. Omit only when the campaign has one published ad set, or when the user has not said which of several.'),
            'name' => $schema->string()
                ->description('Name for the copy. Optional. Defaults to the original name plus " - copy".'),
            'pixel_id' => $schema->string()
                ->description('A pixel assigned to this ad account. Pass it only after the user picks one because the pixel on the ad set is not available to the account.'),
            '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.'),
        ];
    }

    /** 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'] ?? ''));
        $destination = $this->findCampaign($destinationExternal);
        $adSetId = trim((string) ($request['ad_set_id'] ?? ''));

        if ($destination === null && $destinationExternal !== '') {
            return $this->copyIntoUnstoredCampaign($focused, $destinationExternal, $adSetId, $request);
        }

        $campaign = $destination ?? $focused;

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

        if ($campaign->platform !== 'meta' || ! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has not been published yet, so there is nowhere to put a copy.',
                'note' => 'Its ad sets go out when it is published. Ask the user to publish first if they want the copy on the platform.',
            ]);
        }

        $source = $adSetId !== '' ? $this->findSourceAdSet($campaign, $adSetId) : null;

        if ($source === null && $adSetId === '') {
            $prepared = $this->duplicator->prepare($campaign, null);

            if (($prepared['ok'] ?? false) !== true) {
                return $this->json($prepared);
            }

            $source = $prepared['source'];
        }

        if (! $source instanceof CampaignAdSet) {
            return $this->copyExternalInto($campaign, $adSetId, $request);
        }

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

        return $this->copyStoredSource($campaign, $source, $request);
    }

    private function copyStoredSource(Campaign $campaign, CampaignAdSet $source, Request $request): Stringable|string
    {
        $meta = $this->meta->on($campaign->id, $this->actor->describe());
        $pixelId = trim((string) ($request['pixel_id'] ?? ''));
        $pixelName = null;
        $destinationExternal = (string) $campaign->external_campaign_id;
        $pixelDestination = $this->otherCampaignId($campaign);

        try {
            if ($pixelId !== '') {
                $pixelName = $this->pixelOnAccount($campaign, $pixelId);

                if ($pixelName === null) {
                    return $this->offerReplacementPixel($campaign, (string) $source->external_adset_id, $pixelDestination);
                }

                $copied = $meta->duplicateAdSetWithPixel(
                    (string) $source->external_adset_id,
                    $destinationExternal,
                    (string) $campaign->ad_account_id,
                    $pixelId,
                    $request['name'] ?? null,
                );
            } else {
                $copied = $meta->copyAdSet(
                    (string) $source->external_adset_id,
                    $destinationExternal,
                    $campaign->ad_account_id,
                );
            }

            $copiedAds = filled($copied['ad_object_ids'] ?? null)
                ? []
                : $meta->adsIn((string) ($copied['copied_adset_id'] ?? $copied['id'] ?? ''), $campaign->ad_account_id);
            $adSet = $this->duplicator->remember($campaign, $source, $copied, $copiedAds, $request['name'] ?? null, $pixelId !== '' ? $pixelId : null);
        } catch (Throwable $exception) {
            if ($this->pixelAccessRefused($exception)) {
                return $this->offerReplacementPixel($campaign, (string) $source->external_adset_id, $pixelDestination);
            }

            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'Nothing was added and the campaign is unchanged. Say that plainly.',
            ]);
        }

        return $this->copied($campaign, (string) $source->external_adset_id, (string) $adSet->external_adset_id, (string) $adSet->name, $adSet->ads()->count(), $copied, $pixelId, $pixelName, $adSet->id);
    }

    private function copyExternalInto(Campaign $campaign, string $adSetId, Request $request): Stringable|string
    {
        if ($adSetId === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Send the ad set id to duplicate.',
            ]);
        }

        $meta = $this->meta->on($campaign->id, $this->actor->describe());
        $pixelId = trim((string) ($request['pixel_id'] ?? ''));
        $pixelName = null;

        try {
            if ($pixelId !== '') {
                $pixelName = $this->pixelOnAccount($campaign, $pixelId);

                if ($pixelName === null) {
                    return $this->offerReplacementPixel($campaign, $adSetId, $this->otherCampaignId($campaign));
                }

                $copied = $meta->duplicateAdSetWithPixel(
                    $adSetId,
                    (string) $campaign->external_campaign_id,
                    (string) $campaign->ad_account_id,
                    $pixelId,
                    $request['name'] ?? null,
                );
            } else {
                $copied = $meta->copyAdSet($adSetId, (string) $campaign->external_campaign_id, $campaign->ad_account_id);
            }

            $adSet = $this->duplicator->rememberExternal($campaign, $adSetId, $copied, $request['name'] ?? null);
        } catch (Throwable $exception) {
            if ($this->pixelAccessRefused($exception)) {
                return $this->offerReplacementPixel($campaign, $adSetId, $this->otherCampaignId($campaign));
            }

            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'Nothing was added and the campaign is unchanged. Say that plainly.',
            ]);
        }

        return $this->copied($campaign, $adSetId, (string) $adSet->external_adset_id, (string) $adSet->name, $adSet->ads()->count(), $copied, $pixelId, $pixelName, $adSet->id);
    }

    private function copyIntoUnstoredCampaign(?Campaign $focused, string $destinationExternal, string $adSetId, Request $request): Stringable|string
    {
        if ($adSetId === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Send the ad set id and the campaign to copy it into.',
            ]);
        }

        $accountCampaign = $this->accountCampaign($focused);

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

        $meta = $this->meta->on($accountCampaign->id, $this->actor->describe());
        $pixelId = trim((string) ($request['pixel_id'] ?? ''));
        $pixelName = null;

        try {
            if ($pixelId !== '') {
                $pixelName = $this->pixelOnAccount($accountCampaign, $pixelId);

                if ($pixelName === null) {
                    return $this->offerReplacementPixel($accountCampaign, $adSetId, $destinationExternal);
                }

                $copied = $meta->duplicateAdSetWithPixel(
                    $adSetId,
                    $destinationExternal,
                    (string) $accountCampaign->ad_account_id,
                    $pixelId,
                    $request['name'] ?? null,
                );
            } else {
                $copied = $meta->copyAdSet($adSetId, $destinationExternal, $accountCampaign->ad_account_id);
            }
        } catch (Throwable $exception) {
            if ($this->pixelAccessRefused($exception)) {
                return $this->offerReplacementPixel($accountCampaign, $adSetId, $destinationExternal);
            }

            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The ad set was not duplicated. Say that plainly.',
            ]);
        }

        $copiedId = (string) ($copied['copied_adset_id'] ?? $copied['id'] ?? '');

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

        $ads = collect((array) ($copied['ad_object_ids'] ?? []))->where('ad_object_type', 'ad')->count();

        return $this->copied(null, $adSetId, $copiedId, filled($request['name'] ?? null) ? (string) $request['name'] : 'the ad set', $ads, $copied, $pixelId, $pixelName, null, $destinationExternal);
    }

    /**
     * @param  array<string, mixed>  $copied
     */
    private function copied(?Campaign $campaign, string $from, string $externalId, string $name, int $ads, array $copied, string $pixelId, ?string $pixelName, ?int $localId, ?string $destinationExternal = null): Stringable|string
    {
        $status = strtoupper((string) ($copied['status_option'] ?? 'PAUSED')) === 'ACTIVE' ? 'ACTIVE' : 'PAUSED';
        $destinationExternal ??= (string) ($campaign?->external_campaign_id ?? '');

        return $this->json([
            'ok' => true,
            'ad_set_id' => $localId,
            'external_adset_id' => $externalId,
            'name' => $name,
            'copied_from' => $from,
            'destination_campaign_id' => $destinationExternal,
            'destination_name' => $campaign?->name,
            'ads' => $ads,
            'status' => $status,
            'paused' => $status !== 'ACTIVE',
            'pixel_id' => $pixelId !== '' ? $pixelId : null,
            'pixel_name' => $pixelName,
            'note' => $status === 'ACTIVE'
                ? 'The copy is on the platform and active, with the same targeting and the same ads. Say which campaign it went into.'
                : 'The copy is on the platform and paused, with the same targeting and the same ads. Say that it is not spending, and say which campaign it went into.',
        ]);
    }

    private function otherCampaignId(Campaign $campaign): ?string
    {
        $external = (string) $campaign->external_campaign_id;

        return $external !== '' && $external !== (string) ($this->focused()?->external_campaign_id ?? '')
            ? $external
            : null;
    }

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

        $query = Campaign::query()
            ->where('platform', 'meta')
            ->where('external_campaign_id', $externalId);

        if ($userId = auth()->id()) {
            $query->where('user_id', $userId);
        }

        return $query->first();
    }

    private function findSourceAdSet(Campaign $destination, string $adSetId): ?CampaignAdSet
    {
        $onDestination = $destination->adSets()
            ->where(function ($query) use ($adSetId): void {
                $query->where('external_adset_id', $adSetId);

                if (ctype_digit($adSetId)) {
                    $query->orWhere('id', $adSetId);
                }
            })
            ->first();

        if ($onDestination instanceof CampaignAdSet) {
            return $onDestination;
        }

        return CampaignAdSet::query()
            ->whereNotNull('external_adset_id')
            ->where(function ($query) use ($adSetId): void {
                $query->where('external_adset_id', $adSetId);

                if (ctype_digit($adSetId)) {
                    $query->orWhere('id', $adSetId);
                }
            })
            ->whereHas('campaign', function ($query) use ($destination): void {
                $query->where('platform', 'meta')->where('user_id', $destination->user_id);
            })
            ->first();
    }

    private function accountCampaign(?Campaign $focused): ?Campaign
    {
        if ($focused !== null && $focused->platform === 'meta' && filled($focused->ad_account_id)) {
            return $focused;
        }

        $userId = $focused?->user_id ?? auth()->id();

        if ($userId === null) {
            return null;
        }

        return Campaign::query()
            ->where('user_id', $userId)
            ->where('platform', 'meta')
            ->whereNotNull('ad_account_id')
            ->orderByDesc('id')
            ->first();
    }

    private function pixelAccessRefused(Throwable $exception): bool
    {
        $message = $exception->getMessage();

        return str_contains($message, '1815045')
            || str_contains(strtolower($message), 'does not have access to pixel');
    }

    /**
     * Pixels assigned to this ad account. A business-owned pixel that is not
     * assigned is what the copies endpoint just refused.
     *
     * @return list<array<string, mixed>>
     */
    private function accountPixels(Campaign $campaign, bool $fresh = false): array
    {
        return collect($this->meta->on($campaign->id, $this->actor->describe())->pixels((string) $campaign->ad_account_id, fresh: $fresh))
            ->filter(fn (array $pixel): bool => ($pixel['owned_by'] ?? null) === 'ad account' && filled($pixel['id'] ?? null))
            ->values()
            ->all();
    }

    private function pixelOnAccount(Campaign $campaign, string $pixelId): ?string
    {
        $pixel = collect($this->accountPixels($campaign, fresh: true))->firstWhere('id', $pixelId);

        return is_array($pixel) ? (string) ($pixel['name'] ?? $pixelId) : null;
    }

    private function offerReplacementPixel(Campaign $campaign, string $sourceExternalId, ?string $destinationExternalId = null): Stringable|string
    {
        try {
            $pixels = $this->accountPixels($campaign);
        } catch (MetaException $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The duplicate was not created. Say that plainly.',
            ]);
        }

        if ($pixels === []) {
            return $this->json([
                'ok' => false,
                'needs_pixel' => true,
                'ask' => 'This ad account has no pixel assigned to it, so the duplicate was not created. Assign a pixel to the ad account in Business Manager, then ask again.',
            ]);
        }

        $this->choices->offer(
            field: 'duplicate_ad_set_pixel',
            question: 'Which pixel should the duplicate ad set use?',
            options: array_map(fn (array $pixel): array => [
                'value' => $sourceExternalId.'|'.$pixel['id'].($destinationExternalId !== null ? '|'.$destinationExternalId : ''),
                'label' => (string) ($pixel['name'] ?? $pixel['id']),
                'hint' => isset($pixel['last_fired_time'])
                    ? 'last fired '.Carbon::parse($pixel['last_fired_time'])->diffForHumans()
                    : 'Assigned to this ad account',
                'sends' => 'Use the '.($pixel['name'] ?? $pixel['id']).' pixel.',
            ], $pixels),
        );

        return $this->json([
            'ok' => false,
            'needs_pixel' => true,
            'ask' => 'This ad account cannot use the pixel on that ad set. Choose a pixel below and the duplicate will be created with it.',
            'pixels' => array_map(fn (array $pixel): array => [
                'id' => (string) $pixel['id'],
                'name' => (string) ($pixel['name'] ?? $pixel['id']),
            ], $pixels),
        ]);
    }
}
