<?php

namespace Tests\Feature;

use App\Agent\MarketingAgent;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Models\User;
use App\Services\LandingPageAnalyzer;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use PHPUnit\Framework\Attributes\TestWith;
use RuntimeException;
use Tests\TestCase;

/**
 * Reading the page the user wants to advertise, before anything else is asked.
 *
 * This is the first step of a campaign on every platform, which is why the work
 * sits in a shared service rather than beside one platform's tools: the same
 * page decides the Meta objective and the Google keywords.
 *
 * What these pin: the page is read and summarised, the landing URL is recorded
 * as the user's own answer, nothing else is written, and the analyser cannot be
 * pointed at our own network.
 */
class AnalyzeLandingPageTest extends TestCase
{
    use RefreshDatabase;

    private const PAGE = <<<'HTML'
        <html>
            <head>
                <title>Acme Running Shoes</title>
                <meta name="description" content="Lightweight trail shoes built for long distances.">
            </head>
            <body>
                <h1>Acme Running Shoes</h1>
                <h2>Built for distance</h2>
                <p>Cushioned trail running shoes designed for marathon distance comfort and grip.</p>
            </body>
        </html>
        HTML;

    private const STOCK_ANALYSIS_PAGE = <<<'HTML'
            <html><head><title>Trade Smarter — StockPrices.com</title></head>
            <body>
                <h1>Stock Analysis Platform</h1>
                <p>Real-time market data, advanced analytics, and AI-powered insights for informed trading decisions.</p>
                <form>
                    <label>First Name</label><span>Please provide proper first name!</span>
                    <label>Email</label><span>It must contain a valid email address.</span>
                    <select><option>Select State</option><option>Armed Forces Africa</option><option>California</option></select>
                </form>
            </body></html>
            HTML;

    protected User $user;

    protected function setUp(): void
    {
        parent::setUp();

        MarketingAgent::fake(['Noted.']);

        $this->user = User::factory()->create();
        $this->actingAs($this->user);

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-landing-0001');
        $workspace->ownedBy($this->user);
    }

    private function runTool(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__analyze_landing_page');

        $this->assertNotNull($tool, 'The analyser is not registered.');

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    public function test_it_reports_what_the_page_says(): void
    {
        Http::fake(['https://example.com/*' => Http::response(self::PAGE)]);

        $result = $this->runTool(['url' => 'https://example.com/shoes']);

        $this->assertTrue($result['ok']);
        $this->assertSame('Acme Running Shoes', $result['page']['title']);
        $this->assertSame('Lightweight trail shoes built for long distances.', $result['page']['description']);
        $this->assertContains('Built for distance', $result['page']['headings']);
    }

    /** The suggestions are the point: they turn later questions into confirmations. */
    public function test_it_suggests_a_campaign_name_and_copy(): void
    {
        Http::fake(['https://example.com/*' => Http::response(self::PAGE)]);

        $result = $this->runTool(['url' => 'https://example.com/shoes']);

        // The site, then what the page is about. This was the page's title
        // alone, which named a stockprices campaign "trade smarter" and said
        // nothing about the site. See ACampaignNameStartsWithTheSiteTest.
        $this->assertSame('example-acme-running-shoes', $result['suggestions']['campaign_name']);
        $this->assertContains('Acme Running Shoes', $result['suggestions']['headlines']);
        $this->assertNotEmpty($result['suggestions']['keywords']);
    }

    public function test_form_labels_validation_and_select_options_do_not_become_page_keywords(): void
    {
        Http::fake(['https://example.com/*' => Http::response(self::STOCK_ANALYSIS_PAGE)]);

        $analysis = app(LandingPageAnalyzer::class)->analyze('https://example.com/landing');

        $this->assertContains('stock', $analysis->keywords);
        $this->assertContains('market', $analysis->keywords);
        $this->assertNotContains('select', $analysis->keywords);
        $this->assertNotContains('armed', $analysis->keywords);
        $this->assertNotContains('forces', $analysis->keywords);
        $this->assertNotContains('provide', $analysis->keywords);
        $this->assertNotContains('proper', $analysis->keywords);
        $this->assertNotContains('california', $analysis->keywords);
        $this->assertStringNotContainsString('Please provide proper first name', $analysis->text);
        $this->assertStringNotContainsString('It must contain a valid email address', $analysis->reviewText);
    }

    #[TestWith(['radio'])]
    #[TestWith(['checkbox'])]
    public function test_product_choice_labels_preserve_offer_content_but_not_field_noise(string $type): void
    {
        Http::preventStrayRequests();
        Http::fake(['https://example.com/plans' => Http::response(<<<HTML
            <html><head><title>Plans</title></head><body><form>
                <label for="research-plan"><input id="research-plan" type="{$type}" name="plan">
                    <h2>Unlimited Stock Research</h2>
                    <p>Real-time portfolio analysis and dividend tracking for investors.</p>
                    <span>Plans from \$19 per month.</span>
                    <span class="invalid-feedback">Validationnoise</span>
                </label>
                <label><input type="{$type}" name="alerts"><span>Daily market alerts</span></label>
                <label>Email address<input type="email" name="email"></label>
                <label for="name"><span>First Name</span></label><input id="name">
                <button>Subscribe</button>
            </form></body></html>
            HTML)]);

        $analysis = app(LandingPageAnalyzer::class)->analyze('https://example.com/plans');

        $this->assertContains('Unlimited Stock Research', $analysis->headings);
        $this->assertStringContainsString('dividend tracking', $analysis->text);
        $this->assertStringContainsString('Daily market alerts', $analysis->reviewText);
        $this->assertContains('$19', $analysis->prices);
        $this->assertContains('Subscribe', $analysis->callsToAction);
        foreach (['Email address', 'First Name', 'Validationnoise'] as $noise) {
            $this->assertStringNotContainsString($noise, $analysis->reviewText);
        }
        Http::assertSentCount(1);
    }

    #[TestWith(['form'])]
    #[TestWith(['fieldset'])]
    public function test_signup_wrappers_preserve_the_offer_but_not_control_noise(string $wrapper): void
    {
        Http::preventStrayRequests();
        Http::fake(['https://example.com/landing' => Http::response(<<<HTML
            <html><head><title>Market Tools</title></head><body>
            <{$wrapper} id="signup-wrapper">
                <h1>Stock Analysis Platform</h1>
                <h2>Live Market Alerts</h2>
                <h3>Advanced Trading Insights</h3>
                <p>Follow stocks with real-time charts and market alerts.</p>
                <p>Plans from $19 per month.</p>
                <span>Charts for every trading style.</span>
                <label>Email address</label><input name="email">
                <span role="alert">Validationnoise validationnoise validationnoise</span>
                <span class="invalid-feedback">Requirednoise requirednoise requirednoise</span>
                <select><option>Armed Forces Africa</option><option>California</option><option>Premium $29</option></select>
                <button>Start tracking</button>
            </{$wrapper}><footer>Contact us</footer></body></html>
            HTML)]);

        $analysis = app(LandingPageAnalyzer::class)->analyze('https://example.com/landing');

        $this->assertSame(['Stock Analysis Platform', 'Live Market Alerts'], $analysis->headings);
        $this->assertSame(['Advanced Trading Insights'], $analysis->subheadings);
        $this->assertStringContainsString('Follow stocks with real-time charts', $analysis->text);
        $this->assertStringContainsString('Follow stocks with real-time charts', $analysis->reviewText);
        $this->assertStringContainsString('Charts for every trading style.', $analysis->text);
        $this->assertContains('stock analysis platform', $analysis->keywords);
        $this->assertSame(['$19', '$29'], $analysis->prices);
        $this->assertStringNotContainsString('Premium', $analysis->reviewText);
        $this->assertContains('Start tracking', $analysis->callsToAction);

        foreach (['Email address', 'Validationnoise', 'Requirednoise', 'Armed Forces', 'California'] as $noise) {
            $this->assertStringNotContainsString($noise, $analysis->text);
            $this->assertStringNotContainsString($noise, $analysis->reviewText);
        }
    }

    /**
     * The campaign name must not name a platform.
     *
     * One brief can become a campaign on several platforms, so "… - Google Ads"
     * would be wrong on every platform but one.
     */
    public function test_the_suggested_campaign_name_is_platform_neutral(): void
    {
        Http::fake(['https://example.com/*' => Http::response(self::PAGE)]);

        $name = $this->runTool(['url' => 'https://example.com/shoes'])['suggestions']['campaign_name'];

        $this->assertStringNotContainsStringIgnoringCase('google', $name);
        $this->assertStringNotContainsStringIgnoringCase('meta', $name);
    }

    public function test_it_records_the_url_on_the_campaign_in_focus_as_user_stated(): void
    {
        Http::fake(['https://example.com/*' => Http::response(self::PAGE)]);

        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'draft',
        ]);
        app(Workspace::class)->focusOn($campaign);

        $this->runTool(['url' => 'https://example.com/shoes']);

        $this->assertSame('https://example.com/shoes', $campaign->fresh()->landing_url);
        $this->assertSame(
            ArtifactFieldSource::USER_STATED,
            app(Workspace::class)->sourcesFor($campaign->fresh())['landing_url'] ?? null,
        );
    }

    /** It runs before a campaign exists, so it must not need one. */
    public function test_it_works_with_no_campaign_in_focus(): void
    {
        Http::fake(['https://example.com/*' => Http::response(self::PAGE)]);

        $this->assertTrue($this->runTool(['url' => 'https://example.com/shoes'])['ok']);
    }

    public function test_a_missing_url_asks_for_one_rather_than_failing(): void
    {
        $result = $this->runTool([]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('ask the user', strtolower($result['error']));
    }

    public function test_an_unreadable_page_reports_the_reason(): void
    {
        Http::fake(['https://example.com/*' => Http::response('', 404)]);

        $result = $this->runTool(['url' => 'https://example.com/gone']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('404', $result['error']);
    }

    /**
     * The URL comes from whoever is chatting and the server fetches it.
     *
     * Without this the chat is a request-forgery tool aimed at our own network.
     */
    public function test_it_refuses_private_and_local_addresses(): void
    {
        foreach (['http://localhost/admin', 'http://127.0.0.1/', 'http://thing.local/'] as $url) {
            $result = $this->runTool(['url' => $url]);

            $this->assertFalse($result['ok'], "{$url} was allowed.");
            $this->assertStringContainsString('public landing page', $result['error']);
        }
    }

    public function test_an_unresolvable_host_says_so_rather_than_blaming_the_network(): void
    {
        $result = $this->runTool(['url' => 'https://not-a-real-domain.invalid/']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('could not be found', $result['error']);
    }

    /** The service is the one implementation; the MCP tool and this one both call it. */
    public function test_the_service_refuses_private_hosts_directly(): void
    {
        $this->expectException(RuntimeException::class);

        app(LandingPageAnalyzer::class)->analyze('http://127.0.0.1/');
    }

    /**
     * The page is asked for the way a browser asks for it.
     *
     * With no User-Agent the client sends Guzzle's, and kbb.com, carvana.com,
     * cars.com and edmunds.com all answered 403 to it from this step on prod on
     * 30 Sep. The buyer was told "the page returned HTTP 403" for a URL that
     * opens in their own browser, and the campaign lost every page-derived
     * suggestion. ProductPageScraper sent these headers and was not refused,
     * which is what identified the header rather than the address as the
     * difference.
     *
     * Asserted on the request rather than on a fixture, because a fake answers
     * whatever it is asked and would pass with no headers at all.
     */
    public function test_the_page_is_fetched_with_browser_headers(): void
    {
        Http::fake(['https://example.com/*' => Http::response(self::PAGE)]);

        app(LandingPageAnalyzer::class)->analyze('https://example.com/shoes');

        Http::assertSent(function ($request): bool {
            $agent = $request->header('User-Agent')[0] ?? '';

            return str_contains($agent, 'Mozilla/5.0')
                && str_contains($agent, 'Chrome/')
                && str_contains($request->header('Accept')[0] ?? '', 'text/html')
                && str_contains($request->header('Accept-Language')[0] ?? '', 'en');
        });
    }
}
