<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Models\Campaign;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Str;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

/** Final choice cards use the shared approval binding; discovery remains read-only. */
class CreateWebsiteAudience implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly Meta $meta,
        private readonly MetaAudienceSelections $audiences,
        private readonly DuplicateCampaign $duplicateCampaign,
        private readonly CampaignApprovalBinding $approvalBinding,
    ) {}

    public function description(): Stringable|string
    {
        return 'Create a Meta website retargeting audience from a pixel event actually observed on the selected account. '
            .'Offer the account pixels, then observed events, then a review with a retention window. Create nothing until '
            .'the user selects a final confirmation. The user may attach it to this draft or create a separate retargeting draft. '
            .'Never publish either campaign.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'pixel_id' => $schema->string()->description('Pixel ID returned by the current account pixel list.'),
            'event_name' => $schema->string()->description('Exact event name returned by the selected pixel event history.'),
            'retention_days' => $schema->integer()->description('Audience retention in days, from 1 through 180. Defaults to 30.'),
            'name' => $schema->string()->description('Optional audience name. Defaults to the campaign and selected event.'),
            'confirm_action' => $schema->string()->description('Confirmation choice returned by the review card. Never invent this value.'),
        ];
    }

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

        if ($campaign->platform !== 'meta' || (array) ($campaign->special_ad_categories ?? []) !== ['NONE']) {
            return $this->json(['ok' => false, 'error' => 'Website retargeting audiences are available only for Meta campaigns declared outside special ad categories.']);
        }

        if (blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Choose a Meta ad account before creating a website audience.']);
        }

        if ((array) ($campaign->locations['countries'] ?? []) === []) {
            return $this->json(['ok' => false, 'error' => 'Choose the countries for the retargeting campaign before creating its audience.']);
        }

        $arguments = $request->all();

        if (filled($arguments['confirm_action'] ?? null)) {
            return $this->confirm($campaign, (string) $arguments['confirm_action']);
        }

        $pixelId = trim((string) ($arguments['pixel_id'] ?? ''));

        if ($pixelId === '') {
            return $this->offerPixels($campaign, $arguments);
        }

        if (! $this->pixelBelongsToAccount($campaign, $pixelId)) {
            return $this->json(['ok' => false, 'error' => 'Choose a pixel from the selected Meta ad account.']);
        }

        $eventName = trim((string) ($arguments['event_name'] ?? ''));

        if ($eventName === '') {
            return $this->offerEvents($campaign, $pixelId);
        }

        $retentionDays = (int) ($arguments['retention_days'] ?? 30);

        if ($retentionDays < 1 || $retentionDays > 180) {
            return $this->json(['ok' => false, 'error' => 'Choose a retention window between 1 and 180 days.']);
        }

        try {
            $events = $this->meta->pixelEvents($pixelId);
        } catch (MetaException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        if (! array_key_exists($eventName, $events)) {
            return $this->json(['ok' => false, 'error' => 'Choose an event this pixel has actually recorded.']);
        }

        return $this->offerConfirmation($campaign, [
            'pixel_id' => $pixelId,
            'event_name' => $eventName,
            'retention_days' => $retentionDays,
            'name' => trim((string) ($arguments['name'] ?? '')) ?: $this->audienceName($campaign, $eventName, $retentionDays),
        ]);
    }

    /** @param array<string, mixed> $carried */
    private function offerPixels(Campaign $campaign, array $carried): string
    {
        try {
            $pixels = $this->meta->pixels((string) $campaign->ad_account_id);
        } catch (MetaException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $options = [];

        foreach (array_slice($pixels, 0, 30) as $pixel) {
            $id = (string) ($pixel['id'] ?? '');

            if (! preg_match('/^[0-9]+$/D', $id)) {
                continue;
            }

            $options[] = [
                'value' => $id,
                'label' => (string) ($pixel['name'] ?? 'Meta pixel'),
                'hint' => $id === (string) $campaign->pixel_id ? 'Selected for this campaign' : 'Account pixel',
                'badge' => $id === (string) $campaign->pixel_id ? 'Selected' : null,
                'sends' => 'Use the Meta pixel '.(string) ($pixel['name'] ?? $id).' for a retargeting audience.',
                'arguments' => array_filter([
                    'event_name' => filled($carried['event_name'] ?? null) ? (string) $carried['event_name'] : null,
                    'retention_days' => isset($carried['retention_days']) ? (int) $carried['retention_days'] : 30,
                    'name' => filled($carried['name'] ?? null) ? (string) $carried['name'] : null,
                ], static fn (mixed $value): bool => $value !== null),
            ];
        }

        if ($options === []) {
            return $this->json(['ok' => false, 'error' => 'No Meta pixels are available on this account. Install or select a pixel before building a website audience.']);
        }

        $this->choices->offer(
            field: 'meta_retarget_pixel',
            question: 'Which account pixel should define the retargeting audience?',
            options: $options,
        );

        return $this->json(['ok' => true, 'pixels' => count($options), 'note' => 'Pixel choices are on screen. Wait for the user.']);
    }

    private function offerEvents(Campaign $campaign, string $pixelId): string
    {
        try {
            $events = $this->meta->pixelEvents($pixelId);
        } catch (MetaException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        if ($events === []) {
            return $this->json(['ok' => false, 'error' => 'This pixel has no recorded events in the last 30 days, so there is no event to build an audience from yet.']);
        }

        $options = [];

        foreach (array_slice($events, 0, 30, true) as $event => $count) {
            $event = (string) $event;
            $options[] = [
                'value' => $event,
                'label' => $event,
                'hint' => number_format((int) $count).' events · last 30 days',
                'sends' => 'Build a website audience from people who fired '.$event.' in the last 30 days.',
                'arguments' => [
                    'pixel_id' => $pixelId,
                    'event_name' => $event,
                    'retention_days' => 30,
                    'name' => $this->audienceName($campaign, $event, 30),
                ],
            ];
        }

        $this->choices->offer(
            field: 'meta_retarget_event',
            question: 'Choose an event this pixel has recorded.',
            options: $options,
        );

        return $this->json(['ok' => true, 'events' => count($options), 'note' => 'Only events recorded by this pixel are shown. The default retention is 30 days.']);
    }

    /** @param array{pixel_id: string, event_name: string, retention_days: int, name: string} $details */
    private function offerConfirmation(Campaign $campaign, array $details): string
    {
        $label = $details['event_name'].' · '.$details['retention_days'].' days';
        $options = [];

        if (! $campaign->isPublished()) {
            $options[] = [
                'value' => 'use_current',
                'label' => 'Create and use in this campaign',
                'hint' => 'Adds the audience to this draft campaign.',
                'sends' => 'Create and use the '.$label.' audience in this campaign.',
                'arguments' => $details,
            ];
        }

        $options[] = [
            'value' => 'new_draft',
            'label' => 'Create a separate retargeting draft',
            'hint' => 'Copies this campaign into a separate draft; nothing is published.',
            'sends' => 'Create the '.$label.' website audience and a separate retargeting draft based on this campaign.',
            'arguments' => $details,
        ];

        foreach ($options as &$option) {
            $callId = 'website-audience-'.Str::uuid();
            $this->approvalBinding->request(
                new Request($details, toolCallId: $callId),
                $campaign,
                'create_website_audience_'.$option['value'],
                $details,
            );
            $option['arguments']['approval_call_id'] = $callId;
        }
        unset($option);

        $this->choices->offer(
            field: 'meta_retarget_confirmation',
            question: 'Review the website audience before creating it.',
            options: $options,
        );

        return $this->json([
            'ok' => true,
            'review' => [
                'name' => $details['name'],
                'pixel_id' => $details['pixel_id'],
                'event' => $details['event_name'],
                'retention_days' => $details['retention_days'],
            ],
            'note' => 'The website audience is not created yet. Explain the event and retention window, then wait for the user to confirm one option.',
        ]);
    }

    private function confirm(Campaign $campaign, string $action): string
    {
        $choice = collect($this->workspace->pendingChoices())->first(fn (array $offered): bool => ($offered['field'] ?? null) === 'meta_retarget_confirmation'
            && (string) ($offered['focus_id'] ?? '') === (string) $campaign->getKey());
        $option = collect($choice['options'] ?? [])->firstWhere('value', $action);
        $details = is_array($option['arguments'] ?? null) ? $option['arguments'] : null;

        if ($details === null || ! isset($details['pixel_id'], $details['event_name'], $details['retention_days'], $details['name'])
            || ! in_array($action, ['use_current', 'new_draft'], true)) {
            return $this->json(['ok' => false, 'error' => 'Review the current pixel event and audience details before creating it.']);
        }

        if ($action === 'use_current' && $campaign->isPublished()) {
            return $this->json(['ok' => false, 'error' => 'A published campaign cannot be retargeted in place. Choose a separate draft.']);
        }

        $reviewedDetails = array_intersect_key($details, array_flip(['pixel_id', 'event_name', 'retention_days', 'name']));
        $approvedCampaign = $this->approvalBinding->consume(
            new Request($reviewedDetails, toolCallId: (string) ($details['approval_call_id'] ?? '')),
            'create_website_audience_'.$action,
            $reviewedDetails,
        );

        if ($approvedCampaign === null || ! $approvedCampaign->is($campaign)) {
            return $this->json(['ok' => false, 'error' => 'The audience confirmation expired, was already used, or its campaign or details changed. Review it again.']);
        }

        $pixelId = (string) $details['pixel_id'];
        $eventName = (string) $details['event_name'];
        $retentionDays = (int) $details['retention_days'];

        if (! $this->pixelBelongsToAccount($campaign, $pixelId) || $retentionDays < 1 || $retentionDays > 180) {
            return $this->json(['ok' => false, 'error' => 'The reviewed pixel or retention window changed. Start the review again.']);
        }

        try {
            $events = $this->meta->pixelEvents($pixelId);

            if (! array_key_exists($eventName, $events)) {
                return $this->json(['ok' => false, 'error' => 'The selected event is no longer present in this pixel history. Review the current events again.']);
            }
        } catch (MetaException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        try {
            $created = $this->meta->createWebsiteAudience(
                (string) $campaign->ad_account_id,
                (string) $details['name'],
                $pixelId,
                $eventName,
                $retentionDays,
            );
        } catch (MetaException|RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $audienceId = (string) ($created['id'] ?? '');

        if (! preg_match('/^[0-9]+$/D', $audienceId)) {
            return $this->json(['ok' => false, 'error' => 'Meta returned no audience ID. The audience could not be attached to a campaign.']);
        }

        $target = $campaign;
        $draft = null;

        if ($action === 'new_draft') {
            $name = mb_substr(trim($campaign->name).' - Retargeting', 0, 255);
            $duplicate = json_decode((string) $this->duplicateCampaign->handle(new Request([
                'campaign_id' => $campaign->getKey(),
                'name' => $name,
            ])), true);

            if (! is_array($duplicate) || ($duplicate['ok'] ?? false) !== true) {
                return $this->json(['ok' => false, 'audience_created' => true, 'audience_id' => $audienceId,
                    'error' => (string) ($duplicate['error'] ?? 'The retargeting draft could not be created.')]);
            }

            $target = Campaign::query()->find((int) $duplicate['campaign_id']);
            $draft = $duplicate;

            if (! $target) {
                return $this->json(['ok' => false, 'audience_created' => true, 'audience_id' => $audienceId,
                    'error' => 'The new retargeting draft could not be loaded.']);
            }
        }

        try {
            $this->audiences->recordCreated($target, $audienceId, (string) $details['name'], $pixelId);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'audience_created' => true, 'audience_id' => $audienceId,
                'campaign_id' => $target->getKey(), 'error' => $exception->getMessage()]);
        }

        return $this->json([
            'ok' => true,
            'created' => true,
            'audience' => ['id' => $audienceId, 'name' => $details['name'], 'event' => $eventName,
                'retention_days' => $retentionDays, 'pixel_id' => $pixelId],
            'campaign_id' => $target->getKey(),
            'retargeting_draft' => $draft,
            'note' => 'The audience was created and attached to a draft campaign. Meta may need time to populate it. The campaign remains a draft and still requires review and approval before publishing.',
        ]);
    }

    private function pixelBelongsToAccount(Campaign $campaign, string $pixelId): bool
    {
        if (! preg_match('/^[0-9]+$/D', $pixelId)) {
            return false;
        }

        try {
            return collect($this->meta->pixels((string) $campaign->ad_account_id, fresh: true))
                ->contains(fn (array $pixel): bool => (string) ($pixel['id'] ?? '') === $pixelId);
        } catch (MetaException) {
            return false;
        }
    }

    private function audienceName(Campaign $campaign, string $eventName, int $retentionDays): string
    {
        return mb_substr(trim($campaign->name).' - '.$eventName.' ('.$retentionDays.' days)', 0, 255);
    }
}
