from __future__ import annotations

import json
import time
from dataclasses import asdict, dataclass
from pathlib import Path


@dataclass
class PairState:
    last_side: str | None = None
    last_trade_time: float = 0.0
    last_reason: str | None = None


class BotState:
    def __init__(self, path: Path) -> None:
        self.path = path
        self.pairs: dict[str, PairState] = {}
        self.load()

    def load(self) -> None:
        if not self.path.exists():
            return
        raw = json.loads(self.path.read_text(encoding="utf-8"))
        self.pairs = {symbol: PairState(**data) for symbol, data in raw.get("pairs", {}).items()}

    def get_pair(self, symbol: str) -> PairState:
        return self.pairs.setdefault(symbol, PairState())

    def record_trade(self, symbol: str, side: str, reason: str) -> None:
        state = self.get_pair(symbol)
        state.last_side = side
        state.last_trade_time = time.time()
        state.last_reason = reason
        self.save()

    def save(self) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        payload = {"pairs": {symbol: asdict(state) for symbol, state in self.pairs.items()}}
        self.path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
