"""REC-217: FloraAdapter.direct_submit_image — synchronous submit/poll/download.

No network. The single HTTP seam (FloraAdapter._http_json) and the image
downloader (_download_video) are monkeypatched; build_submit runs for real on a
t2i payload (no image inputs → no upload), so the body assembly + parse_submit
+ parse_poll wiring is exercised end-to-end.
"""

from __future__ import annotations

import pytest

import recoil.execution.lib.http_helpers as http_helpers
from recoil.execution.providers.base import UnifiedVideoPayload
from recoil.execution.providers.flora import FloraAdapter


@pytest.fixture(autouse=True)
def _flora_env(monkeypatch):
    monkeypatch.setenv("FLORA_API_KEY", "ak_test")
    monkeypatch.setenv("RECOIL_FLORA_WORKSPACE", "ws_test")
    monkeypatch.setenv("RECOIL_FLORA_PROJECT", "prj_test")
    # deterministic + no real waiting
    monkeypatch.setattr("time.sleep", lambda *_a, **_k: None)


def _queue_http(monkeypatch, responses):
    """Patch _http_json to return queued responses in order."""
    calls = iter(responses)

    def _fake(self, method, url, headers, body):  # noqa: ANN001
        return next(calls)

    monkeypatch.setattr(FloraAdapter, "_http_json", _fake)


def test_direct_submit_image_t2i_happy_path(monkeypatch):
    _queue_http(
        monkeypatch,
        [
            # submit → POST /generate
            {
                "run_id": "run_x",
                "poll_url": "https://app.flora.ai/api/v1/runs/run_x",
                "charged_cost": 0.039,
            },
            # poll #1 → still running
            {"status": "running"},
            # poll #2 → completed with a hosted image output
            {
                "status": "completed",
                "outputs": [{"type": "imageUrl", "url": "https://hosted/img.png"}],
            },
        ],
    )
    monkeypatch.setattr(http_helpers, "_download_video", lambda url, **k: b"PNGBYTES")

    payload = UnifiedVideoPayload(prompt="a red cube on white", model_id="nano-banana")
    out = FloraAdapter().direct_submit_image(payload)

    assert out == {
        "image_bytes": b"PNGBYTES",
        "cost_usd": 0.039,
        "native_id": "run_x",
    }


def test_direct_submit_image_failed_raises(monkeypatch):
    _queue_http(
        monkeypatch,
        [
            {"run_id": "run_y", "poll_url": "https://app.flora.ai/api/v1/runs/run_y"},
            {"status": "failed", "error_code": "BILLING_NOT_ENOUGH_CREDITS"},
        ],
    )
    payload = UnifiedVideoPayload(prompt="x", model_id="nano-banana")
    with pytest.raises(RuntimeError, match="Flora image generation failed"):
        FloraAdapter().direct_submit_image(payload)


def test_direct_submit_image_completed_without_output_raises(monkeypatch):
    _queue_http(
        monkeypatch,
        [
            {"run_id": "run_z", "poll_url": "https://app.flora.ai/api/v1/runs/run_z"},
            {"status": "completed", "outputs": []},
        ],
    )
    payload = UnifiedVideoPayload(prompt="x", model_id="nano-banana")
    with pytest.raises(RuntimeError, match="no output URL"):
        FloraAdapter().direct_submit_image(payload)
