from __future__ import annotations

from datetime import datetime, timezone

from typer.testing import CliRunner

from tests.support import seed_options_context
from uforia import cli as cli_module
from uforia.cli import app
from uforia.storage import DatasetName, DatasetStore


def test_composite_cli_skip_market_avoids_market_write(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",
            "composite",
            "--asset",
            "BTC",
            "--start",
            "2026-03-02T00:00:00+00:00",
            "--end",
            "2026-03-03T23:00:00+00:00",
            "--skip-market",
        ],
    )

    assert result.exit_code == 0, result.stdout
    assert "Wrote 1 composite partitions for BTC" in result.stdout
    written = store.read(DatasetName.COMPOSITE_SIGNAL_SERIES)
    assert set(written.get_column("asset").unique().to_list()) == {"BTC"}


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

    btc = cli_module.build_composite_signal_series(
        store,
        datetime(2026, 3, 2, 0, tzinfo=timezone.utc),
        datetime(2026, 3, 3, 23, tzinfo=timezone.utc),
        asset="BTC",
    )
    eth = cli_module.build_composite_signal_series(
        store,
        datetime(2026, 3, 2, 0, tzinfo=timezone.utc),
        datetime(2026, 3, 3, 23, tzinfo=timezone.utc),
        asset="ETH",
    )
    store.write(DatasetName.COMPOSITE_SIGNAL_SERIES, btc)
    store.write(DatasetName.COMPOSITE_SIGNAL_SERIES, eth)

    runner = CliRunner()
    result = runner.invoke(
        app,
        [
            "build",
            "composite-market",
            "--start",
            "2026-03-02T00:00:00+00:00",
            "--end",
            "2026-03-03T23:00:00+00:00",
        ],
    )

    assert result.exit_code == 0, result.stdout
    assert "Wrote 1 market composite partitions" in result.stdout
    market = store.read(
        DatasetName.COMPOSITE_SIGNAL_SERIES,
        filters={"asset": "MARKET", "scope": "market", "source": "composite_v1"},
    )
    assert market.height > 0
