from __future__ import annotations

from fastapi.testclient import TestClient
from typer.testing import CliRunner

from tests.support import seed_options_context
from uforia.api.app import create_app
from uforia.api.settings import ApiSettings
from uforia import cli as cli_module
from uforia.cli import app
from uforia.storage import DatasetName, DatasetStore


def test_alpha_canvas_cli_smoke_builds_populated_data(tmp_path, monkeypatch) -> None:
    store = DatasetStore(tmp_path)
    seed_options_context(store)
    monkeypatch.setattr(cli_module, "_store", lambda: store)

    runner = CliRunner()
    result = runner.invoke(
        app,
        [
            "build",
            "alpha-canvas",
            "--start",
            "2026-03-01T00:00:00+00:00",
            "--end",
            "2026-03-03T00:00:00+00:00",
            "--underlyings",
            "BTC,ETH",
        ],
    )

    assert result.exit_code == 0, result.stdout
    assert "Built alpha canvas for BTC, ETH" in result.stdout
    for dataset in (
        DatasetName.OPTIONS_SURFACE_FACTOR_SERIES,
        DatasetName.OPTIONS_ML_CARRY_SERIES,
        DatasetName.OPTIONS_EXPIRY_FLOW_SERIES,
        DatasetName.OPTIONS_ADAPTIVE_HEDGE_SERIES,
        DatasetName.OPTIONS_SESSIONALITY_SERIES,
        DatasetName.OPTIONS_DISPERSION_SERIES,
        DatasetName.OPTIONS_FUNDING_SKEW_SERIES,
        DatasetName.OPTIONS_SIGNAL_SERIES,
    ):
        assert store.read(dataset).height > 0


def test_alpha_canvas_outputs_latest_values_for_options_dashboards(tmp_path, monkeypatch) -> None:
    store = DatasetStore(tmp_path)
    seed_options_context(store)
    monkeypatch.setattr(cli_module, "_store", lambda: store)

    runner = CliRunner()
    result = runner.invoke(
        app,
        [
            "build",
            "alpha-canvas",
            "--start",
            "2026-03-01T00:00:00+00:00",
            "--end",
            "2026-03-03T00:00:00+00:00",
            "--underlyings",
            "BTC,ETH",
        ],
    )
    assert result.exit_code == 0, result.stdout

    app_instance = create_app(settings=ApiSettings(data_root=tmp_path), store=store)
    client = TestClient(app_instance)
    latest = client.get(
        "/api/v1/options/ml_carry_toxicity/latest",
        params={"underlying": "BTC"},
    )

    assert latest.status_code == 200
    payload = latest.json()["data"]
    assert payload["latest_quality"] == "ok"
    assert payload["latest_values"]["net_carry_score"] is not None
