<?php

namespace Tests\Feature;

use App\Agent\CampaignPerformanceChatAgent;
use App\Campaigns\CampaignPerformanceSuggestionReplyGuard;
use App\Campaigns\CampaignSuggestionReader;
use App\Mcp\Servers\CampaignPerformanceServer;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Mcp\Server\Attributes\Instructions;
use Tests\TestCase;

class CampaignPerformanceChatTest extends TestCase
{
    use RefreshDatabase;

    public function test_campaign_performance_chat_uses_the_page_text_model(): void
    {
        $this->assertSame('gpt-6.1-sol', app(CampaignPerformanceChatAgent::class)->model());
        $this->assertSame('gpt-6.1-terra', config('ai.providers.openai.models.text.default'));
    }

    public function test_the_chat_page_is_available_to_a_signed_in_user(): void
    {
        $this->actingAs(User::factory()->create());

        $this->get(route('campaigns.performance.chat'))
            ->assertOk()
            ->assertSee('Campaign performance chat')
            ->assertSee('Analyzing campaign data')
            ->assertSee("event.key !== 'Enter'", false)
            ->assertSee('field.value = \'\'', false)
            ->assertSee('mb-chat-table')
            ->assertSee('mb-chat-stat-label strong', false)
            ->assertDontSee('td:first-child { width: 11rem', false)
            ->assertSee('scrollPerformanceChatToEnd', false)
            ->assertSee('id="performanceChatSend" disabled', false)
            ->assertSee('event.preventDefault()', false)
            ->assertSee("Accept': 'application/json'", false)
            ->assertSee('justify-content: flex-end', false);
    }

    public function test_roi_answers_are_told_to_keep_zero_metric_columns(): void
    {
        $instructions = (string) app(CampaignPerformanceChatAgent::class)->instructions();

        $this->assertStringContainsString('columns for platform, spent, sales (arb_sales_amount)', $instructions);
        $this->assertStringContainsString('Keep a column when every value is 0.', $instructions);
        $this->assertStringContainsString('pass days=N', $instructions);
        $this->assertStringContainsString('Do not ask for an end date.', $instructions);
        $this->assertStringContainsString('order=latest', $instructions);
        $this->assertStringContainsString('The default campaign list is active campaigns, newest start_time first.', $instructions);
        $this->assertStringContainsString('roi_dashboard_campaign_stats', $instructions);
        $this->assertStringContainsString('arb_adops_campaigns.start_time', $instructions);
        $this->assertStringContainsString('order=old', $instructions);
        $this->assertStringContainsString('status=active', $instructions);
        $this->assertStringContainsString('arb_adops_stats_daily for that month and date', $instructions);
        $this->assertStringContainsString('ENABLED is an active Google campaign.', $instructions);
        $this->assertStringContainsString('Pass platform=google only when the user asks for Google campaigns or Google platform data.', $instructions);
        $this->assertStringContainsString('Pass platform=linkedin only when the user asks for LinkedIn campaigns or LinkedIn platform data.', $instructions);
        $this->assertStringContainsString('effective_status', $instructions);
        $this->assertStringContainsString('Pass min_spent for a minimum such as 100.', $instructions);
        $this->assertStringContainsString('underperforming=true', $instructions);
        $this->assertStringContainsString('Do not decide underperforming from spend.', $instructions);
        $this->assertStringContainsString('campaigns_matched', $instructions);
        $this->assertStringContainsString('total_spent is every matched campaign.', $instructions);
        $this->assertStringContainsString('group_by account_id,campaign_id,adset_id', $instructions);
        $this->assertStringContainsString('There is no Business Manager id.', $instructions);
        $this->assertStringContainsString('Do not print the ROI list unless the user asks for ROI, sales, orders, subscriptions, installs, bookings, or leads.', $instructions);
        $this->assertStringContainsString('The first time the user asks for a list, print every column on both lists except impressions, conversions, and cpc, including zeros.', $instructions);
        $this->assertStringContainsString('A later question in this chat about the campaign list is a list follow-up.', $instructions);
        $this->assertStringContainsString('Do not print roi_campaigns on that follow-up unless', $instructions);
        $this->assertStringContainsString('rank_by=cpc', $instructions);
        $this->assertStringContainsString('Do not refuse an increase only because sales or orders are zero.', $instructions);
        $server = (string) (new \ReflectionClass(CampaignPerformanceServer::class))
            ->getAttributes(Instructions::class)[0]
            ->getArguments()[0];
        $this->assertStringContainsString('Pass min_spent for a minimum such as 100.', $server);
        $this->assertStringContainsString('underperforming=true', $server);
        $this->assertStringContainsString('There is no Business Manager id.', $server);
        $this->assertStringContainsString('Pass platform=google only when the user asks for Google campaigns or Google platform data.', $server);
        $this->assertStringContainsString('Pass platform=linkedin only when the user asks for LinkedIn campaigns or LinkedIn platform data.', $server);
        $this->assertStringContainsString('arb_adops_stats_daily for that month and date', $server);
        $this->assertStringContainsString('Do not print the ROI list unless the user asks for ROI, sales, orders, subscriptions, installs, bookings, or leads.', $server);
        $this->assertStringContainsString('The default campaign list is active campaigns, newest start_time first.', $server);
        $this->assertStringContainsString('A later question in this chat about the campaign list is a list follow-up.', $server);
        $this->assertStringContainsString('Do not print roi_campaigns on that follow-up unless', $server);
        $this->assertStringContainsString('rank_by=cpc', $server);
    }

    public function test_single_campaign_health_answers_print_the_engine_decision_after_the_metrics(): void
    {
        $instructions = (string) app(CampaignPerformanceChatAgent::class)->instructions();

        $this->assertStringContainsString('reply with its answer field exactly', $instructions);
        $this->assertStringContainsString('why this verdict, and what to do', $instructions);
        $this->assertStringContainsString('Do not add raw status codes such as decrease_budget', $instructions);
        $this->assertStringContainsString('not to list_campaigns', $instructions);
    }

    public function test_a_saved_reply_shows_status_labels_instead_of_codes(): void
    {
        $this->actingAs(User::factory()->create());
        session(['campaign_performance_chat' => [
            ['role' => 'assistant', 'text' => 'Verdict: Decrease budget (decrease_budget). What to do: reduce spend.'],
        ]]);

        $this->get(route('campaigns.performance.chat'))
            ->assertOk()
            ->assertSee('What to do: reduce spend.')
            ->assertSee('Decrease budget')
            ->assertDontSee('decrease_budget');
    }

    public function test_a_message_is_answered_by_the_performance_agent(): void
    {
        CampaignPerformanceChatAgent::fake(['Pause. ROI spent is $89.11 with 0 sales.']);
        $this->actingAs(User::factory()->create());

        $this->post(route('campaigns.performance.chat.send'), [
            'message' => 'How is campaign 120249356799650510 doing?',
        ])->assertRedirect(route('campaigns.performance.chat'));

        $this->get(route('campaigns.performance.chat'))
            ->assertOk()
            ->assertSee('How is campaign 120249356799650510 doing?')
            ->assertSee('ROI spent is $89.11');
    }

    public function test_the_same_suggestion_prompt_reuses_the_reply_when_stats_are_unchanged(): void
    {
        $payload = $this->suggestionPayload(194.29);
        $guard = new CampaignPerformanceSuggestionReplyGuard;
        $this->actingAs(User::factory()->create());
        session([
            CampaignPerformanceSuggestionReplyGuard::SESSION_KEY => [
                $guard->promptKey('Lucos how this campaign works') => [
                    'campaign_id' => '1201',
                    'from' => '2026-09-09',
                    'to' => '2026-10-08',
                    'hash' => $guard->hash($payload),
                    'reply' => 'Monitor the learning period. Make no budget change.',
                ],
            ],
        ]);
        $this->mock(CampaignSuggestionReader::class, function ($mock) use ($payload): void {
            $mock->shouldReceive('forCampaign')->once()->andReturn($payload);
        });
        CampaignPerformanceChatAgent::fake(['A different recommendation.']);

        $this->postJson(route('campaigns.performance.chat.send'), [
            'message' => '  Lucos   how this campaign works ',
        ])->assertOk()
            ->assertJsonPath('html', fn (string $html): bool => str_contains($html, 'Monitor the learning period')
                && ! str_contains($html, 'different recommendation'));
    }

    public function test_a_changed_stat_asks_for_a_new_suggestion(): void
    {
        $guard = new CampaignPerformanceSuggestionReplyGuard;
        $this->actingAs(User::factory()->create());
        session([
            CampaignPerformanceSuggestionReplyGuard::SESSION_KEY => [
                $guard->promptKey('Lucos how this campaign works') => [
                    'campaign_id' => '1201',
                    'from' => '2026-09-09',
                    'to' => '2026-10-08',
                    'hash' => $guard->hash($this->suggestionPayload(194.29)),
                    'reply' => 'Monitor the learning period. Make no budget change.',
                ],
            ],
        ]);
        $this->mock(CampaignSuggestionReader::class, function ($mock): void {
            $mock->shouldReceive('forCampaign')->once()->andReturn($this->suggestionPayload(200));
        });
        CampaignPerformanceChatAgent::fake(['New recommendation after the spend change.']);

        $this->postJson(route('campaigns.performance.chat.send'), [
            'message' => 'Lucos how this campaign works',
        ])->assertOk()
            ->assertJsonPath('html', fn (string $html): bool => str_contains($html, 'New recommendation after the spend change'));
    }

    /**
     * @return array<string, mixed>
     */
    private function suggestionPayload(float $spend): array
    {
        return [
            'from' => '2026-09-09',
            'to' => '2026-10-08',
            'campaign' => [
                'objective' => 'OUTCOME_LEADS',
                'region' => 'US',
                'status' => 'ACTIVE',
            ],
            'delivery' => ['spend' => $spend, 'clicks' => 107],
            'sales' => ['sales' => 4.3],
            'roi' => ['conversions' => 0],
            'health' => 'Needs Optimization',
            'verdict' => [
                'verdict' => 'no_action',
                'recommended_action' => 'NONE',
                'recommended_budget_change_percent' => 0,
            ],
        ];
    }

    public function test_a_json_send_returns_the_reply_without_a_redirect(): void
    {
        CampaignPerformanceChatAgent::fake(['Pause. ROI spent is $89.11 with 0 sales.']);
        $this->actingAs(User::factory()->create());

        $this->postJson(route('campaigns.performance.chat.send'), [
            'message' => 'How is campaign 120249356799650510 doing?',
        ])->assertOk()
            ->assertJsonPath('user', 'How is campaign 120249356799650510 doing?')
            ->assertJsonPath('html', fn (string $html): bool => str_contains($html, 'ROI spent is $89.11'));
    }

    public function test_a_markdown_table_in_the_reply_renders_as_a_table(): void
    {
        CampaignPerformanceChatAgent::fake(["| Campaign | Sales |\n| --- | --- |\n| 1201 | 4 |"]);
        $this->actingAs(User::factory()->create());

        $this->post(route('campaigns.performance.chat.send'), [
            'message' => 'List the top campaigns',
        ])->assertRedirect(route('campaigns.performance.chat'));

        $this->get(route('campaigns.performance.chat'))
            ->assertOk()
            ->assertSee('<th>Campaign</th>', false)
            ->assertSee('<td>1201</td>', false)
            ->assertSee('mb-chat-table-wrap', false);
    }

    public function test_a_markdown_heading_renders_as_bold_without_hash_marks(): void
    {
        CampaignPerformanceChatAgent::fake(['## Lucos - Retargeting - LP Visitors']);
        $this->actingAs(User::factory()->create());

        $this->postJson(route('campaigns.performance.chat.send'), [
            'message' => 'How is Lucos performing?',
        ])->assertOk()
            ->assertJsonPath('html', fn (string $html): bool => str_contains($html, '<strong>Lucos - Retargeting - LP Visitors</strong>')
                && ! str_contains($html, '##'));
    }

    public function test_a_stat_table_uses_the_stats_layout(): void
    {
        CampaignPerformanceChatAgent::fake(["**Chromium Browser**\n\n| Stat | Value |\n| --- | --- |\n| Spend | $0 |\n| CTR | — |"]);
        $this->actingAs(User::factory()->create());

        $this->postJson(route('campaigns.performance.chat.send'), [
            'message' => 'How is Chromium Browser performing?',
        ])->assertOk()
            ->assertJsonPath('html', fn (string $html): bool => str_contains($html, 'mb-chat-stats')
                && str_contains($html, '<td class="mb-chat-stat-label"><strong>Spend</strong></td><td>$0</td><td class="mb-chat-stat-label"><strong>CTR</strong></td>'));
    }

    public function test_a_pipe_inside_a_campaign_name_stays_in_the_campaign_cell(): void
    {
        CampaignPerformanceChatAgent::fake([
            "| Campaign | Campaign ID | Platform | Account ID | Spent |\n| --- | --- | --- | --- | --- |\n| 101\\|New Electric IX SUVs 2025_US_M_MK | 120228855956330510 | meta | 1238155271 | 0 |",
        ]);
        $this->actingAs(User::factory()->create());

        $this->post(route('campaigns.performance.chat.send'), [
            'message' => 'Provide the latest campaigns',
        ])->assertRedirect(route('campaigns.performance.chat'));

        $this->get(route('campaigns.performance.chat'))
            ->assertOk()
            ->assertSee('<td>101|New Electric IX SUVs 2025_US_M_MK</td>', false)
            ->assertSee('<td>120228855956330510</td>', false)
            ->assertSee('<td>meta</td>', false)
            ->assertSee('<td>1238155271</td>', false)
            ->assertDontSee('<td>101\\</td>', false);
    }

    public function test_clearing_the_chat_removes_the_transcript(): void
    {
        $this->actingAs(User::factory()->create());
        session(['campaign_performance_chat' => [
            ['role' => 'user', 'text' => 'Earlier question'],
        ]]);

        $this->post(route('campaigns.performance.chat.reset'))
            ->assertRedirect(route('campaigns.performance.chat'));

        $this->get(route('campaigns.performance.chat'))
            ->assertOk()
            ->assertDontSee('Earlier question');
    }
}
