"""Status writer: JSON file + console dashboard."""
from __future__ import annotations

import json
import time
from pathlib import Path
from typing import Any, Optional


class StatusWriter:
    def __init__(self, path: str | Path, console_every_s: float = 2.0):
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.console_every_s = console_every_s
        self._last_console = 0.0

    def write(self, payload: dict[str, Any], console: bool = True) -> None:
        payload = {**payload, "updated_at": time.time()}
        tmp = self.path.with_suffix(".tmp")
        tmp.write_text(json.dumps(payload, indent=2))
        tmp.replace(self.path)
        if console and (time.time() - self._last_console) >= self.console_every_s:
            self._last_console = time.time()
            self._print(payload)

    def _print(self, p: dict[str, Any]) -> None:
        q = p.get("quote") or {}
        print(
            f"[{p.get('mode','?')}] mid={p.get('mid',0):.1f} "
            f"bid={q.get('bid_px',0):.1f} ask={q.get('ask_px',0):.1f} "
            f"inv={p.get('inventory_btc',0):+.6f} BTC "
            f"eq={p.get('equity',0):.2f}$ "
            f"dayPnL={p.get('day_pnl',0):+.2f}$ ({p.get('day_pnl_pct',0):+.3f}%) "
            f"fills={p.get('fills',0)} "
            f"kill={p.get('killed', False)} "
            f"{p.get('risk_reason','')}",
            flush=True,
        )
