<?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;

/**
 * Meta's language list, for changing the language on an ad set that is already live.
 *
 * Creation does not use this. A draft still chooses its audience through the
 * targeting step, and this search is not part of that step.
 */
class SearchAdLocales implements Tool
{
    use ActsOnFocusedCampaign;

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

    public function description(): Stringable|string
    {
        return 'Search the languages Meta can target, for changing the language on an ad set that is '
            .'already live. Show the returned names and wait for the user to choose. Then call '
            .'edit_entity with that locale number in targeting.locales. Do not invent a locale '
            .'number. Do not use this while creating a campaign.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'query' => $schema->string()
                ->description('The language the user named, such as English or Spanish.')
                ->required(),
        ];
    }

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

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

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

        if ($query === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Name the language to search for.',
            ]);
        }

        try {
            $languages = $this->meta->on($campaign->id, null)->adLocales((string) $campaign->ad_account_id, $query);
        } catch (MetaException $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The language list could not be read, so nothing was changed.',
            ]);
        } catch (\InvalidArgumentException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        return $this->json([
            'ok' => true,
            'languages' => $languages,
            'note' => $languages === []
                ? 'Meta has no language matching that name. Say so and do not invent a locale.'
                : 'Show these language names and wait for the user to choose. Then call edit_entity with the chosen locale number. Do not pick one yourself when more than one is returned.',
        ]);
    }
}
