<?php

namespace App\Agent\Tools\Campaign;

use App\Services\LinkedIn\LinkedIn;
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 campaigns on an ad account, whoever built them.
 *
 * The product used to see only what it had made itself, which is a small
 * fraction of what anyone works on. This is how someone finds the campaign
 * they mean.
 *
 * Read only.
 */
class ListCampaigns implements Tool
{
    public function __construct(private readonly Meta $meta, private readonly ?LinkedIn $linkedin = null) {}

    public function description(): Stringable|string
    {
        return 'List the campaigns on a Meta or LinkedIn ad account, including ones not built here. Use it '
            .'when the user asks what is on an account, or names a campaign you do not have.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'platform' => $schema->string()->enum(['meta', 'linkedin'])->description('Platform; defaults to Meta.'),
            'page_token' => $schema->string()->description('LinkedIn next_page_token from the previous result.'),
            'campaign_group_id' => $schema->string()->description('Optional LinkedIn group ID to filter campaigns.'),
            'ad_account_id' => $schema->string()
                ->description('The ad account to look in, for example act_123456789.')
                ->required(),
            'search' => $schema->string()
                ->description('Optional text to match against the campaign name.'),
            'campaign_ids' => $schema->array()->items($schema->string())
                ->description('Meta campaign IDs whose name and objective should be read from this ad account. Use this when the user asks for the name or objective of specific campaigns.'),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        $arguments = $request->all();
        $adAccountId = trim((string) ($arguments['ad_account_id'] ?? ''));
        $search = trim((string) ($arguments['search'] ?? ''));

        if ($adAccountId === '') {
            return 'error: an ad account id is needed. Call list_ad_accounts first.';
        }

        $campaignIds = $this->campaignIds($arguments['campaign_ids'] ?? []);

        if ($campaignIds !== [] && ($arguments['platform'] ?? 'meta') !== 'linkedin') {
            return $this->lookup($adAccountId, $campaignIds);
        }

        if (($arguments['platform'] ?? 'meta') === 'linkedin') {
            try {
                $page = ($this->linkedin ?? app(LinkedIn::class))->campaigns(
                    $adAccountId, $arguments['page_token'] ?? null, $arguments['campaign_group_id'] ?? null,
                );
                $page['elements'] = array_values(array_filter($page['elements'], fn (array $row): bool => ! in_array($row['status'] ?? null, ['PENDING_DELETION', 'REMOVED', 'CANCELED'], true)
                    && ($search === '' || str_contains(mb_strtolower((string) ($row['name'] ?? '')), mb_strtolower($search)))));

                return json_encode(['ok' => true, 'platform' => 'linkedin', 'ad_account_id' => $adAccountId,
                    'refreshed_at' => now()->toIso8601String(), ...$page], JSON_THROW_ON_ERROR);
            } catch (\Throwable $exception) {
                return json_encode(['ok' => false, 'error' => $exception->getMessage()], JSON_THROW_ON_ERROR);
            }
        }

        try {
            $campaigns = collect($this->meta->campaigns($adAccountId));
        } catch (MetaException $e) {
            return 'error: could not read that account: '.$e->getMessage();
        }

        if ($search !== '') {
            $campaigns = $campaigns->filter(
                fn (array $c): bool => str_contains(mb_strtolower((string) ($c['name'] ?? '')), mb_strtolower($search))
            );
        }

        if ($campaigns->isEmpty()) {
            return $search === ''
                ? "No campaigns on {$adAccountId}."
                : "No campaigns on {$adAccountId} matching \"{$search}\".";
        }

        // Capped because an account can hold hundreds and the whole list is
        // neither readable nor useful in a chat reply.
        $shown = $campaigns->take(25);

        return "Campaigns on {$adAccountId}:\n".$shown
            ->map(fn (array $c): string => sprintf(
                '- %s: %s (%s%s)',
                $c['id'] ?? '?',
                $c['name'] ?? 'untitled',
                strtolower((string) ($c['status'] ?? 'unknown')),
                isset($c['objective']) ? ', '.$c['objective'] : '',
            ))
            ->implode("\n")
            .($campaigns->count() > $shown->count()
                ? sprintf("\n\n%d more not shown. Narrow it with search.", $campaigns->count() - $shown->count())
                : '')
            ."\n\nOpen one with open_campaign to edit it.";
    }

    /**
     * Name and objective for the campaigns the buyer named.
     *
     * The account list is capped, so an ID the buyer pasted is often not on
     * the first page. Reading each ID from Meta is the lookup they asked for.
     *
     * @param  list<string>  $campaignIds
     */
    private function lookup(string $adAccountId, array $campaignIds): string
    {
        $account = preg_replace('/^act_/', '', $adAccountId) ?? '';
        $lines = [];

        foreach ($campaignIds as $campaignId) {
            try {
                $campaign = $this->meta->campaign($campaignId, $adAccountId);
            } catch (MetaException $exception) {
                $lines[] = "- {$campaignId}: unavailable on {$adAccountId} ({$exception->getMessage()})";

                continue;
            }

            $owner = preg_replace('/^act_/', '', (string) ($campaign['account_id'] ?? '')) ?? '';

            if ($owner !== '' && $owner !== $account) {
                $lines[] = "- {$campaignId}: not on {$adAccountId}";

                continue;
            }

            $lines[] = sprintf(
                '- %s: %s (%s, %s)',
                $campaign['id'] ?? $campaignId,
                $campaign['name'] ?? 'untitled',
                strtolower((string) ($campaign['status'] ?? 'unknown')),
                $campaign['objective'] ?? 'no objective',
            );
        }

        return "Campaigns on {$adAccountId}:\n".implode("\n", $lines);
    }

    /**
     * @return list<string>
     */
    private function campaignIds(mixed $ids): array
    {
        $found = [];

        foreach (array_slice((array) $ids, 0, 10) as $id) {
            $id = preg_replace('/\D/', '', (string) $id) ?? '';

            if (preg_match('/^[0-9]{8,20}$/D', $id) === 1) {
                $found[] = $id;
            }
        }

        return array_values(array_unique($found));
    }
}
