<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
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;
use Throwable;

/**
 * Detailed targeting on an ad set that is already live.
 *
 * Creation does not use this. A draft still searches interests through
 * set_targeting, and this list is not part of that step.
 */
class ListDetailedTargeting implements Tool
{
    use ActsOnFocusedCampaign;

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

    public function description(): Stringable|string
    {
        return 'List detailed targeting for an ad set that is already live, as buttons the user can tap. '
            .'With no query, offer a remove button for each saved interest, behavior, or demographic, and '
            .'add buttons for the related interests Meta suggests from those. '
            .'With a query, offer an add button for each search match. Nothing is saved here. After '
            .'a click, call edit_entity with targeting.flexible_spec as the complete list of what should '
            .'remain, using these ids, and leave out anything removed. Do not use this while creating a campaign.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_set' => $schema->string()
                ->description('The ad set id or its current name.')
                ->required(),
            'query' => $schema->string()
                ->description('Optional. Words to search, such as business administration. Omit to list what is already saved.'),
        ];
    }

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

        if ($campaign === null || $campaign->platform !== 'meta' || ! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'Detailed targeting is listed here only for an ad set that is already live. It is not part of creating a campaign.',
            ]);
        }

        $given = trim((string) ($request->all()['ad_set'] ?? ''));

        if ($given === '') {
            return $this->json(['ok' => false, 'error' => 'Name the ad set whose detailed targeting should be listed.']);
        }

        $resolved = $this->resolve($campaign, $given);

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

        try {
            $live = $this->meta->on($campaign->id, null)->readAdSet($resolved['id'], $campaign->ad_account_id);
        } catch (MetaException $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The saved detailed targeting could not be read, so nothing was changed.',
            ]);
        }

        $targeting = is_array($live['targeting'] ?? null) ? $live['targeting'] : [];
        $stored = $this->stored(is_array($targeting['flexible_spec'] ?? null) ? $targeting['flexible_spec'] : []);
        $query = trim((string) ($request->all()['query'] ?? ''));

        if ($query === '') {
            $suggestions = $this->suggestions((string) $campaign->ad_account_id, $stored);
            $this->offer($resolved['id'], $stored, $suggestions);

            return $this->json([
                'ok' => true,
                'ad_set_id' => $resolved['id'],
                'stored' => $stored,
                'matches' => $suggestions,
                'note' => 'Remove buttons are the saved items. Add buttons are Meta\'s suggestions. Wait for a click. Do not ask the user to type a name. Nothing has been saved.',
            ]);
        }

        try {
            $matches = $this->matches((string) $campaign->ad_account_id, $query);
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'stored' => $stored,
                'note' => 'The search could not be read. The saved list is unchanged.',
            ]);
        }

        $this->offer($resolved['id'], $stored, $matches);

        return $this->json([
            'ok' => true,
            'ad_set_id' => $resolved['id'],
            'stored' => $stored,
            'matches' => $matches,
            'note' => $matches === []
                ? 'Meta has no detailed targeting matching that name. Say so and do not invent an id.'
                : 'Add and remove buttons are on screen. Wait for a click. Do not ask the user to type a name. Then call edit_entity with the complete flexible_spec of what should remain.',
        ]);
    }

    /**
     * @param  list<array{id: string, name: string, type: string}>  $stored
     * @param  list<array{id: string, name: string, type: string}>  $matches
     */
    private function offer(string $adSetId, array $stored, array $matches): void
    {
        $storedIds = array_column($stored, 'id');
        $options = [];

        foreach ($stored as $item) {
            $options[] = [
                'value' => 'remove:'.$item['id'],
                'label' => 'Remove '.$item['name'],
                'hint' => $item['type'].' · id '.$item['id'],
                'badge' => 'Saved',
                'sends' => sprintf(
                    'On ad set %s, remove detailed targeting %s (%s id %s). Keep every other detailed targeting item.',
                    $adSetId,
                    $item['name'],
                    $item['type'],
                    $item['id'],
                ),
            ];
        }

        foreach ($matches as $item) {
            if (in_array($item['id'], $storedIds, true)) {
                continue;
            }

            $options[] = [
                'value' => 'add:'.$item['id'],
                'label' => 'Add '.$item['name'],
                'hint' => $item['type'].' · id '.$item['id'],
                'badge' => 'Add',
                'sends' => sprintf(
                    'On ad set %s, add detailed targeting %s (%s id %s). Keep every other detailed targeting item.',
                    $adSetId,
                    $item['name'],
                    $item['type'],
                    $item['id'],
                ),
            ];
        }

        $this->choices->offer(
            'live_detailed_targeting',
            'Which detailed targeting should change?',
            $options,
            multiple: true,
            allowOther: true,
            otherLabel: 'Search',
            otherHint: 'Search Meta for an interest that is not listed.',
            otherPlaceholder: 'stock trading',
        );
    }

    /**
     * @return array{id: string, name: ?string}|array{error: string}
     */
    private function resolve(Campaign $campaign, string $given): array
    {
        try {
            $rows = $this->meta->on($campaign->id, null)
                ->adSets((string) $campaign->external_campaign_id, $campaign->ad_account_id, fresh: true);
        } catch (Throwable $exception) {
            return ['error' => 'The ad sets could not be read, so nothing was changed. '.$exception->getMessage()];
        }

        foreach ($rows as $row) {
            if ((string) ($row['id'] ?? '') === $given) {
                $name = trim((string) ($row['name'] ?? ''));

                return ['id' => $given, 'name' => $name !== '' ? $name : null];
            }
        }

        $matches = array_values(array_filter(
            $rows,
            static fn (array $row): bool => strcasecmp(trim((string) ($row['name'] ?? '')), $given) === 0,
        ));

        if (count($matches) === 1) {
            return ['id' => (string) $matches[0]['id'], 'name' => trim((string) ($matches[0]['name'] ?? $given))];
        }

        if ($matches !== []) {
            return ['error' => 'More than one ad set is named '.$given.'. Nothing was changed.'];
        }

        return ['error' => $given.' is not an ad set id or name in this campaign, so nothing was changed.'];
    }

    /**
     * @param  list<mixed>  $spec
     * @return list<array{id: string, name: string, type: string}>
     */
    private function stored(array $spec): array
    {
        $items = [];

        foreach ($spec as $group) {
            if (! is_array($group)) {
                continue;
            }

            foreach ($group as $type => $rows) {
                if (! is_array($rows) || is_int($type)) {
                    continue;
                }

                foreach ($rows as $row) {
                    if (! is_array($row)) {
                        continue;
                    }

                    $id = trim((string) ($row['id'] ?? ''));
                    $name = trim((string) ($row['name'] ?? ''));

                    if ($id === '' || $name === '') {
                        continue;
                    }

                    $items[] = ['id' => $id, 'name' => $name, 'type' => (string) $type];
                }
            }
        }

        return $items;
    }

    /**
     * Related interests Meta suggests from what the ad set already saves.
     *
     * A failed suggestion still leaves the saved items on screen.
     *
     * @param  list<array{id: string, name: string, type: string}>  $stored
     * @return list<array{id: string, name: string, type: string}>
     */
    private function suggestions(string $adAccountId, array $stored): array
    {
        $names = [];

        foreach (array_slice($stored, 0, 10) as $item) {
            if ($item['type'] === 'interests' && $item['name'] !== '') {
                $names[] = $item['name'];
            }
        }

        if ($names === []) {
            return [];
        }

        try {
            $rows = $this->meta->adInterestSuggestions($adAccountId, $names);
        } catch (Throwable) {
            return [];
        }

        return $this->ranked($rows, 'interests', array_column($stored, 'id'));
    }

    /**
     * Interests first, then job titles. A behavior that does not match the words is not a result.
     *
     * @return list<array{id: string, name: string, type: string}>
     */
    private function matches(string $adAccountId, string $query): array
    {
        $interests = [];

        foreach ($this->interestQueries($query) as $term) {
            try {
                $found = $this->relevant($this->meta->adInterests($adAccountId, $term), $query);
            } catch (Throwable) {
                $found = [];
            }

            $interests = $this->merge($interests, $found);

            if ($interests !== [] && $term === $this->normalized($query)) {
                break;
            }
        }

        $jobs = [];

        foreach ($this->words($query) as $term) {
            try {
                $found = $this->relevant($this->meta->adWorkPositions($adAccountId, $term), $query);
            } catch (Throwable) {
                $found = [];
            }

            $jobs = $this->merge($jobs, $found);
        }

        return array_merge(
            $this->ranked($interests, 'interests'),
            $this->ranked($jobs, 'work_positions'),
        );
    }

    /**
     * The typed phrase, then each word, then a wider investing search when the phrase is about stock.
     *
     * @return list<string>
     */
    private function interestQueries(string $query): array
    {
        $words = $this->words($query);
        $queries = array_merge([$this->normalized($query)], $words);

        if (in_array('stock', $words, true)) {
            $queries[] = 'stock market';
            $queries[] = 'investing';
        }

        $unique = [];

        foreach ($queries as $term) {
            if ($term !== '' && ! in_array($term, $unique, true)) {
                $unique[] = $term;
            }
        }

        return $unique;
    }

    /** @return list<string> */
    private function words(string $query): array
    {
        $words = [];

        foreach (explode(' ', $this->normalized($query)) as $word) {
            if (mb_strlen($word) >= 3 && ! in_array($word, $words, true)) {
                $words[] = $word;
            }
        }

        return $words;
    }

    private function normalized(string $query): string
    {
        return mb_strtolower(trim((string) preg_replace('/\s+/u', ' ', $query)));
    }

    /**
     * @param  list<array{id: string, name: string, audience_size: int}>  $rows
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    private function relevant(array $rows, string $query): array
    {
        $words = $this->words($query);

        return array_values(array_filter($rows, function (array $row) use ($words): bool {
            $name = mb_strtolower($row['name']);

            foreach ($words as $word) {
                if (str_contains($name, $word)) {
                    return true;
                }
            }

            return false;
        }));
    }

    /**
     * @param  list<array{id: string, name: string, audience_size: int}>  $current
     * @param  list<array{id: string, name: string, audience_size: int}>  $more
     * @return list<array{id: string, name: string, audience_size: int}>
     */
    private function merge(array $current, array $more): array
    {
        $seen = array_column($current, 'id');

        foreach ($more as $row) {
            if (! in_array($row['id'], $seen, true)) {
                $current[] = $row;
                $seen[] = $row['id'];
            }
        }

        return $current;
    }

    /**
     * @param  list<array{id: string, name: string, audience_size: int}>  $rows
     * @param  list<string>  $skipIds
     * @return list<array{id: string, name: string, type: string}>
     */
    private function ranked(array $rows, string $type, array $skipIds = []): array
    {
        usort($rows, static fn (array $left, array $right): int => $right['audience_size'] <=> $left['audience_size']);

        $items = [];

        foreach (array_slice($rows, 0, 15) as $row) {
            if (in_array($row['id'], $skipIds, true)) {
                continue;
            }

            $items[] = ['id' => $row['id'], 'name' => $row['name'], 'type' => $type];
        }

        return $items;
    }
}
