from __future__ import annotations

import json
import uuid
from dataclasses import asdict, dataclass
from datetime import UTC, datetime
from pathlib import Path


@dataclass(frozen=True)
class PredictionRecord:
    prediction_id: str
    model_version: str
    feature_version: str
    symbol: str
    as_of_date: str
    execution_date: str | None
    prediction_horizon: int
    buy_probability: float
    neutral_probability: float
    sell_probability: float
    final_signal: str
    confidence: float
    market_regime: str | None
    feature_snapshot: str
    signal_state: str
    created_at: str

    @classmethod
    def create(cls, **values: object) -> "PredictionRecord":
        return cls(
            prediction_id=str(uuid.uuid4()),
            created_at=datetime.now(UTC).isoformat(),
            **values,
        )


class JsonlPredictionStore:
    """Append-only local prediction ledger. Existing records are never updated."""

    def __init__(self, path: str | Path) -> None:
        self.path = Path(path)

    def append(self, records: list[PredictionRecord]) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with self.path.open("a", encoding="utf-8") as handle:
            for record in records:
                handle.write(json.dumps(asdict(record), sort_keys=True) + "\n")

