"""
Trade journal — append-only JSONL + learning state.
"""
from __future__ import annotations
import json
import time
import logging
from pathlib import Path
from typing import Optional
from .models import JournalEntry

log = logging.getLogger(__name__)


class Journal:
    def __init__(self, path: str = "data/journal.jsonl"):
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)

    def log(self, entry: JournalEntry):
        data = {
            "ts": entry.ts,
            "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(entry.ts / 1000)),
            "event": entry.event,
            "coin": entry.coin,
            "side": entry.side,
            "entry": entry.entry,
            "stop": entry.stop,
            "target": entry.target,
            "confidence": entry.confidence,
            "setup_type": entry.setup_type,
            "evidence": entry.evidence,
            "reason": entry.reason,
            "pnl_usd": entry.pnl_usd,
            "mfe_pct": entry.mfe_pct,
            "mae_pct": entry.mae_pct,
            "exit_reason": entry.exit_reason,
        }
        if entry.extra:
            data.update(entry.extra)

        with open(self.path, "a") as f:
            f.write(json.dumps(data) + "\n")

    def load_all(self) -> list[dict]:
        entries = []
        if not self.path.exists():
            return entries
        for line in self.path.read_text().strip().split("\n"):
            if line:
                try:
                    entries.append(json.loads(line))
                except json.JSONDecodeError:
                    continue
        return entries

    def load_recent(self, hours: int = 24) -> list[dict]:
        cutoff = int((time.time() - hours * 3600) * 1000)
        return [e for e in self.load_all() if e.get("ts", 0) >= cutoff]

    def summary(self, hours: int = 24) -> dict:
        entries = self.load_recent(hours)
        submits = [e for e in entries if e.get("event") == "submit"]
        rejects = [e for e in entries if e.get("event") == "risk_reject"]
        closes = [e for e in entries if e.get("event") == "close"]

        total_pnl = sum(e.get("pnl_usd", 0) for e in closes)
        wins = [e for e in closes if e.get("pnl_usd", 0) > 0]
        losses = [e for e in closes if e.get("pnl_usd", 0) < 0]

        return {
            "period_hours": hours,
            "total_events": len(entries),
            "submits": len(submits),
            "risk_rejects": len(rejects),
            "closes": len(closes),
            "wins": len(wins),
            "losses": len(losses),
            "win_rate": len(wins) / len(closes) * 100 if closes else 0,
            "total_pnl_usd": total_pnl,
        }
