from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from uuid import uuid4

import orjson
import polars as pl

from uforia.config import AppConfig
from uforia.storage import DatasetName, DatasetStore, ReadMode

from .live import create_live_client
from .models import (
    VENUE_CAPABILITIES,
    ExecutionAccountConfig,
    ExecutionActionResult,
    ExecutionCancelAllRequest,
    ExecutionCancelRequest,
    ExecutionFailureCode,
    ExecutionIntent,
    ExecutionOrderStatus,
    ExecutionQuoteRequest,
    ExecutionRequestMode,
    ExecutionSettingsView,
    ExecutionVenue,
    ExecutionVenueHealth,
)


class ExecutionService:
    def __init__(self, store: DatasetStore, config: AppConfig) -> None:
        self.store = store
        self.config = config
        self.execution = config.execution
        self._live_clients: dict[tuple[str, str], Any] = {}

    def settings_view(self) -> ExecutionSettingsView:
        default_mode = ExecutionRequestMode(self.execution.default_mode)
        return ExecutionSettingsView(
            accounts_config_path=self.execution.accounts_config_path,
            default_mode=default_mode,
            global_kill_switch=self.execution.global_kill_switch,
            max_order_notional_usd=self.execution.max_order_notional_usd,
            max_position_notional_usd=self.execution.max_position_notional_usd,
        )

    def list_venues(self) -> list[dict[str, Any]]:
        return [cap.model_dump(mode="json") for cap in VENUE_CAPABILITIES.values()]

    def list_accounts(self) -> list[ExecutionAccountConfig]:
        return _load_accounts(self.execution.accounts_config_path)

    def list_markets(
        self,
        venue: str | None = None,
        asset: str | None = None,
    ) -> list[dict[str, Any]]:
        filters: dict[str, Any] = {}
        if venue:
            filters["venue"] = venue
        if asset:
            filters["asset"] = asset.upper()
        latest = self.store.read_latest(DatasetName.EXECUTION_MARKET_SNAPSHOT, filters=filters)
        if latest.is_empty() and self.execution.enabled:
            self.sync_live_state(venue=venue, asset=asset.upper() if asset else None)
            latest = self.store.read_latest(DatasetName.EXECUTION_MARKET_SNAPSHOT, filters=filters)
        if not latest.is_empty():
            return latest.sort(["venue", "asset", "symbol"]).to_dicts()
        return _default_market_rows(asset=asset, venue=venue)

    def list_orders(
        self,
        *,
        venue: str | None = None,
        account: str | None = None,
        asset: str | None = None,
        status: str | None = None,
        limit: int = 100,
    ) -> list[dict[str, Any]]:
        filters = _clean_filters(
            {"venue": venue, "account": account, "asset": asset.upper() if asset else None}
        )
        frame = self.store.read(
            DatasetName.EXECUTION_ORDER_EVENT,
            filters=filters,
            read_mode=ReadMode.ALL_RUNS,
        )
        if frame.is_empty() and self.execution.enabled:
            self.sync_live_state(
                venue=venue,
                account=account,
                asset=asset.upper() if asset else None,
            )
            frame = self.store.read(
                DatasetName.EXECUTION_ORDER_EVENT,
                filters=filters,
                read_mode=ReadMode.ALL_RUNS,
            )
        if status:
            frame = frame.filter(pl.col("status") == status)
        return frame.sort("ts", descending=True).head(limit).to_dicts()

    def list_fills(
        self,
        *,
        venue: str | None = None,
        account: str | None = None,
        asset: str | None = None,
        limit: int = 100,
    ) -> list[dict[str, Any]]:
        filters = _clean_filters(
            {"venue": venue, "account": account, "asset": asset.upper() if asset else None}
        )
        frame = self.store.read(
            DatasetName.EXECUTION_FILL_EVENT,
            filters=filters,
            read_mode=ReadMode.ALL_RUNS,
        )
        if frame.is_empty() and self.execution.enabled:
            self.sync_live_state(
                venue=venue,
                account=account,
                asset=asset.upper() if asset else None,
            )
            frame = self.store.read(
                DatasetName.EXECUTION_FILL_EVENT,
                filters=filters,
                read_mode=ReadMode.ALL_RUNS,
            )
        return frame.sort("ts", descending=True).head(limit).to_dicts()

    def list_positions(
        self,
        *,
        venue: str | None = None,
        account: str | None = None,
        asset: str | None = None,
    ) -> list[dict[str, Any]]:
        filters = _clean_filters(
            {"venue": venue, "account": account, "asset": asset.upper() if asset else None}
        )
        frame = self.store.read_latest(DatasetName.EXECUTION_POSITION_SNAPSHOT, filters=filters)
        if frame.is_empty() and self.execution.enabled:
            self.sync_live_state(
                venue=venue,
                account=account,
                asset=asset.upper() if asset else None,
            )
            frame = self.store.read_latest(DatasetName.EXECUTION_POSITION_SNAPSHOT, filters=filters)
        return frame.sort(["venue", "account", "asset", "symbol"]).to_dicts()

    def list_balances(
        self,
        *,
        venue: str | None = None,
        account: str | None = None,
    ) -> list[dict[str, Any]]:
        frame = self.store.read_latest(
            DatasetName.EXECUTION_BALANCE_SNAPSHOT,
            filters=_clean_filters({"venue": venue, "account": account}),
        )
        if frame.is_empty() and self.execution.enabled:
            self.sync_live_state(venue=venue, account=account)
            frame = self.store.read_latest(
                DatasetName.EXECUTION_BALANCE_SNAPSHOT,
                filters=_clean_filters({"venue": venue, "account": account}),
            )
        return frame.sort(["venue", "account", "asset"]).to_dicts()

    def get_health(self) -> list[dict[str, Any]]:
        frame = self.store.read_latest(DatasetName.EXECUTION_HEALTH_SNAPSHOT)
        if frame.is_empty() and self.execution.enabled:
            self.sync_live_state()
            frame = self.store.read_latest(DatasetName.EXECUTION_HEALTH_SNAPSHOT)
        if not frame.is_empty():
            return frame.sort(["venue", "account"]).to_dicts()
        return [
            ExecutionVenueHealth(
                venue=venue,
                account="unconfigured",
                status="not_configured",
                ws_connected=False,
                private_ws_connected=False,
            ).model_dump(mode="json")
            for venue in ExecutionVenue
        ]

    def seed_market_snapshots(self, *, asset: str | None = None, venue: str | None = None) -> int:
        rows = _default_market_rows(asset=asset, venue=venue)
        if not rows:
            return 0
        frame = pl.DataFrame(rows)
        return len(self.store.write(DatasetName.EXECUTION_MARKET_SNAPSHOT, frame))

    def write_health_snapshot(self, health: list[ExecutionVenueHealth]) -> int:
        if not health:
            return 0
        now = datetime.now(tz=timezone.utc)
        frame = pl.DataFrame(
            [
                {
                    "ts": now,
                    "date": now.date(),
                    "venue": item.venue.value,
                    "account": item.account,
                    "status": item.status,
                    "ws_connected": item.ws_connected,
                    "private_ws_connected": item.private_ws_connected,
                    "last_heartbeat_ms": item.last_heartbeat_ms,
                    "latency_ms": item.latency_ms,
                    "last_error": item.last_error,
                    "reconnect_count": item.reconnect_count,
                    "quality_flag": "ok" if item.status == "online" else "warn",
                }
                for item in health
            ]
        )
        return len(self.store.write(DatasetName.EXECUTION_HEALTH_SNAPSHOT, frame))

    def request_quote(self, request: ExecutionQuoteRequest) -> ExecutionActionResult:
        now = datetime.now(tz=timezone.utc)
        account, account_failure = self._resolve_account(
            venue=request.venue,
            account_label=request.account,
            mode=request.mode,
            request_id=uuid4().hex,
            now=now,
        )
        if account_failure is not None:
            self._write_quote_request(request, account_failure, now=now)
            return account_failure
        assert account is not None
        failure = self._risk_block(
            venue=request.venue,
            account=account,
            asset=request.asset,
            symbol=request.symbol,
            notional_usd=request.notional_usd or request.size,
        )
        request_id = account_failure.request_id if account_failure is not None else uuid4().hex
        if failure:
            result = ExecutionActionResult(
                request_id=request_id,
                venue=request.venue,
                account=request.account,
                status=ExecutionOrderStatus.REJECTED,
                mode=request.mode,
                message=failure.value,
                failure_code=failure,
            )
            self._write_quote_request(request, result, now=now)
            return result

        if request.mode == ExecutionRequestMode.LIVE:
            client = self._live_client(account)
            try:
                live_result = client.request_quote(request)
            except Exception as exc:
                result = ExecutionActionResult(
                    request_id=request_id,
                    venue=request.venue,
                    account=request.account,
                    status=ExecutionOrderStatus.REJECTED,
                    mode=request.mode,
                    message=str(exc),
                    failure_code=ExecutionFailureCode.AUTH_FAILURE,
                )
                self._write_quote_request(request, result, now=now)
                return result
            result = ExecutionActionResult(
                request_id=request_id,
                venue=request.venue,
                account=request.account,
                status=ExecutionOrderStatus.ACCEPTED,
                mode=request.mode,
                message=live_result.message,
                quote_id=live_result.quote_id,
                payload=live_result.payload,
            )
            self._write_quote_request(
                request,
                result,
                now=now,
                price=live_result.price,
                expires_at=live_result.expires_at,
                route=live_result.route,
            )
            return result

        quote_id = (
            f"{request.venue.value}-{request.account}-{request.asset.lower()}-{uuid4().hex[:10]}"
        )
        payload = {
            "quote_id": quote_id,
            "venue": request.venue.value,
            "account": request.account,
            "asset": request.asset.upper(),
            "symbol": request.symbol,
            "side": request.side.value,
            "size": request.size,
            "notional_usd": request.notional_usd,
            "mode": request.mode.value,
        }
        result = ExecutionActionResult(
            request_id=request_id,
            venue=request.venue,
            account=request.account,
            status=ExecutionOrderStatus.DRY_RUN
            if request.mode == ExecutionRequestMode.DRY_RUN
            else ExecutionOrderStatus.PAPER,
            mode=request.mode,
            message="Quote validated and recorded.",
            quote_id=quote_id,
            payload=payload,
        )
        self._write_quote_request(request, result, now=now)
        return result

    def submit_order(self, intent: ExecutionIntent) -> ExecutionActionResult:
        now = datetime.now(tz=timezone.utc)
        effective_intent = self._hydrate_live_intent(intent)
        account, account_failure = self._resolve_account(
            venue=effective_intent.venue,
            account_label=effective_intent.account,
            mode=effective_intent.mode,
            request_id=effective_intent.request_id,
            now=now,
        )
        if account_failure is not None:
            self._write_intent(effective_intent, account_failure, now=now)
            return account_failure
        assert account is not None
        failure = self._risk_block(
            venue=effective_intent.venue,
            account=account,
            asset=effective_intent.asset,
            symbol=effective_intent.symbol,
            notional_usd=effective_intent.notional_usd
            or ((effective_intent.price or 0.0) * effective_intent.size),
            reduce_only=effective_intent.reduce_only,
            order_type=effective_intent.order_type.value,
        )
        if failure:
            result = ExecutionActionResult(
                request_id=effective_intent.request_id,
                venue=effective_intent.venue,
                account=effective_intent.account,
                status=ExecutionOrderStatus.REJECTED,
                mode=effective_intent.mode,
                message=failure.value,
                failure_code=failure,
            )
            self._write_intent(effective_intent, result, now=now)
            return result

        capabilities = VENUE_CAPABILITIES[effective_intent.venue]
        if effective_intent.instrument_type not in capabilities.supported_instrument_types:
            result = ExecutionActionResult(
                request_id=effective_intent.request_id,
                venue=effective_intent.venue,
                account=effective_intent.account,
                status=ExecutionOrderStatus.REJECTED,
                mode=effective_intent.mode,
                message="Instrument type is not supported by venue.",
                failure_code=ExecutionFailureCode.MARKET_UNSUPPORTED,
            )
            self._write_intent(effective_intent, result, now=now)
            return result
        if effective_intent.order_type not in capabilities.supported_order_types:
            result = ExecutionActionResult(
                request_id=effective_intent.request_id,
                venue=effective_intent.venue,
                account=effective_intent.account,
                status=ExecutionOrderStatus.REJECTED,
                mode=effective_intent.mode,
                message="Order type is not supported by venue.",
                failure_code=ExecutionFailureCode.MARKET_UNSUPPORTED,
            )
            self._write_intent(effective_intent, result, now=now)
            return result

        venue_order_id = f"{effective_intent.venue.value}-{uuid4().hex[:12]}"
        payload = {
            "venue": effective_intent.venue.value,
            "account": effective_intent.account,
            "symbol": effective_intent.symbol,
            "side": effective_intent.side.value,
            "order_type": effective_intent.order_type.value,
            "tif": effective_intent.time_in_force.value,
            "price": effective_intent.price,
            "size": effective_intent.size,
            "reduce_only": effective_intent.reduce_only,
            "mode": effective_intent.mode.value,
        }
        status = (
            ExecutionOrderStatus.DRY_RUN
            if effective_intent.mode == ExecutionRequestMode.DRY_RUN
            else ExecutionOrderStatus.PAPER
            if effective_intent.mode == ExecutionRequestMode.PAPER
            else ExecutionOrderStatus.ACCEPTED
        )
        message = (
            "Order validated and recorded."
            if effective_intent.mode != ExecutionRequestMode.LIVE
            else "Live order intent accepted for adapter handoff."
        )
        failure_code = (
            None
            if effective_intent.mode != ExecutionRequestMode.LIVE
            else ExecutionFailureCode.NOT_IMPLEMENTED
        )
        if effective_intent.mode == ExecutionRequestMode.LIVE:
            client = self._live_client(account)
            try:
                live_result = client.place_order(effective_intent)
            except Exception as exc:
                result = ExecutionActionResult(
                    request_id=effective_intent.request_id,
                    venue=effective_intent.venue,
                    account=effective_intent.account,
                    status=ExecutionOrderStatus.REJECTED,
                    mode=effective_intent.mode,
                    message=str(exc),
                    failure_code=ExecutionFailureCode.QUOTE_EXPIRED
                    if "expired" in str(exc).lower()
                    else ExecutionFailureCode.AUTH_FAILURE,
                )
                self._write_intent(effective_intent, result, now=now)
                return result
            result = ExecutionActionResult(
                request_id=effective_intent.request_id,
                venue=effective_intent.venue,
                account=effective_intent.account,
                status=live_result.status,
                mode=effective_intent.mode,
                message=live_result.message,
                venue_order_id=live_result.venue_order_id,
                payload=live_result.payload,
            )
            self._write_intent(
                effective_intent,
                result,
                now=now,
                remaining_size=live_result.remaining_size,
                filled_size=live_result.filled_size,
                avg_fill_price=live_result.avg_fill_price,
            )
            if live_result.fill_events:
                self._write_fill_events(live_result.fill_events, now=now)
            self.sync_live_state(
                venue=effective_intent.venue.value,
                account=effective_intent.account,
                asset=effective_intent.asset.upper(),
            )
            return result
        result = ExecutionActionResult(
            request_id=effective_intent.request_id,
            venue=effective_intent.venue,
            account=effective_intent.account,
            status=status,
            mode=effective_intent.mode,
            message=message,
            venue_order_id=venue_order_id,
            failure_code=failure_code,
            payload=payload,
        )
        self._write_intent(effective_intent, result, now=now)
        return result

    def cancel(self, request: ExecutionCancelRequest) -> ExecutionActionResult:
        now = datetime.now(tz=timezone.utc)
        _, account_failure = self._resolve_account(
            venue=request.venue,
            account_label=request.account,
            mode=request.mode,
            request_id=request.request_id or uuid4().hex,
            now=now,
        )
        if account_failure is not None:
            self._write_cancel_event(request, account_failure, now=now, event_type="cancel")
            return account_failure
        if request.mode == ExecutionRequestMode.LIVE:
            account = self._account(request.account, request.venue)
            client = self._live_client(account)
            try:
                live_result = client.cancel(request)
            except Exception as exc:
                result = ExecutionActionResult(
                    request_id=request.request_id or uuid4().hex,
                    venue=request.venue,
                    account=request.account,
                    status=ExecutionOrderStatus.REJECTED,
                    mode=request.mode,
                    message=str(exc),
                    failure_code=ExecutionFailureCode.AUTH_FAILURE,
                )
                self._write_cancel_event(request, result, now=now, event_type="cancel")
                return result
            result = ExecutionActionResult(
                request_id=request.request_id or uuid4().hex,
                venue=request.venue,
                account=request.account,
                status=live_result.status,
                mode=request.mode,
                message=live_result.message,
                venue_order_id=live_result.venue_order_id,
                payload=live_result.payload,
            )
            self._write_cancel_event(request, result, now=now, event_type="cancel")
            self.sync_live_state(
                venue=request.venue.value,
                account=request.account,
                asset=request.asset.upper() if request.asset else None,
            )
            return result
        venue_order_id = request.venue_order_id or f"cancel-{uuid4().hex[:8]}"
        result = ExecutionActionResult(
            request_id=request.request_id or uuid4().hex,
            venue=request.venue,
            account=request.account,
            status=ExecutionOrderStatus.DRY_RUN
            if request.mode == ExecutionRequestMode.DRY_RUN
            else ExecutionOrderStatus.PAPER,
            mode=request.mode,
            message="Cancel request validated and recorded.",
            venue_order_id=venue_order_id,
            payload=request.model_dump(mode="json"),
        )
        self._write_cancel_event(request, result, now=now, event_type="cancel")
        return result

    def cancel_all(self, request: ExecutionCancelAllRequest) -> ExecutionActionResult:
        now = datetime.now(tz=timezone.utc)
        _, account_failure = self._resolve_account(
            venue=request.venue,
            account_label=request.account,
            mode=request.mode,
            request_id=uuid4().hex,
            now=now,
        )
        if account_failure is not None:
            self._write_cancel_all_event(request, account_failure, now=now)
            return account_failure
        if request.mode == ExecutionRequestMode.LIVE:
            account = self._account(request.account, request.venue)
            client = self._live_client(account)
            try:
                live_result = client.cancel_all(request)
            except Exception as exc:
                result = ExecutionActionResult(
                    request_id=uuid4().hex,
                    venue=request.venue,
                    account=request.account,
                    status=ExecutionOrderStatus.REJECTED,
                    mode=request.mode,
                    message=str(exc),
                    failure_code=ExecutionFailureCode.AUTH_FAILURE,
                )
                self._write_cancel_all_event(request, result, now=now)
                return result
            result = ExecutionActionResult(
                request_id=uuid4().hex,
                venue=request.venue,
                account=request.account,
                status=live_result.status,
                mode=request.mode,
                message=live_result.message,
                venue_order_id=live_result.venue_order_id,
                payload=live_result.payload,
            )
            self._write_cancel_all_event(request, result, now=now)
            self.sync_live_state(
                venue=request.venue.value,
                account=request.account,
                asset=request.asset.upper() if request.asset else None,
            )
            return result
        result = ExecutionActionResult(
            request_id=uuid4().hex,
            venue=request.venue,
            account=request.account,
            status=ExecutionOrderStatus.DRY_RUN
            if request.mode == ExecutionRequestMode.DRY_RUN
            else ExecutionOrderStatus.PAPER,
            mode=request.mode,
            message="Cancel-all request validated and recorded.",
            payload=request.model_dump(mode="json"),
        )
        self._write_cancel_all_event(request, result, now=now)
        return result

    def sync_live_state(
        self,
        *,
        venue: str | None = None,
        account: str | None = None,
        asset: str | None = None,
    ) -> dict[str, int]:
        written = {
            "markets": 0,
            "balances": 0,
            "positions": 0,
            "orders": 0,
            "fills": 0,
            "health": 0,
        }
        if not self.execution.enabled:
            return written
        for account_config in self.list_accounts():
            if venue and account_config.venue.value != venue:
                continue
            if account and account_config.label != account:
                continue
            try:
                client = self._live_client(account_config)
                market_rows = self._market_rows(
                    client.market_snapshots(asset=asset),
                    now=datetime.now(tz=timezone.utc),
                )
                if market_rows:
                    written["markets"] += len(
                        self.store.write(
                            DatasetName.EXECUTION_MARKET_SNAPSHOT,
                            pl.DataFrame(market_rows),
                        )
                    )
                snapshot = client.account_snapshot(asset=asset)
                written["balances"] += self._write_snapshot_rows(
                    DatasetName.EXECUTION_BALANCE_SNAPSHOT,
                    snapshot.balances,
                )
                written["positions"] += self._write_snapshot_rows(
                    DatasetName.EXECUTION_POSITION_SNAPSHOT,
                    snapshot.positions,
                )
                written["orders"] += self._write_snapshot_rows(
                    DatasetName.EXECUTION_ORDER_EVENT,
                    snapshot.orders,
                )
                written["fills"] += self._write_fill_events(snapshot.fills)
                if snapshot.health is not None:
                    written["health"] += self.write_health_snapshot([snapshot.health])
            except Exception:
                continue
        return written

    def _account(self, label: str, venue: ExecutionVenue) -> ExecutionAccountConfig:
        for account in self.list_accounts():
            if account.label == label and account.venue == venue:
                return account
        raise KeyError(f"Unknown execution account {label} for venue {venue.value}")

    def _resolve_account(
        self,
        *,
        venue: ExecutionVenue,
        account_label: str,
        mode: ExecutionRequestMode,
        request_id: str,
        now: datetime,
    ) -> tuple[ExecutionAccountConfig | None, ExecutionActionResult | None]:
        try:
            return self._account(account_label, venue), None
        except KeyError:
            return None, ExecutionActionResult(
                request_id=request_id,
                venue=venue,
                account=account_label,
                status=ExecutionOrderStatus.REJECTED,
                mode=mode,
                message=f"Unknown execution account {account_label} for venue {venue.value}.",
                failure_code=ExecutionFailureCode.AUTH_FAILURE,
                emitted_at=now,
            )

    def _risk_block(
        self,
        *,
        venue: ExecutionVenue,
        account: ExecutionAccountConfig,
        asset: str,
        symbol: str,
        notional_usd: float | None,
        reduce_only: bool = False,
        order_type: str | None = None,
    ) -> ExecutionFailureCode | None:
        if self.execution.global_kill_switch:
            return ExecutionFailureCode.RISK_BLOCKED
        if not account.enabled or account.kill_switch:
            return ExecutionFailureCode.RISK_BLOCKED
        if asset.upper() not in account.enabled_assets:
            return ExecutionFailureCode.RISK_BLOCKED
        if account.enabled_symbols and symbol not in account.enabled_symbols:
            return ExecutionFailureCode.RISK_BLOCKED
        max_notional = min(account.max_order_notional_usd, self.execution.max_order_notional_usd)
        if notional_usd and notional_usd > max_notional:
            return ExecutionFailureCode.RISK_BLOCKED
        capabilities = VENUE_CAPABILITIES[venue]
        if reduce_only and not capabilities.supports_reduce_only:
            return ExecutionFailureCode.REDUCE_ONLY_VIOLATION
        if (
            order_type == "post_only_limit"
            and not capabilities.supports_post_only
        ):
            return ExecutionFailureCode.MARKET_UNSUPPORTED
        return None

    def _write_intent(
        self,
        intent: ExecutionIntent,
        result: ExecutionActionResult,
        *,
        now: datetime,
        remaining_size: float | None = None,
        filled_size: float | None = None,
        avg_fill_price: float | None = None,
    ) -> None:
        frame = pl.DataFrame(
            [
                {
                    "ts": now,
                    "date": now.date(),
                    "request_id": intent.request_id,
                    "idempotency_key": intent.idempotency_key,
                    "venue": intent.venue.value,
                    "account": intent.account,
                    "instrument_type": intent.instrument_type.value,
                    "asset": intent.asset.upper(),
                    "symbol": intent.symbol,
                    "side": intent.side.value,
                    "order_type": intent.order_type.value,
                    "time_in_force": intent.time_in_force.value,
                    "price": intent.price,
                    "size": intent.size,
                    "notional_usd": intent.notional_usd,
                    "status": result.status.value,
                    "dry_run": intent.mode == ExecutionRequestMode.DRY_RUN,
                    "paper_mode": intent.mode == ExecutionRequestMode.PAPER,
                    "payload": orjson.dumps(result.payload).decode(),
                    "error_code": result.failure_code.value if result.failure_code else None,
                    "error_message": result.message if result.failure_code else None,
                    "quality_flag": "ok" if result.failure_code is None else "blocked",
                }
            ]
        )
        self.store.write(DatasetName.EXECUTION_ORDER_INTENT, frame)
        event = pl.DataFrame(
            [
                {
                    "ts": now,
                    "date": now.date(),
                    "request_id": intent.request_id,
                    "venue_order_id": result.venue_order_id,
                    "client_order_id": intent.client_order_id,
                    "venue": intent.venue.value,
                    "account": intent.account,
                    "asset": intent.asset.upper(),
                    "symbol": intent.symbol,
                    "event_type": "submit",
                    "status": result.status.value,
                    "side": intent.side.value,
                    "order_type": intent.order_type.value,
                    "time_in_force": intent.time_in_force.value,
                    "price": intent.price,
                    "size": intent.size,
                    "remaining_size": remaining_size if remaining_size is not None else intent.size,
                    "filled_size": filled_size if filled_size is not None else 0.0,
                    "avg_fill_price": avg_fill_price,
                    "reason": result.message,
                    "payload": orjson.dumps(result.payload).decode(),
                    "quality_flag": "ok" if result.failure_code is None else "blocked",
                }
            ]
        )
        self.store.write(DatasetName.EXECUTION_ORDER_EVENT, event)

    def _write_quote_request(
        self,
        request: ExecutionQuoteRequest,
        result: ExecutionActionResult,
        *,
        now: datetime,
        price: float | None = None,
        expires_at: datetime | None = None,
        route: str = "router",
    ) -> None:
        frame = pl.DataFrame(
            [
                {
                    "ts": now,
                    "date": now.date(),
                    "request_id": result.request_id,
                    "quote_id": result.quote_id,
                    "venue": request.venue.value,
                    "account": request.account,
                    "asset": request.asset.upper(),
                    "symbol": request.symbol,
                    "side": request.side.value,
                    "price": price,
                    "size": request.size,
                    "notional_usd": request.notional_usd,
                    "expires_at": expires_at or now,
                    "route": route,
                    "status": result.status.value,
                    "payload": orjson.dumps(result.payload).decode(),
                    "quality_flag": "ok" if result.failure_code is None else "blocked",
                }
            ]
        )
        self.store.write(DatasetName.EXECUTION_QUOTE_SNAPSHOT, frame)

    def _write_cancel_event(
        self,
        request: ExecutionCancelRequest,
        result: ExecutionActionResult,
        *,
        now: datetime,
        event_type: str,
    ) -> None:
        frame = pl.DataFrame(
            [
                {
                    "ts": now,
                    "date": now.date(),
                    "request_id": result.request_id,
                    "venue_order_id": result.venue_order_id,
                    "client_order_id": None,
                    "venue": request.venue.value,
                    "account": request.account,
                    "asset": request.asset.upper() if request.asset else None,
                    "symbol": request.symbol,
                    "event_type": event_type,
                    "status": result.status.value,
                    "side": None,
                    "order_type": None,
                    "time_in_force": None,
                    "price": None,
                    "size": None,
                    "remaining_size": None,
                    "filled_size": None,
                    "avg_fill_price": None,
                    "reason": result.message,
                    "payload": orjson.dumps(result.payload).decode(),
                    "quality_flag": "ok",
                }
            ]
        )
        self.store.write(DatasetName.EXECUTION_ORDER_EVENT, frame)

    def _write_fill_events(
        self,
        rows: list[dict[str, Any]],
        *,
        now: datetime | None = None,
    ) -> int:
        if not rows:
            return 0
        ts = now or datetime.now(tz=timezone.utc)
        frame = pl.DataFrame(
            [
                {
                    "ts": item.get("ts", ts),
                    "date": item.get("ts", ts).date() if item.get("ts") else ts.date(),
                    "fill_id": item["fill_id"],
                    "request_id": item.get("request_id"),
                    "venue_order_id": item.get("venue_order_id"),
                    "venue": item["venue"],
                    "account": item["account"],
                    "asset": item["asset"],
                    "symbol": item["symbol"],
                    "side": item.get("side"),
                    "price": item.get("price"),
                    "size": item.get("size"),
                    "fee": item.get("fee"),
                    "fee_asset": item.get("fee_asset"),
                    "liquidity": item.get("liquidity"),
                    "payload": orjson.dumps(item.get("payload", {})).decode(),
                    "quality_flag": item.get("quality_flag", "ok"),
                }
                for item in rows
            ]
        )
        return len(self.store.write(DatasetName.EXECUTION_FILL_EVENT, frame))

    def _write_snapshot_rows(self, dataset: DatasetName, rows: list[dict[str, Any]]) -> int:
        if not rows:
            return 0
        frame = pl.DataFrame(
            [
                {
                    **{
                        **item,
                        "payload": orjson.dumps(item["payload"]).decode()
                        if dataset == DatasetName.EXECUTION_ORDER_EVENT
                        else item.get("payload"),
                    },
                    "date": item.get("ts", datetime.now(tz=timezone.utc)).date(),
                }
                for item in rows
            ]
        )
        return len(self.store.write(dataset, frame))

    def _market_rows(self, rows: list[dict[str, Any]], *, now: datetime) -> list[dict[str, Any]]:
        return [{**row, "ts": now, "date": now.date()} for row in rows]

    def _live_client(self, account: ExecutionAccountConfig) -> Any:
        key = (account.venue.value, account.label)
        client = self._live_clients.get(key)
        if client is None:
            client = create_live_client(config=self.config, account=account)
            self._live_clients[key] = client
        return client

    def _hydrate_live_intent(self, intent: ExecutionIntent) -> ExecutionIntent:
        if (
            intent.mode != ExecutionRequestMode.LIVE
            or intent.venue != ExecutionVenue.BEBOP
            or not intent.quote_id
            or "quote_payload" in intent.metadata
        ):
            return intent
        quote_payload = self._quote_payload(intent.venue, intent.account, intent.quote_id)
        if quote_payload is None:
            return intent
        return intent.model_copy(
            update={
                "metadata": {
                    **intent.metadata,
                    "quote_payload": quote_payload,
                }
            }
        )

    def _quote_payload(
        self,
        venue: ExecutionVenue,
        account: str,
        quote_id: str,
    ) -> dict[str, Any] | None:
        frame = self.store.read(
            DatasetName.EXECUTION_QUOTE_SNAPSHOT,
            filters={"venue": venue.value, "account": account},
            read_mode=ReadMode.ALL_RUNS,
        )
        if frame.is_empty() or "quote_id" not in frame.columns or "payload" not in frame.columns:
            return None
        frame = frame.filter(pl.col("quote_id") == quote_id).sort("ts", descending=True)
        if frame.is_empty():
            return None
        payload = frame.item(0, "payload")
        if not payload:
            return None
        if isinstance(payload, str):
            return orjson.loads(payload)
        return payload

    def _write_cancel_all_event(
        self,
        request: ExecutionCancelAllRequest,
        result: ExecutionActionResult,
        *,
        now: datetime,
    ) -> None:
        frame = pl.DataFrame(
            [
                {
                    "ts": now,
                    "date": now.date(),
                    "request_id": result.request_id,
                    "venue_order_id": None,
                    "client_order_id": None,
                    "venue": request.venue.value,
                    "account": request.account,
                    "asset": request.asset.upper() if request.asset else None,
                    "symbol": request.symbol,
                    "event_type": "cancel_all",
                    "status": result.status.value,
                    "side": None,
                    "order_type": None,
                    "time_in_force": None,
                    "price": None,
                    "size": None,
                    "remaining_size": None,
                    "filled_size": None,
                    "avg_fill_price": None,
                    "reason": result.message,
                    "payload": orjson.dumps(result.payload).decode(),
                    "quality_flag": "ok",
                }
            ]
        )
        self.store.write(DatasetName.EXECUTION_ORDER_EVENT, frame)


def _load_accounts(path: Path) -> list[ExecutionAccountConfig]:
    if not path.exists():
        return []
    data = orjson.loads(path.read_bytes())
    return [ExecutionAccountConfig.model_validate(item) for item in data]


def _clean_filters(values: dict[str, Any]) -> dict[str, Any]:
    return {key: value for key, value in values.items() if value not in {None, ""}}


def _default_market_rows(asset: str | None, venue: str | None) -> list[dict[str, Any]]:
    assets = [asset.upper()] if asset else ["BTC", "ETH"]
    venues = [ExecutionVenue(venue)] if venue else list(ExecutionVenue)
    rows: list[dict[str, Any]] = []
    now = datetime.now(tz=timezone.utc)
    for execution_venue in venues:
        capabilities = VENUE_CAPABILITIES[execution_venue]
        for item in assets:
            instrument_type = capabilities.supported_instrument_types[0].value
            symbol = f"{item}-USD" if instrument_type == "spot" else f"{item}-PERP"
            rows.append(
                {
                    "ts": now,
                    "date": now.date(),
                    "venue": execution_venue.value,
                    "asset": item,
                    "symbol": symbol,
                    "instrument_type": instrument_type,
                    "status": "unseeded",
                    "tick_size": None,
                    "step_size": None,
                    "min_size": None,
                    "min_notional": None,
                    "best_bid": None,
                    "best_ask": None,
                    "mark_price": None,
                    "index_price": None,
                    "quality_flag": "unseeded",
                }
            )
    return rows
