<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * The budget question offers an amount of your own, and checks the floor.
 *
 * Two halves of one report from arb-dev: "we dont have the option for entering
 * the budget manually?"
 *
 * The question had always said "Pick one or type any amount up to USD 500", and
 * the tool's own result tells the model to "mention they can type any amount
 * instead", so typing was the intended path. Nothing on screen offered it. The
 * rungs are 5, 10, 20, 50 and 100 filtered to what the floor and the ceiling
 * allow, so on a campaign with a high floor or a low ceiling the ladder comes
 * down to one or two tiles and an amount between them reads as unavailable.
 * Choices::offer() has taken an allowOther flag the whole time, which draws an
 * "Other" tile and an input; three other tools pass it and this one did not.
 *
 * Offering it widens a known trap, which is the second half. A typed total
 * across several platforms has been checked against their combined floor since a
 * buyer on arb-dev typed 10 for three platforms and only found out two turns
 * later at the split. A single platform had no such check: any amount above zero
 * was taken, and Meta's 5.00 floor was first mentioned by the publish gate once
 * every other question had been answered. Unreachable from the rungs, which
 * never go below the floor. Reachable the moment you can type.
 */
class ABudgetCanBeTypedRatherThanPickedTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            'platforms.guardrails.max_daily_budget' => 500,
            'platforms.guardrails.confirm_daily_budget_above' => 400,
        ]);

        $this->actingAs(User::factory()->create());
        app(Workspace::class)->bindTo('conv-typed-budget');
        app(Workspace::class)->ownedBy(auth()->user());
    }

    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Meta campaign',
            'platform' => 'meta',
            'status' => 'draft',
            'currency' => 'USD',
            'budget_mode' => 'daily',
            'budget_level' => 'campaign',
            ...$attributes,
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    /** @return array<string,mixed> */
    private function setBudget(array $arguments = []): array
    {
        $result = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__set_campaign_budget')
            ->handle(new Request($arguments));

        return json_decode((string) $result, true);
    }

    /** @return array<string,mixed>|null */
    private function offerFor(string $field): ?array
    {
        return collect(app(Choices::class)->all())->first(fn (array $o): bool => $o['field'] === $field);
    }

    // ------------------------------------------------- an amount of your own

    /** The defect: the rungs were the only thing on screen. */
    public function test_the_amounts_question_offers_an_amount_of_your_own(): void
    {
        $this->campaign();
        $this->setBudget();

        $offer = $this->offerFor('budget_amount');

        $this->assertNotNull($offer, 'no amounts were offered at all');
        $this->assertTrue(
            $offer['allow_other'] ?? false,
            'The question says "or type any amount" and nothing on screen lets them.',
        );
    }

    /** The rungs are still there beside it. */
    public function test_the_suggested_amounts_are_still_offered(): void
    {
        $this->campaign();
        $this->setBudget();

        $this->assertNotEmpty($this->offerFor('budget_amount')['options'] ?? []);
    }

    /**
     * And the other budget question is untouched.
     *
     * How the budget works is a closed list of what the platform supports, so a
     * free-text answer there is not an amount, it is an unpublishable mode.
     */
    public function test_the_strategy_question_does_not_take_a_free_answer(): void
    {
        $this->campaign(['budget_level' => null, 'budget_mode' => null]);
        $this->setBudget();

        $strategy = $this->offerFor('budget_strategy');

        $this->assertNotNull($strategy, 'Meta has more than one way to hold a budget, so it should be asked.');
        $this->assertFalse($strategy['allow_other'] ?? false);
    }

    // ------------------------------------------------------- the floor check

    /** Below what the one platform will take, refused here with the number. */
    public function test_an_amount_below_the_platform_floor_is_refused(): void
    {
        $campaign = $this->campaign();

        $result = $this->setBudget(['amount' => 3]);

        $this->assertFalse($result['ok'], 'Meta will not run on 3.00 a day.');
        $this->assertStringContainsString('5.00', $result['error']);
        $this->assertStringContainsString('Meta', $result['error']);
        $this->assertSame(0.0, (float) $campaign->fresh()->budget, 'the refused amount was written anyway');
    }

    /** Exactly the floor is allowed: it is a minimum, not a threshold to clear. */
    public function test_the_floor_itself_is_accepted(): void
    {
        $campaign = $this->campaign();

        $result = $this->setBudget(['amount' => 5]);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
        $this->assertSame(5.0, (float) $campaign->fresh()->budget);
    }

    /** An ordinary amount is unaffected. */
    public function test_an_amount_above_the_floor_is_set(): void
    {
        $campaign = $this->campaign();

        $this->assertTrue($this->setBudget(['amount' => 37.5])['ok'] ?? false);
        $this->assertSame(37.5, (float) $campaign->fresh()->budget);
    }

    /**
     * A lifetime total is left to the gate, as the ceiling already is.
     *
     * What a total works out to per day is not known until there is an end date,
     * so a daily floor cannot judge it and guessing here would refuse totals
     * that are perfectly runnable over a long enough run.
     */
    public function test_a_lifetime_total_is_not_judged_against_the_daily_floor(): void
    {
        $this->campaign(['budget_mode' => 'lifetime']);

        $result = $this->setBudget(['amount' => 3]);

        $this->assertTrue($result['ok'] ?? false, $result['error'] ?? '');
    }

    /**
     * And a multi-platform total still gets the combined-floor message.
     *
     * The two checks answer different questions and the new one must not take
     * the other's case: this amount is a total to divide, and what it is refused
     * against is what the platforms need between them.
     */
    public function test_a_multi_platform_total_still_names_the_combined_floor(): void
    {
        $brief = Brief::create(['user_id' => auth()->id(), 'conversation_id' => 'conv-typed-budget']);

        $meta = $this->campaign(['brief_id' => $brief->id]);
        Campaign::create([
            'user_id' => auth()->id(), 'brief_id' => $brief->id,
            'name' => 'LinkedIn campaign', 'platform' => 'linkedin', 'status' => 'draft',
            'currency' => 'USD', 'budget_mode' => 'daily', 'budget_level' => 'campaign',
        ]);

        app(Workspace::class)->focusOn($meta);

        $result = $this->setBudget(['amount' => 6]);

        $this->assertFalse($result['ok'], '6.00 cannot be divided across Meta and LinkedIn.');
        $this->assertStringContainsString('between them', $result['error']);
    }
}
