<?php

namespace Tests\Feature;

use App\Agent\Instructions;
use App\Agent\Workspace;
use App\Models\Asset;
use App\Models\Brief;
use App\Models\Creative;
use App\Models\User;
use App\Support\AssetOriginal;
use Illuminate\Filesystem\FilesystemAdapter as Filesystem;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Local\LocalFilesystemAdapter as LocalAdapter;
use Tests\TestCase;

/**
 * Two reports from production on 7 Oct, both reproduced from the stored chat.
 *
 * "I tried adding another creative for which it asked me to create new one and i
 * did but it fails to retrieve", 3:49 PM, and "i tried using new chat to add
 * creative but it is not letting me proceed", 3:54 PM. Different causes.
 *
 * The first: import_creatives said "Creative 14 is attached here, but its original
 * file is unavailable, so it couldn't be uploaded to the ad account". It was
 * available. Fetching the exact path on the asset row from production returned 200
 * and 1,240,773 bytes, matching assets.bytes exactly, and nothing distinguished it
 * from creative 10 which the same reply was still offering. A single
 * Storage::exists() decided it, and a stat can be wrong in ways a file is not.
 *
 * The second is in the transcript verbatim:
 *
 *   10:22:34  i want to add a new ad creative to an existing campaign
 *   10:22:57  Use ad account act_1950320145707342
 *   10:23:29  can you list down campaigns from the selected ad account
 *             -> "What are you promoting? Paste the URL of the page the ads
 *                should send people to."
 *
 * He asked twice and got the brief's opening question both times, because that
 * question is emitted whenever no campaign is in focus and nothing told it that
 * an existing campaign is a different situation.
 */
class TwoThingsMohsinCouldNotDoTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

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

    // ------------------------------------- 1. the creative that was there

    private function creative(string $path, bool $writeFile = true): Creative
    {
        Storage::fake('public');

        if ($writeFile) {
            Storage::disk('public')->put($path, 'png-bytes');
        }

        $asset = Asset::create([
            'owner_type' => $this->user->getMorphClass(),
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'public',
            'path' => $path,
            'original_name' => 'attestpath.png',
            'mime' => 'image/png',
            'bytes' => 1240773,
            'checksum' => 'sum-'.md5($path),
        ]);

        return Creative::create([
            'user_id' => $this->user->id,
            'type' => 'image',
            'source' => 'generated',
            'status' => 'completed',
            'asset_id' => $asset->id,
            'title' => 'attestpath-manual-to-ai-soc-2-prep_Image',
        ]);
    }

    public function test_a_creative_whose_file_is_present_is_readable(): void
    {
        $creative = $this->creative('creatives/images/lECe3BMj.png');

        $this->assertTrue(AssetOriginal::isReadable($creative->asset));
        $this->assertFalse(AssetOriginal::isMissing($creative->asset));
    }

    /**
     * The case that matters: exists() says no and the bytes are there anyway.
     *
     * This is the condition production was in and the reason the whole class
     * exists. It is constructed directly rather than reproduced, because I could
     * not reproduce it: the file was served from the stored path twelve times out
     * of twelve, its last-modified matched assets.updated_at to the second, and it
     * had been on disk for six minutes by the time the tool said it was gone. Why
     * the stat disagreed is still unknown and needs a look at the box.
     *
     * So this does not assert a cause. It asserts the only thing worth asserting
     * without one: when a disk's exists() and its bytes disagree, the bytes win,
     * because the bytes are what the upload needs. A Storage::fake cannot express
     * that disagreement - it is a real local disk and its exists() tells the truth
     * - which is exactly why an earlier version of this test passed against a bare
     * exists() and proved nothing at all.
     */
    public function test_the_bytes_win_when_exists_disagrees_with_them(): void
    {
        $lying = new class extends Filesystem
        {
            public function __construct()
            {
                parent::__construct(new \League\Flysystem\Filesystem(new LocalAdapter(sys_get_temp_dir())), new LocalAdapter(sys_get_temp_dir()));
            }

            public function exists($path): bool
            {
                return false;
            }

            public function readStream($path)
            {
                return fopen('php://memory', 'r');
            }
        };

        Storage::set('lying-disk', $lying);

        $asset = Asset::create([
            'owner_type' => $this->user->getMorphClass(),
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'lying-disk',
            'path' => 'creatives/images/lECe3BMj.png',
            'original_name' => 'attestpath.png',
            'mime' => 'image/png',
            'bytes' => 1240773,
            'checksum' => 'sum-lying',
        ]);

        $this->assertFalse(Storage::disk('lying-disk')->exists($asset->path), 'the premise');
        $this->assertTrue(
            AssetOriginal::isReadable($asset),
            'exists() said no, the bytes were readable, and the buyer was told their file had gone',
        );
    }

    /** When neither agrees it is there, it is not there. */
    public function test_an_unreadable_stream_is_still_missing(): void
    {
        $silent = new class extends Filesystem
        {
            public function __construct()
            {
                parent::__construct(new \League\Flysystem\Filesystem(new LocalAdapter(sys_get_temp_dir())), new LocalAdapter(sys_get_temp_dir()));
            }

            public function exists($path): bool
            {
                return false;
            }

            public function readStream($path)
            {
                return null;
            }
        };

        Storage::set('silent-disk', $silent);

        $asset = Asset::create([
            'owner_type' => $this->user->getMorphClass(),
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'silent-disk',
            'path' => 'creatives/images/gone.png',
            'original_name' => 'gone.png',
            'mime' => 'image/png',
            'bytes' => 10,
            'checksum' => 'sum-silent',
        ]);

        $this->assertTrue(AssetOriginal::isMissing($asset));
    }

    /** A file that really is absent is still reported absent. */
    public function test_a_genuinely_missing_file_is_still_missing(): void
    {
        $creative = $this->creative('creatives/images/never-written.png', writeFile: false);

        $this->assertTrue(AssetOriginal::isMissing($creative->asset));
    }

    /** And the degenerate rows, without throwing. */
    public function test_rows_with_nothing_to_read_are_missing_not_fatal(): void
    {
        Storage::fake('public');

        $this->assertTrue(AssetOriginal::isMissing(null));

        $blank = Asset::create([
            'owner_type' => $this->user->getMorphClass(),
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'public',
            'path' => '',
            'original_name' => 'x.png',
            'mime' => 'image/png',
            'bytes' => 0,
            'checksum' => 'sum-blank',
        ]);

        $this->assertTrue(AssetOriginal::isMissing($blank));

        $gone = Asset::create([
            'owner_type' => $this->user->getMorphClass(),
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'a-disk-that-is-not-configured',
            'path' => 'creatives/images/x.png',
            'original_name' => 'x.png',
            'mime' => 'image/png',
            'bytes' => 10,
            'checksum' => 'sum-gone',
        ]);

        $this->assertTrue(AssetOriginal::isMissing($gone), 'an unknown disk should be missing, not an exception');
    }

    /** The chooser and the uploader must agree, or one offers what the other refuses. */
    public function test_the_chooser_and_the_uploader_ask_the_same_question(): void
    {
        foreach ([
            'app/Agent/Tools/Campaign/ImportCreatives.php',
            'app/Agent/Tools/Campaign/ReviewAssets.php',
        ] as $file) {
            $source = file_get_contents(base_path($file));

            $this->assertStringContainsString('AssetOriginal::isMissing', $source, $file.' still decides on its own');
            $this->assertStringNotContainsString(
                'exists($asset->path)',
                $source,
                $file.' is back to a bare exists()',
            );
        }
    }

    // --------------------------- 2. the chat that would not let him proceed

    private function prompt(): string
    {
        Brief::create([
            'user_id' => $this->user->id,
            'conversation_id' => 'conv-mohsin',
        ]);

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

        return app(Instructions::class)->build();
    }

    /** The opening question is still asked, because a new campaign still needs it. */
    public function test_the_opening_question_is_still_there(): void
    {
        $this->assertStringContainsString('What are you promoting?', $this->prompt());
    }

    /**
     * And it now says it does not apply to a campaign that already exists.
     *
     * Asserted on the instruction rather than on a model reply, because the defect
     * is that the instruction gave the model no way to do anything else.
     */
    public function test_it_no_longer_applies_to_an_existing_campaign(): void
    {
        $prompt = $this->prompt();

        $this->assertStringContainsString('already exists', $prompt);
        $this->assertStringContainsString('list_campaigns', $prompt);
        $this->assertStringContainsString('open_campaign', $prompt);
    }

    /** Including the three things he actually asked for. */
    public function test_the_exception_covers_what_he_asked_for(): void
    {
        $prompt = $this->prompt();

        foreach (['which ones there are', 'ad account to look in', 'add a creative'] as $phrase) {
            $this->assertStringContainsString($phrase, $prompt, 'the exception does not cover: '.$phrase);
        }
    }

    /**
     * The creative list must be re-read when the user says they have made one.
     *
     * Kaushal, 08:55 to 08:59. He was offered three creatives, which was right -
     * creative 13 "Attespath" did not exist until 08:57:46. It then sat unlisted
     * while the conversation held the earlier options, and he had to ask "Can
     * check for Attespath creative in adstudio ?" before anything looked again.
     * Mohsin hit the same snapshot at 10:16 and was told the new creative "isn't
     * available to import yet".
     */
    public function test_the_creative_list_is_re_read_when_the_user_says_they_made_one(): void
    {
        $prompt = $this->prompt();

        $this->assertStringContainsString('The creative list is a snapshot', $prompt);
        $this->assertStringContainsString('call import_creatives again with no ids', $prompt);
        $this->assertStringContainsString('never tell them a creative', $prompt);
    }

    /** And it must not be asked a second time once a campaign is in focus. */
    public function test_it_says_not_to_ask_again(): void
    {
        $this->assertStringContainsString('do not ask this question again', $this->prompt());
    }
}
