"""Persist execution fills + TCA into the cockpit DB (so the dashboard can show live execution + cost)."""
from __future__ import annotations

import datetime as dt

from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool

from fxhnt.adapters.persistence.cockpit_models import CockpitBase, ExecFillRow


class ExecStore:
    def __init__(self, dsn: str) -> None:
        kw = {"future": True}
        if dsn == "sqlite://":
            kw |= {"connect_args": {"check_same_thread": False}, "poolclass": StaticPool}
        self._engine = create_engine(dsn, **kw)
        CockpitBase.metadata.create_all(self._engine)

    def record(self, *, client_id: str, rebalance_id: str, symbol: str, side: str, qty: float,
               price: float, fee: float, status: str, shortfall_bps: float, at: dt.datetime) -> None:
        with Session(self._engine) as s:
            s.merge(ExecFillRow(client_id=client_id, rebalance_id=rebalance_id, symbol=symbol, side=side,
                                qty=qty, price=price, fee=fee, status=status, shortfall_bps=shortfall_bps, at=at))
            s.commit()

    def fills(self, rebalance_id: str) -> list[ExecFillRow]:
        stmt = select(ExecFillRow).where(ExecFillRow.rebalance_id == rebalance_id)
        with Session(self._engine) as s:
            return list(s.scalars(stmt))
