"""Decision recorder for learning lifecycle events.

Stores observation / proposal / risk / execution / closure events as JSONL so
the learning pipeline can reconstruct a complete decision trace without
blocking the trading path.
"""

from __future__ import annotations

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

import config_manager

EVENT_FILE_MAX_BYTES = 8_000_000
EVENT_FILE_MAX_LINES = 20_000


def _events_dir() -> Path:
    path = config_manager.get_data_dir() / "learning" / "events"
    path.mkdir(parents=True, exist_ok=True)
    return path


def _trim_jsonl_file(file_path: Path, *, max_bytes: int = EVENT_FILE_MAX_BYTES, max_lines: int = EVENT_FILE_MAX_LINES) -> None:
    try:
        if not file_path.exists() or file_path.stat().st_size <= max_bytes:
            return
        lines = file_path.read_text(encoding="utf-8").splitlines()
        if len(lines) > max_lines:
            lines = lines[-max_lines:]
        file_path.write_text(("\n".join(lines) + "\n") if lines else "", encoding="utf-8")
    except Exception:
        return


def _append_event(event_type: str, decision_id: str, source: str, payload: dict[str, Any]) -> None:
    file_path = _events_dir() / f"{event_type}.jsonl"
    entry = {
        "event_type": event_type,
        "decision_id": str(decision_id or ""),
        "source": str(source or "unknown"),
        "event_time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "payload": payload if isinstance(payload, dict) else {},
    }
    with open(file_path, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry, ensure_ascii=False) + "\n")
    _trim_jsonl_file(file_path)


def record_observation(decision_id: str, source: str, payload: dict[str, Any]) -> None:
    _append_event("observations", decision_id, source, payload)


def record_proposal(decision_id: str, source: str, payload: dict[str, Any]) -> None:
    _append_event("proposals", decision_id, source, payload)


def record_risk_verdict(decision_id: str, source: str, payload: dict[str, Any]) -> None:
    _append_event("risk_verdicts", decision_id, source, payload)


def record_execution(decision_id: str, source: str, payload: dict[str, Any]) -> None:
    _append_event("executions", decision_id, source, payload)


def record_closure(decision_id: str, source: str, payload: dict[str, Any]) -> None:
    _append_event("closures", decision_id, source, payload)
