<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * The verified advertiser Meta requires on an ad set for some accounts.
 *
 * The Ads Manager dropdown is a list of verified-identity ids. Meta does not
 * offer that list on the ad account, so the ids are read from ad sets that
 * already have one saved. The display name is kept beside the id. Sending the
 * name alone is what Meta refuses with subcode 3858634.
 */
class ChooseVerifiedAdvertiser implements Tool
{
    use ActsOnFocusedCampaign;

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

    public function description(): Stringable|string
    {
        return 'Offer the verified advertisers already saved on this Meta ad account and set the one the ads use. '
            .'Call it with no identity to show the choices. Pass identity as the chosen id. '
            .'Do not invent an id or a name. A display name is not accepted. '
            .'When none are on file, an ad set must be saved in Ads Manager with the advertiser selected.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'identity' => $schema->string()
                ->description('The verified advertiser id, exactly as offered. Not the display name.'),
        ];
    }

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

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

        if ($campaign->platform !== 'meta') {
            return $this->json([
                'ok' => false,
                'error' => 'A verified advertiser is only required for a Meta campaign.',
                'note' => 'Do not ask about this. Move on.',
            ]);
        }

        if (blank($campaign->ad_account_id)) {
            return $this->json([
                'ok' => false,
                'error' => 'Choose the ad account first. The verified advertiser belongs to that account.',
            ]);
        }

        try {
            $identities = $this->meta->on($campaign->id, null)->verifiedAdvertiserIdentities((string) $campaign->ad_account_id);
        } catch (MetaException $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'This is a platform error. Do not invent an advertiser.',
            ]);
        }

        $arguments = $request->all();

        if (! array_key_exists('identity', $arguments)) {
            return $this->offer($campaign, $identities);
        }

        $chosen = trim((string) $arguments['identity']);
        $match = $this->match($identities, $chosen);

        if ($match === null) {
            return $this->json([
                'ok' => false,
                'error' => 'Choose one of the verified advertisers already saved on this ad account.',
                'advertisers' => array_map(fn (array $identity): string => $this->label($identity), $identities),
            ]);
        }

        $this->store($campaign, $match);

        return $this->json([
            'ok' => true,
            'advertiser' => $this->label($match),
            'identity' => $match['beneficiary_id'],
            'note' => 'The ads will use '.$this->label($match).' as the verified advertiser. Say that in one line.',
        ]);
    }

    /**
     * @param  list<array{beneficiary_id: string, payer_id: string, beneficiary_name: string, payer_name: string, categories: list<string>}>  $identities
     */
    private function offer(Campaign $campaign, array $identities): Stringable|string
    {
        if ($identities === []) {
            if (($campaign->meta['verified_advertiser_required'] ?? false) === true
                || str_contains((string) $campaign->last_error, '3858634')) {
                return $this->json([
                    'ok' => false,
                    'error' => 'This ad account has no saved verified-advertiser id to choose.',
                    'note' => 'Say that the advertiser has to be selected on an ad set in Ads Manager and that ad set saved, so the id can be read. Do not invent an id or a name.',
                ]);
            }

            $this->remember($campaign, [
                'verified_advertiser_status' => 'not_required',
            ]);

            return $this->json([
                'ok' => true,
                'advertisers' => [],
                'note' => 'This account has no verified advertiser on file. Do not ask. Move on.',
            ]);
        }

        $this->choices->offer(
            field: 'verified_advertiser',
            question: 'Which verified advertiser should these ads use?',
            options: array_map(fn (array $identity): array => [
                'value' => $identity['beneficiary_id'].'|'.$identity['payer_id'],
                'label' => $this->label($identity),
                'hint' => 'ID '.$identity['beneficiary_id'],
                'sends' => 'Use verified advertiser '.$identity['beneficiary_id'],
            ], $identities),
        );

        return $this->json([
            'ok' => true,
            'offered' => array_map(fn (array $identity): string => $this->label($identity), $identities),
            'note' => 'The choice is on screen. Say one short line and wait; do not restate the options.',
        ]);
    }

    /**
     * @param  list<array{beneficiary_id: string, payer_id: string, beneficiary_name: string, payer_name: string, categories: list<string>}>  $identities
     * @return array{beneficiary_id: string, payer_id: string, beneficiary_name: string, payer_name: string, categories: list<string>}|null
     */
    private function match(array $identities, string $chosen): ?array
    {
        foreach ($identities as $identity) {
            $pair = $identity['beneficiary_id'].'|'.$identity['payer_id'];

            if ($chosen === $pair || $chosen === $identity['beneficiary_id']) {
                return $identity;
            }
        }

        return null;
    }

    /**
     * @param  array{beneficiary_id: string, payer_id: string, beneficiary_name: string, payer_name: string, categories: list<string>}  $identity
     */
    private function label(array $identity): string
    {
        $name = $identity['beneficiary_name'] !== '' ? $identity['beneficiary_name'] : 'Verified advertiser';

        if ($identity['payer_name'] !== '' && $identity['payer_name'] !== $identity['beneficiary_name']) {
            $name .= ' / '.$identity['payer_name'];
        }

        return $name.' · '.$identity['beneficiary_id'];
    }

    /**
     * @param  array{beneficiary_id: string, payer_id: string, beneficiary_name: string, payer_name: string, categories: list<string>}  $identity
     */
    private function store(Campaign $campaign, array $identity): void
    {
        $values = [
            'universal_beneficiary' => $identity['beneficiary_id'],
            'universal_payer' => $identity['payer_id'],
            'regional_regulated_categories' => $identity['categories'],
            'verified_advertiser_status' => 'chosen',
        ];

        if ($identity['beneficiary_name'] !== '') {
            $values['dsa_beneficiary'] = $identity['beneficiary_name'];
        }

        $payerName = $identity['payer_name'] !== '' ? $identity['payer_name'] : $identity['beneficiary_name'];

        if ($payerName !== '') {
            $values['dsa_payor'] = $payerName;
        }

        $this->remember($campaign, $values);
        $this->workspace->recordSource($campaign->fresh(), 'verified_advertiser', ArtifactFieldSource::USER_STATED);
    }

    /**
     * @param  array<string, mixed>  $values
     */
    private function remember(Campaign $campaign, array $values): void
    {
        $meta = (array) ($campaign->meta ?? []);
        unset($meta['verified_advertiser_status']);

        $campaign->forceFill(['meta' => [...$meta, ...$values]])->save();
    }
}
