<?php

namespace App\Mcp\Tools\Performance;

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('find_campaign')]
#[Description('Find advertising campaigns in Whale arb_adops tables by campaign id or name. Defaults to Meta. Pass google only when the user asks for Google. Pass linkedin only when the user asks for LinkedIn.')]
class FindCampaign extends Tool
{
    public function __construct(private readonly WhaleAdopsReader $adops) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'query' => $schema->string()
                ->description('Platform campaign id or a name fragment from arb_adops tables.')
                ->required(),
            'platform' => $schema->string()
                ->description('meta, google, or linkedin. Defaults to meta.'),
        ];
    }

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

        $query = trim((string) $request->get('query', ''));
        $platform = strtolower(trim((string) $request->get('platform', 'meta'))) ?: 'meta';

        if ($query === '') {
            return Response::error('query is required.');
        }

        if (! in_array($platform, ['meta', 'google', 'linkedin'], true)) {
            return Response::text(json_encode([
                'ok' => false,
                'platform' => $platform,
                'message' => 'Only Meta, Google, and LinkedIn campaign data are in Whale so far.',
                'campaigns' => [],
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        }

        $campaigns = $this->adops->campaigns($platform, null, $query, 25);

        // Nothing found has two very different causes, and they used to look
        // identical. "No Google campaign matched Italy" and "Google has never
        // been ingested into Whale" both came back as an empty list with
        // ok:true, so a buyer was told their campaign does not exist when the
        // truth was that nobody had looked. Only said when the list is empty:
        // rows present mean the ingest plainly ran, whatever the status row
        // says about it.
        if ($campaigns === [] && $this->adops->latestIngest($platform, null, 'campaign_daily') === null) {
            return Response::text(json_encode([
                'ok' => false,
                'platform' => $platform,
                'query' => $query,
                'campaigns' => [],
                'message' => ucfirst($platform).' performance data is not ready in Whale: nothing has been '
                    .'ingested for it yet, so this found nothing rather than confirming the campaign is absent. '
                    .'Say that the data is not available rather than that the campaign does not exist.',
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        }

        return Response::text(json_encode([
            'ok' => true,
            'platform' => $platform,
            'query' => $query,
            'campaigns' => $campaigns,
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    }
}
