"""Receipt persistence helpers."""

from __future__ import annotations

import json
from pathlib import Path
from typing import List

from .contracts import PlanV1, ReceiptArtifact, ReceiptV1


class ReceiptWriter:
    def __init__(self, state_dir: Path):
        self.state_dir = Path(state_dir)

    def write(self, receipt: ReceiptV1, plan: PlanV1) -> Path:
        receipt_dir = self.state_dir / "receipts" / plan.run_id
        receipt_dir.mkdir(parents=True, exist_ok=True)

        receipt_path = receipt_dir / "receipt.json"
        plan_path = receipt_dir / "plan.json"
        logs_path = receipt_dir / "logs.txt"

        artifacts = list(receipt.artifacts)
        artifacts.append(ReceiptArtifact(type="plan", path=str(plan_path)))
        artifacts.append(ReceiptArtifact(type="logs", path=str(logs_path)))
        receipt.artifacts = artifacts

        with open(plan_path, "w", encoding="utf-8") as f:
            json.dump(plan.to_dict(), f, indent=2)

        with open(logs_path, "w", encoding="utf-8") as f:
            f.write("")

        with open(receipt_path, "w", encoding="utf-8") as f:
            json.dump(receipt.to_dict(), f, indent=2)

        return receipt_dir


def load_receipt(state_dir: Path, run_id: str) -> ReceiptV1:
    receipt_path = Path(state_dir) / "receipts" / run_id / "receipt.json"
    with open(receipt_path, encoding="utf-8") as f:
        payload = json.load(f)
    return ReceiptV1.from_dict(payload)


def list_receipts(state_dir: Path) -> List[str]:
    receipts_root = Path(state_dir) / "receipts"
    if not receipts_root.exists():
        return []
    return sorted([
        path.name
        for path in receipts_root.iterdir()
        if path.is_dir()
    ])


__all__ = ["ReceiptWriter", "load_receipt", "list_receipts"]
