<?php

namespace App\Mcp\Tools\Performance;

use App\Campaigns\AdopsCampaignListReader;
use App\Campaigns\PerformanceVerdict;
use App\Campaigns\RoiDashboardReader;
use App\Models\CampaignPerformanceSuggestion;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Carbon;
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;
use Throwable;

#[Name('list_campaigns')]
#[Description('List campaigns. The main campaigns list comes from Whale arb_adops_campaign_performance and other arb_adops_* tables. roi_campaigns is a separate ROI list and must not be mixed into the main ranking. Use order top, worst, or list. When the user asks for the latest, newest, most recent, or recently added campaigns, use order latest. When the user asks for old or oldest campaigns, use order old. campaigns is the Whale arb_adops list ordered by arb_adops_campaigns.start_time: latest is newest start_time first, old is earliest start_time first, and a campaign with an empty start_time is left out. roi_campaigns stays a separate list. For order latest, roi_campaigns is from roi_dashboard_campaign_stats, newest recorded row first. Do not print the ROI list unless the user asks for ROI, sales, orders, subscriptions, installs, bookings, or leads. Print start_time. When the user asks which campaigns are active, running, or paused, pass status=active or status=paused. That filters campaigns using arb_adops_campaigns status and effective_status. active means effective_status or status is ACTIVE or ENABLED. ENABLED is an active Google campaign. Omit platform for Meta. Pass google only when the user asks for Google. Pass linkedin only when the user asks for LinkedIn. paused means status or effective_status is PAUSED. Print status and effective_status. Do not say campaign status is unavailable. For one ad account, pass account or account_id. For a spend minimum, pass min_spent. Both apply before the row cap. Print account, campaigns_matched, campaigns_returned, and total_spent. total_spent is every matched campaign. For underperforming campaigns, pass underperforming=true. That list is stored verdicts pause, stop, and action_required. Print verdict and reason. rank_by for the main list is sales, orders, clicks, or spent. ROI-only rank_by values are conversions, subscriptions, installs, bookings, or leads. Pass platform only when the user names one. For "last N days", pass days=N and do not pass from or to. Pass from and to only for an explicit date range. The first time the user asks for a list, print every returned column except impressions, conversions, and cpc, including zeros. Do not print the ROI list unless the user asks for ROI, sales, orders, subscriptions, installs, bookings, or leads. Pass follow_up=true only when this question is a later question in the same chat. A follow-up prints only the columns that question needs and does not print roi_campaigns unless the user asks for ROI, sales, orders, subscriptions, installs, bookings, or leads. rank_by cpc is spend divided by clicks. For CPC, order top is the lowest CPC first, and a campaign with no clicks is left out. Do not ask the user for an end date. Do not say an added date is unavailable when order is latest.')]
class ListCampaigns extends Tool
{
    public function __construct(
        private readonly AdopsCampaignListReader $adops,
        private readonly RoiDashboardReader $roi,
    ) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'order' => $schema->string()
                ->description('top, worst, list, latest, or old. The default list is latest: active campaigns, newest start_time first. Use old for old or oldest campaigns. A one-day list keeps order list.'),
            'rank_by' => $schema->string()
                ->description('Main list: sales, orders, clicks, spent, or cpc. cpc is spend divided by clicks, and order top is the lowest CPC first. ROI list only: conversions, subscriptions, installs, bookings, or leads. Defaults to sales.'),
            'platform' => $schema->string()
                ->description('Omit for Meta only. Pass google only when the user asks for Google campaigns or Google platform data. Pass linkedin only when the user asks for LinkedIn campaigns or LinkedIn platform data. ENABLED counts as active for Google. LinkedIn active status is ACTIVE.'),
            'days' => $schema->integer()
                ->description('For "last N days". The tool sets to=today and from=today minus N-1 days. Do not also pass from and to.'),
            'from' => $schema->string()
                ->description('Start date YYYY-MM-DD. For campaigns running on one date, pass that date as both from and to. The list then comes from arb_adops_stats_daily for that month.'),
            'to' => $schema->string()
                ->description('End date YYYY-MM-DD. Pass with from only when the user names explicit dates.'),
            'limit' => $schema->integer()
                ->description('Max campaigns to return. Defaults to 25, max 100. Use 5 for a top 5.'),
            'status' => $schema->string()
                ->description('active, paused, or all. Omit for active campaigns. Pass paused for paused campaigns. Pass all only when the user asks for every campaign, including paused or closed. A one-day list does not use this filter.'),
            'account_id' => $schema->string()
                ->description('Ad account id, with or without the act_ prefix. Omit when the user does not name an account.'),
            'account' => $schema->string()
                ->description('Ad account name. Resolved once to account_id. Omit when account_id is passed.'),
            'min_spent' => $schema->number()
                ->description('Minimum platform spend for the selected window, such as 100. Applied before the row cap. Omit when the user sets no spend minimum.'),
            'underperforming' => $schema->boolean()
                ->description('True when the user asks for underperforming campaigns. Keeps stored verdicts pause, stop, and action_required. Filtered to the ad account when account or account_id is passed.'),
            'follow_up' => $schema->boolean()
                ->description('True only when this list question is a later question in the same chat. Keeps active campaigns with spend above zero unless the user asks for paused, closed, all, latest, oldest, or one date. The first question leaves this unset.'),
        ];
    }

    public function handle(Request $request): Response
    {
        $order = strtolower(trim((string) $request->get('order', 'list'))) ?: 'list';

        if (in_array($order, ['new', 'newest'], true)) {
            $order = 'latest';
        } elseif ($order === 'oldest') {
            $order = 'old';
        }
        $rankBy = strtolower(trim((string) $request->get('rank_by', 'sales'))) ?: 'sales';
        $from = $this->date($request->get('from'));
        $to = $this->date($request->get('to'));
        $days = (int) $request->get('days', 0);
        $limit = (int) $request->get('limit', 25);
        $limit = $limit > 0 ? min($limit, 100) : 25;
        $status = strtolower(trim((string) $request->get('status', '')));
        $accountId = trim((string) $request->get('account_id', ''));
        $accountName = trim((string) $request->get('account', ''));
        $minSpent = $request->get('min_spent');
        $underperforming = filter_var($request->get('underperforming', false), FILTER_VALIDATE_BOOLEAN);
        $followUp = filter_var($request->get('follow_up', false), FILTER_VALIDATE_BOOLEAN);

        if (in_array($status, ['active', 'running', 'live'], true)) {
            $status = 'active';
        } elseif (in_array($status, ['paused', 'pause'], true)) {
            $status = 'paused';
        } elseif ($status === 'all') {
            $status = null;
        } elseif ($status !== '') {
            return Response::error('status must be active, paused, or all.');
        } else {
            $status = null;
        }

        if (! in_array($order, ['top', 'worst', 'list', 'latest', 'old'], true)) {
            return Response::error('order must be top, worst, list, latest, or old.');
        }

        if (! in_array($rankBy, ['sales', 'orders', 'clicks', 'spent', 'cpc', 'conversions', 'subscriptions', 'installs', 'bookings', 'leads'], true)) {
            return Response::error('rank_by must be sales, orders, clicks, spent, cpc, conversions, subscriptions, installs, bookings, or leads.');
        }

        if ($from === false || $to === false) {
            return Response::error('from and to must be YYYY-MM-DD dates.');
        }

        if (($from === null) !== ($to === null)) {
            return Response::error('Pass both from and to, or omit both.');
        }

        if (is_string($from) && is_string($to) && $from > $to) {
            return Response::error('from must be on or before to.');
        }

        if ($from === null && $to === null && $days > 0) {
            $days = min($days, 366);
            $to = now()->toDateString();
            $from = now()->subDays($days - 1)->toDateString();
        }

        if ($minSpent === null || $minSpent === '') {
            $minSpent = null;
        } elseif (! is_numeric($minSpent) || (float) $minSpent < 0) {
            return Response::error('min_spent must be a number that is zero or greater.');
        } else {
            $minSpent = (float) $minSpent;
        }

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

        if ($accountId !== '' || $accountName !== '') {
            $accounts = $this->adops->findAccounts(
                $accountId !== '' ? $accountId : null,
                $accountId === '' ? $accountName : null,
                $platform,
            );

            if ($accountId === '' && count($accounts) > 1) {
                return Response::text(json_encode([
                    'ok' => true,
                    'accounts' => $accounts,
                    'campaigns' => [],
                    'note' => 'More than one ad account matches that name. Ask which account_id to use. Do not list campaigns yet.',
                ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
            }

            if ($accountId === '' && $accounts === []) {
                return Response::error('No ad account found for that name.');
            }

            $resolved = $accounts[0] ?? [
                'account_id' => $accountId,
                'name' => null,
                'status' => null,
                'currency' => null,
            ];
        }

        $singleDate = is_string($from) && $from === $to;
        $statusWasOmitted = $request->get('status') === null || trim((string) $request->get('status')) === '';

        if ($statusWasOmitted && $status === null && ! $singleDate) {
            $status = 'active';
        }

        if ($order === 'list' && ! $singleDate) {
            $order = 'latest';
        }

        if ($followUp && $underperforming && $status === null && ! $singleDate && ! in_array($order, ['latest', 'old'], true)) {
            $status = 'active';
        }

        $spendingOnly = $followUp && $status === 'active' && ! $singleDate && ! in_array($order, ['latest', 'old'], true);
        $verdicts = $underperforming ? $this->underperformingVerdicts($platform) : [];

        $roiRank = in_array($rankBy, ['sales', 'spent', 'conversions', 'subscriptions', 'installs', 'bookings', 'leads'], true)
            ? $rankBy
            : 'sales';

        $result = $this->adops->listCampaigns(
            $platform,
            $from,
            $to,
            $order,
            $rankBy,
            $limit,
            $status,
            $resolved['account_id'] ?? null,
            $minSpent,
            $underperforming ? array_keys($verdicts) : null,
            $spendingOnly,
        );
        $roi = $this->roi->listCampaigns(
            $platform,
            $from,
            $to,
            $order,
            $roiRank,
            $limit,
        );

        $result['roi_campaigns'] = $roi['campaigns'] ?? [];
        $result['account'] = $resolved === null ? null : [
            'account_id' => $resolved['account_id'],
            'name' => $resolved['name'],
            'status' => $resolved['status'],
            'currency' => $resolved['currency'],
            'campaigns_matched' => $result['campaigns_matched'] ?? 0,
            'campaigns_returned' => $result['campaigns_returned'] ?? 0,
            'total_spent' => $result['total_spent'] ?? 0,
        ];
        $result['min_spent'] = $minSpent;
        $result['underperforming'] = $underperforming;

        if ($underperforming) {
            foreach ($result['campaigns'] as $index => $campaign) {
                $verdict = $verdicts[(string) $campaign['campaign_id']] ?? null;

                if ($verdict === null) {
                    continue;
                }

                $result['campaigns'][$index] = array_merge($campaign, $verdict);
            }
        }

        $result['note'] = match (true) {
            $status !== null => 'campaigns is the Whale arb_adops list filtered by arb_adops_campaigns status and effective_status. active means effective_status or status is ACTIVE or ENABLED. ENABLED is an active Google campaign. Omit platform for Meta. Pass google only when the user asks for Google. Pass linkedin only when the user asks for LinkedIn. paused means status or effective_status is PAUSED. roi_campaigns is separate and is not a running or paused list.',
            $order === 'latest' => 'campaigns is the Whale arb_adops list ordered by arb_adops_campaigns.start_time, newest start first. A campaign with an empty start_time is left out. roi_campaigns is a separate list of the latest campaigns from roi_dashboard_campaign_stats, newest recorded row first. Do not mix the two. The monitor lag window is not applied.',
            $order === 'old' => 'campaigns is the Whale arb_adops list ordered by arb_adops_campaigns.start_time, earliest start first. A campaign with an empty start_time is left out. roi_campaigns is separate and is not ordered by start_time. Do not mix the two.',
            default => 'campaigns is the main Whale arb_adops list. roi_campaigns is separate and is not used to rank the main list. The monitor lag window is not applied.',
        };

        if ($order === 'latest') {
            $result['note'] .= ' The default list is active campaigns ordered by start_time, newest first. A campaign with an empty start_time is left out. roi_campaigns for order latest comes from roi_dashboard_campaign_stats and stays separate.';
        }

        if (is_string($from) && $from === $to) {
            $result['note'] = 'campaigns are the campaign ids with rows in arb_adops_stats_daily for '.$from.', summed by campaign_id from the ad rows. spent, impressions, and clicks are those totals. A campaign with no row on that date is left out. Do not use current status to decide who was running. Print spend, impressions, and clicks.';
        }

        if ($resolved !== null || $minSpent !== null || $underperforming) {
            $result['note'] .= ' campaigns_matched is the full count before the limit. campaigns_returned is this page. total_spent sums every matched campaign.';
        }

        if ($resolved !== null) {
            $result['note'] .= ' account is the resolved ad account. Do not call query_adops for this campaign list.';
        }

        if ($underperforming) {
            $result['note'] .= ' Underperforming is the stored verdict pause, stop, or action_required. Print verdict and reason. Do not decide underperforming from spend.';
        }

        if ($rankBy === 'cpc') {
            $result['note'] .= ' cpc is spent divided by clicks. order top is the lowest CPC first. A campaign with no clicks is left out.';
        }

        $result['note'] .= ' Do not print roi_campaigns unless the user asks for ROI, sales, orders, subscriptions, installs, bookings, or leads.';

        if ($followUp) {
            $result['follow_up'] = true;
            $result['note'] .= ' This is a list follow-up. Print only the columns the question needs. Do not print roi_campaigns unless the user asked for ROI, sales, orders, subscriptions, installs, bookings, or leads. Do not say Whale. If a source must be named, call it the ad reporting data. A performance brief is one short summary and one table with Campaign Name, Spend, Impressions, Clicks, and Conversions. A pause question prints the campaign name and the stored reason. Highest spend prints Campaign Name and Spend. A budget question uses spend, clicks, and conversions. Do not refuse an increase only because sales or orders are zero. Lowest CPC prints Campaign Name, Spend, Clicks, and CPC. Campaigns with spent of 0 are left out when this follow-up is about active campaigns.';
        }

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

    /**
     * @return array<string, array{verdict: string, verdict_label: string, reason: string}>
     */
    private function underperformingVerdicts(?string $platform): array
    {
        $platform = strtolower(trim((string) $platform));
        $query = CampaignPerformanceSuggestion::query()
            ->whereIn('status', [
                PerformanceVerdict::Pause->value,
                PerformanceVerdict::Stop->value,
                PerformanceVerdict::ActionRequired->value,
            ])
            ->orderByDesc('suggested_at');

        if ($platform !== '') {
            $query->where('platform', $platform);
        }

        $verdicts = [];

        foreach ($query->get() as $row) {
            $id = (string) $row->external_campaign_id;

            if (isset($verdicts[$id])) {
                continue;
            }

            $verdict = PerformanceVerdict::tryFrom((string) $row->status);
            $verdicts[$id] = [
                'verdict' => (string) $row->status,
                'verdict_label' => $verdict?->label() ?? (string) $row->status,
                'reason' => (string) $row->reason,
            ];
        }

        return $verdicts;
    }

    private function date(mixed $value): string|false|null
    {
        if ($value === null || trim((string) $value) === '') {
            return null;
        }

        try {
            return Carbon::parse(trim((string) $value))->toDateString();
        } catch (Throwable) {
            return false;
        }
    }
}
