<?php

namespace App\AI\Tools;

use App\AI\Mcp\Client;

/**
 * A local tool, not an MCP one. It calls the MCP account list and then groups
 * the results deterministically in PHP, so the agent never has to infer which
 * monetization service an account belongs to.
 */
class AccountsByService implements Tool
{
    public function __construct(protected Client $client) {}

    public function definition(): array
    {
        return [
            'type' => 'function',
            'name' => 'accounts_by_service',
            'description' => <<<'TXT'
                List every ad account grouped by its monetization service (Bing,
                Yahoo, RSOC, Amazon, AFS, ...). Call this FIRST whenever a request
                involves more than one account, comparisons, rankings, or
                portfolio-wide analysis. Campaigns may only be compared within a
                single service, and this tool is the authoritative grouping — do
                not infer the service from an account name yourself.
                TXT,
            'parameters' => [
                'type' => 'object',
                'properties' => (object) [],
                'additionalProperties' => false,
            ],
        ];
    }

    public function use(array $arguments): string
    {
        $payload = json_decode($this->client->call('ads_get_ad_accounts', []), true);

        $grouped = [];

        foreach ($payload['ad_accounts'] ?? [] as $account) {
            $service = $this->serviceFor($account['ad_account_name'] ?? '');

            $grouped[$service][] = [
                'ad_account_id' => $account['ad_account_id'] ?? null,
                'ad_account_name' => $account['ad_account_name'] ?? null,
                'account_status' => $account['account_status'] ?? null,
                'is_queryable' => $account['is_queryable'] ?? null,
                'currency' => $account['currency'] ?? null,
            ];
        }

        ksort($grouped);

        return json_encode([
            'note' => 'Campaigns may only be compared within a single service.',
            'services' => $grouped,
        ]);
    }

    protected function serviceFor(string $name): string
    {
        $haystack = strtolower($name);

        foreach (config('media_buying.services') as $service => $needles) {
            foreach ($needles as $needle) {
                if (str_contains($haystack, strtolower($needle))) {
                    return $service;
                }
            }
        }

        return config('media_buying.unclassified');
    }
}
