<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
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 custom audiences on the ad account, for an ad set that is already live.
 *
 * Creation does not use this. A draft still chooses its audience through
 * choose_audience_list, and this list is not part of that step.
 */
class ListCustomAudiences implements Tool
{
    use ActsOnFocusedCampaign;

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

    public function description(): Stringable|string
    {
        return 'List the custom audiences on the ad account, when the user asks for them on a campaign '
            .'that is already live. Show the returned names and ids and wait for the user to choose. '
            .'Then call edit_entity with that id in targeting.custom_audiences, and keep the audiences '
            .'already on the ad set. Do not invent an id. Do not use this while creating a campaign.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'query' => $schema->string()
                ->description('Optional. A name to narrow the list, such as stockprices-visitors. Omit to list the account.'),
        ];
    }

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

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

        if (! filled($campaign->ad_account_id)) {
            return $this->json([
                'ok' => false,
                'error' => 'This campaign has no ad account, so its audiences could not be listed.',
            ]);
        }

        try {
            $rows = $this->meta->on($campaign->id, null)
                ->customAudiences((string) $campaign->ad_account_id, fresh: true);
        } catch (MetaException $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The ad account audience list could not be read, so nothing was changed.',
            ]);
        }

        $query = trim((string) ($request->all()['query'] ?? ''));
        $audiences = [];

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

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

            if ($query !== '' && ! str_contains(strtolower($name), strtolower($query))) {
                continue;
            }

            $audiences[] = [
                'id' => $id,
                'name' => $name,
                'subtype' => (string) ($row['subtype'] ?? ''),
            ];
        }

        $shown = array_slice($audiences, 0, 50);

        return $this->json([
            'ok' => true,
            'audiences' => $shown,
            'note' => $shown === []
                ? 'This ad account has no custom audience matching that request. Say so and do not invent an id.'
                : 'Show these audience names and ids and wait for the user to choose. Then call edit_entity with the chosen id. Do not pick one yourself when more than one is returned.'
                    .(count($audiences) > count($shown) ? ' More audiences exist than are shown.' : ''),
        ]);
    }
}
