<?php

namespace Tests\Unit\Services\AI;

use App\Services\AI\LaravelAiCreativeBriefResolver;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\StructuredAnonymousAgent;
use RuntimeException;
use Tests\TestCase;

class LaravelAiCreativeBriefResolverTest extends TestCase
{
    public function test_product_url_keeps_certificate_verification_enabled_locally_by_default(): void
    {
        $options = $this->productUrlRequestOptionsForEnvironment('local', true);

        $this->assertNotSame(false, $options['verify'] ?? true);
    }

    public function test_product_url_can_disable_certificate_verification_explicitly(): void
    {
        $options = $this->productUrlRequestOptionsForEnvironment('local', false);

        $this->assertFalse($options['verify']);
    }

    public function test_private_product_urls_are_rejected_before_fetching(): void
    {
        Http::preventStrayRequests();

        try {
            (new LaravelAiCreativeBriefResolver)->fromProductUrl('http://169.254.169.254/latest/meta-data/');
            $this->fail('A private metadata address must not be fetched.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('public product page URL', $exception->getMessage());
        }

        Http::assertNothingSent();
    }

    public function test_product_url_redirects_to_private_addresses_are_rejected(): void
    {
        Http::fake([
            'https://8.8.8.8/*' => Http::response('', 302, ['Location' => 'http://127.0.0.1/admin']),
        ]);

        try {
            (new LaravelAiCreativeBriefResolver)->fromProductUrl('https://8.8.8.8/product');
            $this->fail('A redirect to a private address must not be fetched.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('not publicly reachable', $exception->getMessage());
        }

        Http::assertSentCount(1);
    }

    public function test_it_prioritizes_specific_product_over_marketplace_platform(): void
    {
        Storage::fake('public');
        Http::preventStrayRequests();

        $amazonHtml = <<<'HTML'
<!DOCTYPE html>
<html>
<head>
    <title>Buy Van Heusen Women's Regular Fit Anti Bacterial T-Shirt at Amazon.in</title>
    <meta name="description" content="Buy Van Heusen Women's Regular Fit Proactive Anti Bacterial T-Shirt. 30 days return.">
    <script>var ue_t0 = 12345; window.ue_ihb = 1;</script>
    <style>.nav { display: none; }</style>
</head>
<body>
    <header>Amazon Navigation Bar with Prime Video and Fresh Grocery</header>
    <div id="centerCol">
        <span id="productTitle">Van Heusen Women's Polyester Regular Fit Proactive Anti Bacterial T-Shirt</span>
        <div id="bylineInfo">Brand: Van Heusen</div>
        <div id="corePrice_feature_div"><span class="a-offscreen">₹551.00</span></div>
        <div id="feature-bullets">
            <ul>
                <li>Anti Bacterial, relaxed fit t-shirt made with high stretch fabric for superior comfort.</li>
                <li>Moisture wicking finish keeps you cool and dry during workouts.</li>
            </ul>
        </div>
        <img id="landingImage" data-old-hires="https://m.media-amazon.com/images/I/71Tjjbk1z9L._SL1500_.jpg" src="https://m.media-amazon.com/images/I/71Tjjbk1z9L._SX38_.jpg">
    </div>
    <footer>Amazon Copyright 2026, Prime, Grocery, Alexa</footer>
</body>
</html>
HTML;

        Http::fake([
            'https://www.amazon.in/dp/B08LV7YGGQ*' => Http::response($amazonHtml, 200),
            'https://m.media-amazon.com/*' => Http::response('fake-image-bytes', 200, ['Content-Type' => 'image/jpeg']),
        ]);

        StructuredAnonymousAgent::fake([
            [
                'product_name' => "Van Heusen Women's Anti-Bacterial T-Shirt",
                'project_name' => 'Van Heusen',
                'benefits' => ['Superior comfort with high stretch', 'Moisture wicking keeps you cool and dry'],
                'features' => ['Anti-bacterial fabric', 'Polyester relaxed fit', 'Short sleeve'],
                'images' => ['https://m.media-amazon.com/images/I/71Tjjbk1z9L.jpg'],
                'messaging' => 'Stay fresh, active, and confident during workouts',
                'cta' => 'Order now',
            ],
        ]);

        $resolver = new LaravelAiCreativeBriefResolver;
        $brief = $resolver->fromProductUrl('https://www.amazon.in/dp/B08LV7YGGQ/?');

        $this->assertSame("Van Heusen Women's Anti-Bacterial T-Shirt", $brief->productName);
        $this->assertSame('Van Heusen', $brief->projectName);
        $this->assertContains('Superior comfort with high stretch', $brief->benefits);
        $this->assertContains('Anti-bacterial fabric', $brief->features);

        StructuredAnonymousAgent::assertPrompted(function ($prompt): bool {
            return str_contains($prompt->agent->instructions, 'CRITICAL PRODUCT FOCUS')
                && str_contains($prompt->agent->instructions, 'NEVER create an ad for the marketplace or retailer itself')
                && str_contains($prompt->prompt, "Van Heusen Women's Polyester Regular Fit Proactive Anti Bacterial T-Shirt")
                && str_contains($prompt->prompt, 'Brand/Manufacturer: Van Heusen')
                && str_contains($prompt->prompt, 'Price: ₹551.00')
                && str_contains($prompt->prompt, 'Anti Bacterial, relaxed fit t-shirt made with high stretch fabric')
                && ! str_contains($prompt->prompt, 'var ue_t0');
        });
    }

    public function test_from_prompt_uses_attached_images_as_the_product_visual_reference(): void
    {
        Storage::fake('public');

        Storage::disk('public')->put('creatives/brief-images/shoe.jpg', 'fake-image-bytes');

        StructuredAnonymousAgent::fake([
            [
                'product_name' => 'Acme Running Shoes',
                'project_name' => 'Acme Shoes',
                'benefits' => ['Lighter on every stride'],
                'features' => ['Mesh upper'],
                'visual_description' => 'A white mesh running shoe with a chunky black sole.',
                'handling' => 'handheld',
                'images' => [],
                'messaging' => 'Inspired by a competitor ad',
                'cta' => 'Shop now',
            ],
        ]);

        $resolver = new LaravelAiCreativeBriefResolver;
        $brief = $resolver->fromPrompt(
            "Create an ad inspired by this competitor ad from Acme Shoes:\nSuper Lightweight Running Shoes",
            ['creatives/brief-images/shoe.jpg'],
        );

        $this->assertSame('A white mesh running shoe with a chunky black sole.', $brief->visualDescription);
        $this->assertSame('handheld', $brief->handling);
        $this->assertSame('handheld', $brief->toArray()['handling']);
        $this->assertSame('Acme Shoes', $brief->projectName);
        $this->assertNotEmpty($brief->images);

        StructuredAnonymousAgent::assertPrompted(function ($prompt): bool {
            return str_contains($prompt->agent->instructions, 'attached image is a still of the featured product')
                && str_contains($prompt->prompt, 'Create an ad inspired by this competitor ad from Acme Shoes');
        });
    }

    /** @return array<string, mixed> */
    private function productUrlRequestOptionsForEnvironment(string $environment, bool $verifyTls): array
    {
        $this->app->detectEnvironment(fn (): string => $environment);
        config()->set('creative.url_brief.capture_reference_images', false);
        config()->set('creative.verify_product_url_tls', $verifyTls);
        Http::preventStrayRequests();

        $requestOptions = [];

        Http::fake(function ($request, array $options) use (&$requestOptions) {
            $requestOptions = $options;

            return Http::response('<html><title>Example Product</title></html>', 200);
        });

        StructuredAnonymousAgent::fake([[
            'product_name' => 'Example Product',
            'project_name' => 'Example',
            'benefits' => [],
            'features' => [],
            'visual_description' => 'Example product.',
            'handling' => 'handheld',
            'images' => [],
            'messaging' => 'Example messaging.',
            'cta' => 'Shop now',
        ]]);

        (new LaravelAiCreativeBriefResolver)->fromProductUrl('https://example.com/product');

        return $requestOptions;
    }
}
