<?php

namespace Tests\Feature;

use App\Agent\Tools\Campaign\ReviewAssets;
use App\Agent\Workspace;
use App\Models\Asset;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

class MultiPlatformCreativeRatioAdviceTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    private Brief $brief;

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

        Storage::fake('local');

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

        $this->brief = Brief::create([
            'user_id' => $this->user->id,
            'conversation_id' => 'conv-ratio',
            'landing_url' => 'https://example.com/',
        ]);

        app(Workspace::class)->ownedBy($this->user);
        app(Workspace::class)->bindTo('conv-ratio');
    }

    private function createImageAsset(int $width, int $height, string $filename = 'test.png'): Asset
    {
        $im = imagecreatetruecolor($width, $height);
        ob_start();
        imagepng($im);
        $contents = ob_get_clean();
        imagedestroy($im);

        $path = "creatives/{$filename}";
        Storage::disk('local')->put($path, $contents);

        $asset = Asset::create([
            'owner_type' => User::class,
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'upload',
            'disk' => 'local',
            'path' => $path,
            'original_name' => $filename,
            'mime' => 'image/png',
            'bytes' => strlen($contents),
        ]);

        app(Workspace::class)->produced($asset);

        return $asset;
    }

    public function test_asset_calculates_standard_aspect_ratios(): void
    {
        $square = $this->createImageAsset(1080, 1080, 'square.png');
        $this->assertSame('1:1', $square->aspectRatio());

        $vertical = $this->createImageAsset(1080, 1920, 'vertical.png');
        $this->assertSame('9:16', $vertical->aspectRatio());

        $landscape = $this->createImageAsset(1200, 628, 'landscape.png');
        $this->assertSame('1.91:1', $landscape->aspectRatio());

        $feed = $this->createImageAsset(1080, 1350, 'feed.png');
        $this->assertSame('4:5', $feed->aspectRatio());

        $standard = $this->createImageAsset(1200, 900, 'standard.png');
        $this->assertSame('4:3', $standard->aspectRatio());

        $video169 = $this->createImageAsset(1920, 1080, 'widescreen.png');
        $this->assertSame('16:9', $video169->aspectRatio());
    }

    public function test_review_assets_warns_when_creative_ratio_incompatible_with_shared_brief_platform(): void
    {
        // 9:16 vertical is supported on Meta, but not on Google (which accepts 1.91:1, 1:1, 4:5)
        $asset = $this->createImageAsset(1080, 1920, 'story.png');

        $metaCampaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $this->brief->id,
            'name' => 'Meta campaign',
            'platform' => 'meta',
            'ad_account_id' => 'act_123',
            'status' => 'draft',
        ]);

        $googleCampaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $this->brief->id,
            'name' => 'Google campaign',
            'platform' => 'google',
            'ad_account_id' => '3460855874',
            'status' => 'draft',
        ]);

        app(Workspace::class)->produced($metaCampaign);
        app(Workspace::class)->produced($googleCampaign);

        $meta = $this->createMock(Meta::class);
        $metaInstance = $this->createMock(Meta::class);
        $meta->method('on')->willReturn($metaInstance);
        $metaInstance->method('uploadImage')->willReturn('meta_hash_123');

        $tool = new ReviewAssets(
            app(Workspace::class),
            $meta,
        );

        $response = json_decode((string) $tool->handle(new Request([])), true);

        $this->assertTrue($response['ok']);
        $this->assertArrayHasKey('ratio_advice', $response);

        $advice = $response['ratio_advice'];
        $this->assertNotEmpty($advice['incompatible']);
        $this->assertSame($asset->id, $advice['incompatible'][0]['asset_id']);
        $this->assertSame('9:16', $advice['incompatible'][0]['ratio']);
        $this->assertContains('google', $advice['incompatible'][0]['unsupported_on']);
        $this->assertContains('meta', $advice['incompatible'][0]['supported_on']);
    }

    public function test_review_assets_has_no_incompatibility_when_ratios_supported_everywhere(): void
    {
        // 1:1 square is supported on both Meta and Google
        $this->createImageAsset(1080, 1080, 'square.png');

        $metaCampaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $this->brief->id,
            'name' => 'Meta campaign',
            'platform' => 'meta',
            'ad_account_id' => 'act_123',
            'status' => 'draft',
        ]);

        $googleCampaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $this->brief->id,
            'name' => 'Google campaign',
            'platform' => 'google',
            'ad_account_id' => '3460855874',
            'status' => 'draft',
        ]);

        app(Workspace::class)->produced($metaCampaign);
        app(Workspace::class)->produced($googleCampaign);

        $meta = $this->createMock(Meta::class);
        $metaInstance = $this->createMock(Meta::class);
        $meta->method('on')->willReturn($metaInstance);
        $metaInstance->method('uploadImage')->willReturn('meta_hash_123');

        $tool = new ReviewAssets(
            app(Workspace::class),
            $meta,
        );

        $response = json_decode((string) $tool->handle(new Request([])), true);

        $this->assertTrue($response['ok']);
        $this->assertArrayNotHasKey('ratio_advice', $response);
    }
}
