<?php

namespace App\Mcp\Tools\Performance;

use App\Campaigns\CampaignPerformanceAdopsMonitor;
use App\Campaigns\CampaignPerformanceChatAnswer;
use App\Campaigns\CampaignPerformanceSuggestionDisplay;
use App\Campaigns\RoiDashboardReader;
use App\Campaigns\WhaleAdopsReader;
use App\Library\CampaignDecision\CampaignBudgetRecommendation;
use App\Models\CampaignPerformanceSuggestion;
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('campaign_health')]
#[Description('How a campaign is doing. For a chat reply about one campaign, print the answer field exactly and add nothing else. answer lists the metrics, then the decision: verdict, why this verdict, and what to do, using readable labels. Copy numbers from the tool; do not invent them.')]
class CampaignHealth extends Tool
{
    public function __construct(
        private readonly WhaleAdopsReader $adops,
        private readonly CampaignPerformanceAdopsMonitor $monitor,
        private readonly RoiDashboardReader $roi,
    ) {}

    public function schema(JsonSchema $schema): array
    {
        return [
            'campaign_id' => $schema->string()
                ->description('Platform campaign id from find_campaign.')
                ->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.');
        }

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

        $health = $this->monitor->health($platform, $campaignId);

        if ($health === null) {
            return Response::error('No Whale campaign found for that id.');
        }

        $suggestion = CampaignPerformanceSuggestion::query()
            ->where('platform', $platform)
            ->where('external_campaign_id', $campaignId)
            ->first();

        $snapshot = is_array($health['snapshot'] ?? null) ? $health['snapshot'] : [];
        $evaluation = is_array($health['evaluation'] ?? null) ? $health['evaluation'] : [];
        $roi = $this->roi->forCampaign($platform, $campaignId);
        $recommendation = $this->budgetRecommendation($health['campaign'], $snapshot, $evaluation, $suggestion);
        $details = $this->campaignDetails($health['campaign'], $snapshot, $evaluation, $suggestion);
        $stored = $this->storedEvaluation($suggestion, $evaluation);
        $implementationPlan = CampaignPerformanceSuggestionDisplay::implementationPlanMarkdown($suggestion);

        if (is_array($stored) && is_array($recommendation) && is_string($recommendation['summary'] ?? null)) {
            $stored['action_summary'] = $recommendation['summary'];
        }

        $payload = [
            'ok' => true,
            'campaign' => $health['campaign']['name'],
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'account_id' => $health['campaign']['account_id'],
            'platform_status' => $health['campaign']['effective_status'] ?? $health['campaign']['status'],
            'verdict' => $stored['verdict'] ?? $evaluation['final_verdict'] ?? null,
            'verdict_label' => $stored['verdict_label'] ?? null,
            'action_summary' => $stored['action_summary'] ?? (is_array($recommendation) ? ($recommendation['summary'] ?? null) : null),
            'budget_recommendation' => $recommendation,
            'reason' => $stored['verdict_reason'] ?? $evaluation['final_reason'] ?? null,
            'confidence' => $details['confidence'],
            'hourly_verdict' => $evaluation['hourly_verdict'] ?? null,
            'decision' => $suggestion?->reason,
            'implementation_plan' => $implementationPlan,
            'marketing_plan' => $stored['marketing_plan'] ?? null,
            'marketing_lever' => $stored['marketing_lever'] ?? null,
            'stored_evaluation' => $stored,
            'live_evaluation' => [
                'verdict' => $evaluation['final_verdict'] ?? null,
                'reason' => $evaluation['final_reason'] ?? null,
            ],
            'last_saved_reason' => $suggestion?->reason,
            'last_saved_at' => $suggestion?->suggested_at?->toDateTimeString(),
            'saved_status' => $details['saved_status'],
            'ai_status' => $details['ai_status'],
            'last_7_hours' => $snapshot['last_7_hours'] ?? $details['last_7_hours'],
            'last_7_days' => $snapshot['last_7_days'] ?? $details['last_7_days'],
            'yesterday' => $snapshot['yesterday'] ?? null,
            'trend' => $snapshot['trend'] ?? null,
            'trend_summary' => $snapshot['trend_summary'] ?? null,
            'sync_failed' => $snapshot['sync_failed'] ?? false,
            'sync_error' => $snapshot['sync_error'] ?? null,
            'campaign_details' => $details,
            'revenue_included' => false,
            'note' => 'Affiliate CPC, commissions, and conversions are not in Whale yet. Verdicts use platform spend, impressions, and clicks only.',
        ];

        if ($roi['included']) {
            $payload['roi'] = [
                'source' => 'roi_dashboard',
                'date_window_applied' => false,
                'rows' => $roi['rows'],
            ];
            $payload['note'] = 'ROI rows are included because this campaign id is not in arb_adops_campaign_performance. No date window is applied. The verdict itself is unchanged.';
        }

        if (is_array($details['outcome_window'])) {
            $payload['note'] = 'outcome_window is the lagged window behind the verdict. last_7_hours and last_7_days are Meta delivery. Do not replace outcome_window with an empty ROI query.';
        }

        $payload['note'] = trim($payload['note'].' Reply with the answer field exactly. Do not add raw status codes.');
        $payload = [
            'answer' => CampaignPerformanceChatAnswer::fromHealthPayload($payload),
        ] + $payload;

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

    /**
     * @param  array<string, mixed>  $campaign
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $evaluation
     * @return array<string, mixed>|null
     */
    private function budgetRecommendation(array $campaign, array $snapshot, array $evaluation, ?CampaignPerformanceSuggestion $suggestion): ?array
    {
        $source = is_array($suggestion?->snapshot) ? $suggestion->snapshot : $snapshot;

        if (! is_numeric($source['daily_budget'] ?? null) && is_numeric($campaign['daily_budget'] ?? null)) {
            $source['daily_budget'] = (float) $campaign['daily_budget'];
        }

        if (! is_numeric($source['recommended_budget_change_percent'] ?? null) && is_numeric($snapshot['recommended_budget_change_percent'] ?? null)) {
            $source['recommended_budget_change_percent'] = (int) $snapshot['recommended_budget_change_percent'];
        }

        $status = $suggestion?->status ?? (is_string($evaluation['final_verdict'] ?? null) ? $evaluation['final_verdict'] : null);
        $liveBudget = is_numeric($campaign['daily_budget'] ?? null) ? (float) $campaign['daily_budget'] : null;

        return CampaignBudgetRecommendation::fromStored($status, $source, $liveBudget);
    }

    /**
     * @param  array<string, mixed>  $evaluation
     * @return array<string, mixed>|null
     */
    private function storedEvaluation(?CampaignPerformanceSuggestion $suggestion, array $evaluation): ?array
    {
        if ($suggestion === null) {
            return null;
        }

        $planRow = CampaignPerformanceSuggestionDisplay::planRow($suggestion);

        return [
            'verdict' => $suggestion->status,
            'verdict_label' => CampaignPerformanceSuggestionDisplay::verdictLabel($suggestion->status),
            'action_summary' => CampaignPerformanceSuggestionDisplay::actionSummary($suggestion->status),
            'verdict_reason' => CampaignPerformanceSuggestionDisplay::engineVerdictReason($suggestion),
            'marketing_plan' => $planRow['marketing_plan'] ?? null,
            'marketing_lever' => $planRow['marketing_lever'] ?? null,
            'saved_at' => $suggestion->suggested_at?->toDateTimeString(),
            'live_verdict' => $evaluation['final_verdict'] ?? null,
            'live_reason' => $evaluation['final_reason'] ?? null,
        ];
    }

    /**
     * @param  array<string, mixed>  $campaign
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $evaluation
     * @return array<string, mixed>
     */
    private function campaignDetails(array $campaign, array $snapshot, array $evaluation, ?CampaignPerformanceSuggestion $suggestion): array
    {
        $windows = is_array($evaluation['windows'] ?? null) ? $evaluation['windows'] : [];
        $snapshotWindows = is_array($snapshot['windows'] ?? null) ? $snapshot['windows'] : [];

        return [
            'name' => $campaign['name'] ?? null,
            'account_id' => $campaign['account_id'] ?? null,
            'platform_status' => $campaign['effective_status'] ?? $campaign['status'] ?? null,
            'verdict' => $evaluation['final_verdict'] ?? null,
            'reason' => $evaluation['final_reason'] ?? null,
            'confidence' => $snapshot['confidence'] ?? $suggestion?->confidence,
            'last_7_hours' => $this->deliveryWindow($windows['7h'] ?? $snapshotWindows['7h'] ?? $snapshot['last_7_hours'] ?? null),
            'last_7_days' => $this->deliveryWindow($windows['7d'] ?? $snapshotWindows['7d'] ?? $snapshot['last_7_days'] ?? null),
            'outcome_window' => $this->outcomeWindow($snapshot, $snapshotWindows),
            'saved_status' => $suggestion?->status,
            'ai_status' => is_array($suggestion?->snapshot) ? ($suggestion->snapshot['ai_status'] ?? null) : null,
            'decision' => $suggestion?->reason,
            'implementation_plan' => CampaignPerformanceSuggestionDisplay::implementationPlanMarkdown($suggestion),
            'action_summary' => CampaignPerformanceSuggestionDisplay::actionSummary($suggestion?->status),
            'verdict_label' => CampaignPerformanceSuggestionDisplay::verdictLabel($suggestion?->status),
            'verdict_reason' => CampaignPerformanceSuggestionDisplay::engineVerdictReason($suggestion),
        ];
    }

    /**
     * @return array{from: mixed, to: mixed, spend: mixed, clicks: mixed, impressions: mixed}|null
     */
    private function deliveryWindow(mixed $window): ?array
    {
        if (! is_array($window)) {
            return null;
        }

        return [
            'from' => $window['from'] ?? null,
            'to' => $window['to'] ?? null,
            'spend' => $window['spend'] ?? null,
            'clicks' => $window['clicks'] ?? null,
            'impressions' => $window['impressions'] ?? null,
        ];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $windows
     * @return array<string, mixed>|null
     */
    private function outcomeWindow(array $snapshot, array $windows): ?array
    {
        $channel = $snapshot['channels']['outcome'] ?? null;

        if (is_array($channel) && ($channel['available'] ?? false) === true) {
            return [
                'from' => $channel['from'] ?? null,
                'to' => $channel['to'] ?? null,
                'spend' => $channel['spend'] ?? null,
                'orders' => $channel['orders'] ?? null,
                'sales' => $channel['revenue'] ?? null,
                'conversions' => $channel['conversions'] ?? null,
                'subscriptions' => $channel['subscriptions'] ?? null,
                'installs' => $channel['installs'] ?? null,
                'bookings' => $channel['bookings'] ?? null,
                'leads' => $channel['leads'] ?? null,
            ];
        }

        $window = null;

        foreach ($windows as $key => $value) {
            if (is_string($key) && str_starts_with($key, 'outcome_') && is_array($value)) {
                $window = $value;
                break;
            }
        }

        if ($window === null) {
            return null;
        }

        return [
            'from' => $window['from'] ?? null,
            'to' => $window['to'] ?? null,
            'spend' => $window['platform_spend'] ?? $window['spend'] ?? null,
            'orders' => $window['orders'] ?? null,
            'sales' => $window['revenue'] ?? $window['net_revenue'] ?? null,
            'conversions' => $window['conversions'] ?? null,
            'subscriptions' => $window['subscriptions'] ?? null,
            'installs' => $window['installs'] ?? null,
            'bookings' => $window['bookings'] ?? null,
            'leads' => $window['leads'] ?? null,
        ];
    }
}
