"""Lightweight ReceiptWriter facade to decouple tests from heavy infra."""

from __future__ import annotations

import json
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Any, Mapping, MutableMapping, Optional


class ReceiptDomain(str, Enum):
    GOVERNANCE = "governance"
    ORGANISM = "organism"
    MEMORY = "memory"


def _coerce_payload(receipt: Any) -> MutableMapping[str, Any]:
    if hasattr(receipt, "model_dump"):
        return receipt.model_dump(mode="json")  # type: ignore[no-any-return]
    if isinstance(receipt, Mapping):
        return dict(receipt)
    raise TypeError(f"Unsupported receipt payload: {type(receipt)!r}")


@dataclass
class ReceiptWriter:
    """Persist receipts to disk for audit/testing."""

    out_dir: Path = Path("var/receipts/stream")

    def __post_init__(self) -> None:
        self.out_dir.mkdir(parents=True, exist_ok=True)

    def write(self, receipt: Any, domain: ReceiptDomain = ReceiptDomain.GOVERNANCE) -> Path:
        payload = _coerce_payload(receipt)
        payload.setdefault("domain", domain.value)
        payload.setdefault("ts", datetime.now(timezone.utc).isoformat())
        receipt_id = payload.get("receipt_id") or payload.get("discovery_id") or "receipt"
        filename = f"{domain.value}_{receipt_id}.json"
        path = self.out_dir / filename
        path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
        return path


__all__ = ["ReceiptWriter", "ReceiptDomain"]
