<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Targeting\GoogleUserListSelections;
use App\Campaigns\Targeting\LinkedInAudienceSelections;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Models\Campaign;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

class ChooseAudienceList implements Tool
{
    use ActsOnFocusedCampaign;

    public const CHANGE_AUDIENCE_MODE = 'change_audience_mode';

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly GoogleUserListSelections $audiences,
        private readonly MetaAudienceSelections $metaAudiences,
        private readonly LinkedInAudienceSelections $linkedinAudiences,
    ) {}

    public function description(): Stringable|string
    {
        return 'Discover Google Search remarketing lists, Meta website audiences, or LinkedIn retargeting segments and let the user choose an exact list '
            .'to include or exclude. Call without a resource name to show available and unavailable lists. '
            .'Use a resource name returned by that search and the latest targeting revision. '
            .'This does not upload customer data or create audience lists.';
    }

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

        $arguments = $request->all();
        $removing = ($arguments['operation'] ?? null) === 'remove';

        if ($campaign->platform === 'meta') {
            return $this->handleMeta($campaign, $arguments);
        }

        if ($campaign->platform === 'linkedin') {
            return $this->handleLinkedIn($campaign, $arguments);
        }

        if ($campaign->platform !== 'google' || $campaign->isPublished()
            || (($campaign->campaign_type ?: 'search') !== 'search' && ! $removing)) {
            return $this->json(['ok' => false, 'error' => 'Audience selection is available for draft Google Search campaigns only.']);
        }

        $revision = (int) ($campaign->targetingSet()->value('revision') ?? 0);

        try {
            if (blank($arguments['resource_name'] ?? null)) {
                $lists = $this->audiences->discover($campaign, isset($arguments['query']) ? (string) $arguments['query'] : null);
                $available = array_values(array_filter($lists, static fn (array $list): bool => $list['available']));
                $options = [];

                foreach (array_slice($available, 0, 30) as $list) {
                    foreach (['include', 'exclude'] as $operation) {
                        $options[] = [
                            'value' => $operation.'|'.$list['resource_name'],
                            'label' => ucfirst($operation).' '.$list['name'],
                            'hint' => $list['type'].' · '.$list['resource_name'],
                            'sends' => ucfirst($operation).' the Google audience list '.$list['name'].' ('.$list['resource_name'].').',
                        ];
                    }
                }

                $this->choices->offer('google_audience_list', 'Choose an account-owned Search remarketing list.', $options);

                return $this->json([
                    'ok' => true, 'revision' => $revision,
                    'selected' => $this->audiences->selected($campaign),
                    'lists' => $lists,
                ]);
            }

            if (! isset($arguments['expected_revision'])) {
                return $this->json(['ok' => false, 'error' => 'Review the current audience lists and provide their targeting revision.']);
            }

            $resourceName = (string) $arguments['resource_name'];
            $operation = (string) ($arguments['operation'] ?? 'include');

            if ($operation !== 'remove') {
                $offered = collect($this->workspace->pendingChoices())->first(
                    fn (array $choice): bool => ($choice['field'] ?? null) === 'google_audience_list'
                        && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey()
                );

                if ($offered === null || ! collect($offered['options'] ?? [])->contains(
                    fn (array $option): bool => ($option['value'] ?? null) === $operation.'|'.$resourceName
                )) {
                    return $this->json(['ok' => false, 'error' => 'Choose an audience from the current account list before saving it.']);
                }
            }

            $set = $operation === 'remove'
                ? $this->audiences->remove($campaign, $resourceName, (int) $arguments['expected_revision'])
                : $this->audiences->save($campaign, $resourceName, $operation, (int) $arguments['expected_revision']);

            return $this->json([
                'ok' => true,
                'revision' => $set->revision,
                'selected' => $removing
                    ? (array) ($set->options['google_user_lists'] ?? [])
                    : $this->audiences->selected($campaign),
            ]);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    /** @param  array<string, mixed>  $arguments */
    private function handleMeta(Campaign $campaign, array $arguments): string
    {
        if ($campaign->isPublished()) {
            return $this->json(['ok' => false, 'error' => 'Audience selection is available for draft Meta campaigns only.']);
        }

        $revision = (int) ($campaign->targetingSet()->value('revision') ?? 0);

        try {
            if (blank($arguments['resource_name'] ?? null)) {
                $lists = $this->metaAudiences->discover($campaign, isset($arguments['query']) ? (string) $arguments['query'] : null);
                $options = [];

                foreach (array_slice(array_values(array_filter($lists, static fn (array $list): bool => $list['available'])), 0, 30) as $list) {
                    foreach (['include', 'exclude'] as $operation) {
                        $options[] = [
                            'value' => $operation.'|'.$list['id'],
                            'label' => ucfirst($operation).' '.$list['name'],
                            'hint' => 'Meta website audience · ID '.$list['id'],
                            'sends' => ucfirst($operation).' Meta website audience '.$list['name'].' (ID '.$list['id'].').',
                        ];
                    }
                }

                $this->choices->offer('meta_audience_list', 'Choose an account-owned Meta website audience.', $options);

                return $this->json(['ok' => true, 'revision' => $revision, 'selected' => $this->metaAudiences->selected($campaign), 'lists' => $lists]);
            }

            if (! isset($arguments['expected_revision'])) {
                return $this->json(['ok' => false, 'error' => 'Review the current audience lists and provide their targeting revision.']);
            }

            $id = (string) $arguments['resource_name'];
            $operation = (string) ($arguments['operation'] ?? 'include');

            if ($operation !== 'remove') {
                $offered = collect($this->workspace->pendingChoices())->first(
                    fn (array $choice): bool => ($choice['field'] ?? null) === 'meta_audience_list'
                        && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey(),
                );

                if ($offered === null || ! collect($offered['options'] ?? [])->contains(
                    fn (array $option): bool => ($option['value'] ?? null) === $operation.'|'.$id,
                )) {
                    return $this->json(['ok' => false, 'error' => 'Choose an audience from the current account list before saving it.']);
                }
            }

            $set = $operation === 'remove'
                ? $this->metaAudiences->remove($campaign, $id, (int) $arguments['expected_revision'])
                : $this->metaAudiences->save($campaign, $id, $operation, (int) $arguments['expected_revision']);

            return $this->json([
                'ok' => true,
                'revision' => $set->revision,
                'selected' => (array) ($set->options['meta_audiences'] ?? []),
            ]);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    /** @param  array<string, mixed>  $arguments */
    private function handleLinkedIn(Campaign $campaign, array $arguments): string
    {
        if ($campaign->isPublished()) {
            return $this->json(['ok' => false, 'error' => 'Audience selection is available for draft LinkedIn campaigns only.']);
        }

        $revision = (int) ($campaign->targetingSet()->value('revision') ?? 0);

        try {
            if (blank($arguments['resource_name'] ?? null)) {
                $segments = $this->linkedinAudiences->discover($campaign, isset($arguments['query']) ? (string) $arguments['query'] : null);
                $options = [];

                foreach (array_slice($segments, 0, 30) as $segment) {
                    if (! $segment['available']) {
                        $options[] = [
                            'value' => 'unavailable|'.$segment['urn'],
                            'label' => $segment['name'],
                            'hint' => 'Unavailable: '.$segment['type'].' / '.$segment['status'],
                            'disabled' => true,
                        ];

                        continue;
                    }
                    foreach (['include', 'exclude'] as $operation) {
                        $options[] = [
                            'value' => $operation.'|'.$segment['urn'],
                            'label' => ucfirst($operation).' '.$segment['name'],
                            'hint' => 'LinkedIn retargeting · '.$segment['urn'],
                            'sends' => ucfirst($operation).' LinkedIn segment '.$segment['name'].' ('.$segment['urn'].').',
                        ];
                    }
                }

                $options[] = [
                    'value' => self::CHANGE_AUDIENCE_MODE,
                    'label' => 'Choose another audience',
                    'sends' => 'Show the LinkedIn audience refinement choices using choose_linked_in_resource with section audience and review_audience true. Keep my current targeting.',
                ];
                $this->choices->offer('linkedin_audience_segment', $segments === []
                    ? 'No retargeting segments were returned for this LinkedIn account.'
                    : 'Choose an account-owned LinkedIn retargeting segment. Unavailable segments cannot be selected.', $options);

                return $this->json([
                    'ok' => true, 'revision' => $revision,
                    'selected' => $this->linkedinAudiences->selected($campaign), 'segments' => $segments,
                ]);
            }

            if (! isset($arguments['expected_revision'])) {
                return $this->json(['ok' => false, 'error' => 'Review the current segments and provide their targeting revision.']);
            }

            $urn = (string) $arguments['resource_name'];
            $operation = (string) ($arguments['operation'] ?? 'include');

            if ($operation !== 'remove') {
                $offered = collect($this->workspace->pendingChoices())->first(
                    fn (array $choice): bool => ($choice['field'] ?? null) === 'linkedin_audience_segment'
                        && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey(),
                );

                if ($offered === null || ! collect($offered['options'] ?? [])->contains(
                    fn (array $option): bool => ($option['value'] ?? null) === $operation.'|'.$urn,
                )) {
                    return $this->json(['ok' => false, 'error' => 'Choose a segment from the current account list before saving it.']);
                }
            }

            $set = $operation === 'remove'
                ? $this->linkedinAudiences->remove($campaign, $urn, (int) $arguments['expected_revision'])
                : $this->linkedinAudiences->save($campaign, $urn, $operation, (int) $arguments['expected_revision']);

            $campaign->update(['meta' => [...(array) $campaign->meta,
                'linkedin_audience_reviewed' => ($set->options['linkedin_segments'] ?? []) !== []]]);

            return $this->json([
                'ok' => true, 'revision' => $set->revision,
                'selected' => (array) ($set->options['linkedin_segments'] ?? []),
            ]);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'resource_name' => $schema->string()->description('Exact Google user-list resource name, Meta audience ID, or LinkedIn segment URN from discovery; also used to remove a selection.'),
            'query' => $schema->string()->description('Optional 2–60 character audience-name search when listing account-owned lists.'),
            'operation' => $schema->string()->description('include, exclude, or remove.'),
            'expected_revision' => $schema->integer()->description('Targeting revision returned by the latest list review.'),
        ];
    }
}
