<?php

namespace App\Mcp\Tools\Performance;

use App\Campaigns\CampaignComparisonReader;
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('compare_campaign')]
#[Description('Compare one campaign. Last 2 days, last 3 days, or last N days compares each of those days, ending yesterday, as its own column. A week compares the last 7 days with the 7 days before. A named range compares that range with the period before it, or with a second named range. Returns delivery, affiliate, and ROI metrics, which day or window did better, and what to do with why. Do not use this for a plain performance question.')]
class CompareCampaign extends Tool
{
    public function __construct(
        private readonly WhaleAdopsReader $adops,
        private readonly CampaignComparisonReader $comparisons,
    ) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'campaign_id' => $schema->string()
                ->description('Platform campaign id. Call find_campaign first when the user gives a name.')
                ->required(),
            'platform' => $schema->string()
                ->description('meta, google, or linkedin. Defaults to meta.'),
            'preset' => $schema->string()
                ->description('day, 3day, or week. day is today versus yesterday. 3day is the last 3 days ending yesterday, each day as its own column. week is the last 7 days versus the 7 days before.')
                ->enum(['day', '3day', 'week']),
            'days' => $schema->integer()
                ->description('Last N days, each day as its own column, ending yesterday. Last 2 days is yesterday versus the day before. Do not include today and do not compare those days with the N days before them. Do not also pass from or to.'),
            'from' => $schema->string()
                ->description('Start of the current range, YYYY-MM-DD. The tool compares it with the same number of days immediately before, unless compare_from and compare_to are also passed.'),
            'to' => $schema->string()
                ->description('End of the current range, YYYY-MM-DD.'),
            'compare_from' => $schema->string()
                ->description('Start of the second named range, YYYY-MM-DD. Pass with compare_to only when the user names both ranges.'),
            'compare_to' => $schema->string()
                ->description('End of the second named range, YYYY-MM-DD.'),
        ];
    }

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

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

        if ($campaignId === '') {
            return Response::error('campaign_id is required. Call find_campaign first.');
        }

        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.',
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        }

        $days = $request->get('days');

        return Response::text(json_encode(
            $this->comparisons->compare(
                $platform,
                $campaignId,
                $request->get('preset'),
                is_numeric($days) ? (int) $days : null,
                $this->nullableString($request->get('from')),
                $this->nullableString($request->get('to')),
                $this->nullableString($request->get('compare_from')),
                $this->nullableString($request->get('compare_to')),
            ),
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
        ));
    }

    private function nullableString(mixed $value): ?string
    {
        if (! is_string($value)) {
            return null;
        }

        $value = trim($value);

        return $value === '' ? null : $value;
    }
}
