<?php

namespace App\Mcp\Tools\Performance;

use App\Campaigns\CampaignPerformanceSuggestionReplyGuard;
use App\Campaigns\CampaignSuggestionReader;
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('suggest_campaign')]
#[Description('Suggestions for one campaign. For how it is performing, budget, conversions, or pause, use focus performance and print the stats table. Ad set audience, delivery, bid, and breakdowns are in ad_set_optimization. When the user names a day or a date range and is not asking to compare periods, pass from and to so delivery, sales, roi, and ad_set_optimization use those dates. For creatives, the landing page, or targeting, set focus to creative, landing, or targeting and follow the returned note. Do not print the campaign stats table for those focuses.')]
class SuggestCampaign extends Tool
{
    public function __construct(
        private readonly WhaleAdopsReader $adops,
        private readonly CampaignSuggestionReader $suggestions,
    ) {}

    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.'),
            'focus' => $schema->string()
                ->description('performance, creative, landing, or targeting. Defaults to performance.')
                ->enum(['performance', 'creative', 'landing', 'targeting']),
            'from' => $schema->string()
                ->description('Start date YYYY-MM-DD when the user names a day or a range. For one day, set from and to to that day. Omit for the default 30-day window. Do not pass these for a comparison.'),
            'to' => $schema->string()
                ->description('End date YYYY-MM-DD. For one day, set this to the same date as from.'),
        ];
    }

    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';
        $focus = strtolower(trim((string) $request->get('focus', 'performance'))) ?: 'performance';

        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));
        }

        $from = $this->nullableString($request->get('from'));
        $to = $this->nullableString($request->get('to'));
        $payload = $this->suggestions->forCampaign($platform, $campaignId, $focus, $from, $to);
        app(CampaignPerformanceSuggestionReplyGuard::class)->record($campaignId, $focus, $from, $to, $payload);

        return Response::text(json_encode(
            $payload,
            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;
    }
}
