<?php

namespace App\Mcp\Tools\Performance;

use App\Campaigns\WhaleAdopsQuery;
use App\Campaigns\WhaleAdopsReader;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Tool;

#[Name('query_adops')]
#[Description('Read-only slice of Whale arb_adops data: accounts, campaigns, ads, adsets, geo, placements, devices, affiliate revenue, conversions, quality, changes. Use list_adops_catalog if you do not know the dataset key. Quote only returned numbers.')]
class QueryAdops extends Tool
{
    public function __construct(
        private readonly WhaleAdopsReader $adops,
        private readonly WhaleAdopsQuery $query,
    ) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'dataset' => $schema->string()
                ->description('Catalog key such as accounts, campaigns, ads, adsets, stats_geo_daily, stats_breakdown_daily, stats_daily, campaign_performance.')
                ->required(),
            'from' => $schema->string()
                ->description('Start date YYYY-MM-DD. Defaults to 7 days ago. Ignored for structure tables.'),
            'to' => $schema->string()
                ->description('End date YYYY-MM-DD. Defaults to today.'),
            'platform' => $schema->string()
                ->description('meta, google, or linkedin. Defaults to meta.'),
            'account_id' => $schema->string()
                ->description('Ad account id, without or with act_ prefix as stored in Whale.'),
            'campaign_id' => $schema->string()
                ->description('Platform campaign id.'),
            'adset_id' => $schema->string()
                ->description('Ad set id.'),
            'ad_id' => $schema->string()
                ->description('Ad id.'),
            'country' => $schema->string()
                ->description('ISO country code for stats_geo_daily, e.g. US.'),
            'region' => $schema->string()
                ->description('Region/state name when present on geo rows.'),
            'dimension' => $schema->string()
                ->description('For stats_breakdown_daily: age_gender, device, placement, or region.'),
            'value_1' => $schema->string()
                ->description('Breakdown slice such as mobile, feed, or 18-24.'),
            'search' => $schema->string()
                ->description('Name fragment for accounts, campaigns, ads, creatives, actions, affiliates.'),
            'group_by' => $schema->string()
                ->description('Comma-separated dimensions from the catalog, e.g. account_id,country or dimension,value_1.'),
            'limit' => $schema->integer()
                ->description('Max rows to return. Defaults to 25, max 100.'),
        ];
    }

    public function handle(Request $request): Response
    {
        if (! $this->adops->isAvailable()) {
            return Response::error('Whale adops tables are not available.');
        }

        $result = $this->query->run([
            'dataset' => $request->get('dataset', ''),
            'from' => $request->get('from'),
            'to' => $request->get('to'),
            'platform' => $request->get('platform', 'meta'),
            'account_id' => $request->get('account_id'),
            'campaign_id' => $request->get('campaign_id'),
            'adset_id' => $request->get('adset_id'),
            'ad_id' => $request->get('ad_id'),
            'country' => $request->get('country'),
            'region' => $request->get('region'),
            'dimension' => $request->get('dimension'),
            'value_1' => $request->get('value_1'),
            'search' => $request->get('search'),
            'group_by' => $request->get('group_by', ''),
            'limit' => $request->get('limit', 25),
        ]);

        if (! ($result['ok'] ?? false)) {
            return Response::error((string) ($result['error'] ?? 'Query failed.'));
        }

        return Response::text(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    }
}
