"""Cockpit ORM tables create cleanly and the registry seed is well-formed."""
from __future__ import annotations

from sqlalchemy import create_engine, inspect

from fxhnt.adapters.persistence.cockpit_models import CockpitBase
from fxhnt.registry import STRATEGY_REGISTRY


def test_cockpit_tables_create() -> None:
    eng = create_engine("sqlite://", future=True)
    CockpitBase.metadata.create_all(eng)
    tables = set(inspect(eng).get_table_names())
    assert {"forward_nav", "forward_summary", "strategy_registry"} <= tables


def test_registry_entries_have_required_fields() -> None:
    assert STRATEGY_REGISTRY, "registry must not be empty"
    for sid, e in STRATEGY_REGISTRY.items():
        assert e["display_name"] and e["sleeve"] and "state_file" in e
        assert "gate_spec" in e and "min_days" in e["gate_spec"]


import datetime as dt

from fxhnt.adapters.persistence.forward_nav import ForwardNavRepo
from fxhnt.application.forward_models import ForwardNavRow as Row
from fxhnt.application.forward_models import ForwardSummary


def _repo() -> ForwardNavRepo:
    repo = ForwardNavRepo("sqlite://")   # shared in-memory engine held by the repo
    repo.migrate()
    return repo


def test_upsert_rows_is_idempotent() -> None:
    repo = _repo()
    rows = [Row("combined", "2026-06-05", 0.01, 1.01), Row("combined", "2026-06-06", 0.0099, 1.0201)]
    at = dt.datetime(2026, 6, 14, 23, 30)
    repo.upsert_rows(rows, at)
    repo.upsert_rows(rows, at)                       # second time = no dupes
    got = repo.nav_history("combined")
    assert [r.date for r in got] == ["2026-06-05", "2026-06-06"]


def test_upsert_rows_updates_existing_value() -> None:
    repo = _repo()
    at = dt.datetime(2026, 6, 14, 23, 30)
    repo.upsert_rows([Row("x", "2026-06-05", 0.01, 1.01)], at)
    repo.upsert_rows([Row("x", "2026-06-05", 0.02, 1.02)], at)   # same key, new value
    got = repo.nav_history("x")
    assert len(got) == 1 and got[0].nav == 1.02


def test_upsert_summary_and_fetch() -> None:
    repo = _repo()
    s = ForwardSummary("x", "2026-06-12", 7, 1.05, 0.05, 1.2, -0.04)
    repo.upsert_summary(s, "GO", "7d ok", dt.datetime(2026, 6, 14))
    got = {r.strategy_id: r for r in repo.all_summaries()}
    assert got["x"].nav == 1.05 and got["x"].gate_status == "GO"


def test_all_nav_histories_groups_by_strategy() -> None:
    repo = _repo()
    at = dt.datetime(2026, 6, 14, 23, 30)
    repo.upsert_rows([
        Row("a", "2026-06-04", 0.01, 1.01),
        Row("a", "2026-06-05", 0.02, 1.03),
    ], at)
    repo.upsert_rows([
        Row("b", "2026-06-05", 0.03, 1.03),
    ], at)
    got = repo.all_nav_histories()
    # "a" has 2 rows, "b" has 1 row
    assert set(got.keys()) >= {"a", "b"}
    assert len(got["a"]) == 2
    assert len(got["b"]) == 1
    # dates are ISO strings, ordered ascending
    assert [r.date for r in got["a"]] == ["2026-06-04", "2026-06-05"]
    assert got["b"][0].date == "2026-06-05"
