"""Phase 5 — gpt-image-2 E2E integration test + fal markup verification.

ONE real fal.ai call at LOW quality + 1:1 aspect ratio (~$0.009 budgeted;
$0.05 hard ceiling).

Asserts:
  - HTTP success (no exception from dispatch)
  - Output image bytes present + non-empty
  - cost_usd stamped on receipt (non-zero — flags any cost-extraction regression)
  - cost_usd < $0.05 (hard budget ceiling; aborts on overspend)
  - cost_usd < $1.00 (per-shot max ceiling)
  - Measured markup vs OpenAI published rate logged to sidecar

Gated by env var RECOIL_RUN_LIVE_TESTS=1 — defaults to skip so CI / harness
re-runs do not burn billing repeatedly.

Independence from Phase 4: this test does NOT use the Stage-2 plan-pass
template. The payload is constructed directly here.
"""
from __future__ import annotations

import json
import os
from pathlib import Path

import pytest

LIVE = os.environ.get("RECOIL_RUN_LIVE_TESTS") == "1"

# Hardcoded test parameters (Gemini P1-1 resolution).
_TEST_PROMPT = "A simple red square on white background"
_TEST_ASPECT = "1:1"   # → adapter pins to 1024x1024 per SYNTHESIS §11
_TEST_QUALITY = "low"  # ~$0.009 budgeted at 1.5x markup
_HARD_BUDGET_CEILING_USD = 0.05
_PER_SHOT_CEILING_USD = 1.00


@pytest.mark.skipif(not LIVE, reason="set RECOIL_RUN_LIVE_TESTS=1 to enable")
def test_gpt_image_2_low_quality_real_call_budget_under_5_cents():
    """ONE real call. LOW quality. Hard $0.05 ceiling assertion."""
    from recoil.pipeline.core import dispatch, DispatchContext
    from recoil.execution.step_runner import StepRunner
    from recoil.execution.execution_store import ExecutionStore
    from recoil.execution.step_types import ProjectPaths

    store = ExecutionStore(project="_probes", db_path=Path("/tmp/gpt_image_2_e2e_store"))
    paths = ProjectPaths.for_episode("_probes", 1)
    sr = StepRunner(store=store, paths=paths)

    ctx = DispatchContext(
        caller_id="gpt_image_2_e2e",
        step_runner=sr,
        project="_probes", episode=1,
        receipts_log_path="DISABLED",
    )

    receipt = dispatch("image_t2i", {
        "shot_id": "EP001_GPTIMG2_E2E",
        "model": "gpt-image-2",
        "prompt": _TEST_PROMPT,
        "aspect_ratio": _TEST_ASPECT,
        "quality": _TEST_QUALITY,
    }, context=ctx)

    rr = receipt.run_result
    assert rr.success, f"dispatch failed: {rr.error}"
    assert rr.output_path is not None, "no output_path on RunResult"
    out = Path(rr.output_path)
    assert out.exists() and out.stat().st_size > 0, "output file missing or empty"

    cost_usd = (rr.metadata or {}).get("cost_usd")
    assert cost_usd is not None, "cost_usd was not stamped on RunResult.metadata"
    assert cost_usd > 0, (
        f"cost_usd={cost_usd} — fal billing field missing or extractor regressed; "
        f"see _extract_fal_billing_cost_usd in fal.py"
    )
    assert cost_usd < _HARD_BUDGET_CEILING_USD, (
        f"cost ${cost_usd:.4f} breached ${_HARD_BUDGET_CEILING_USD:.2f} ceiling; "
        f"aborting to protect billing"
    )
    assert cost_usd < _PER_SHOT_CEILING_USD, (
        f"cost ${cost_usd:.4f} breached per-shot ${_PER_SHOT_CEILING_USD:.2f} ceiling"
    )

    openai_published_low = 0.006
    multiplier = cost_usd / openai_published_low
    print(
        f"[markup verify] measured=${cost_usd:.4f} "
        f"openai_published=${openai_published_low:.4f} "
        f"multiplier={multiplier:.2f}x (placeholder=1.5x)"
    )

    sidecar = Path("/tmp/gpt_image_2_e2e_measurement.json")
    sidecar.write_text(json.dumps({
        "measured_cost_usd": cost_usd,
        "openai_published_low_usd": openai_published_low,
        "actual_multiplier": multiplier,
        "placeholder_multiplier": 1.5,
        "delta_pct": abs(multiplier - 1.5) / 1.5,
    }))

    forbidden = ("FAL_KEY", "fal_api_key", "Bearer ", "Authorization")
    metadata_str = json.dumps(rr.metadata or {})
    provenance_str = json.dumps(receipt.provenance or {})
    for token in forbidden:
        assert token not in metadata_str, f"leaked '{token}' in metadata"
        assert token not in provenance_str, f"leaked '{token}' in provenance"
