<?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 Tests\TestCase;

class LaravelAiCreativeBriefResolverTest extends TestCase
{
    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');
        });
    }
}
