"""Pending action metadata persistence for maker/checker enforcement."""

from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path

from .contracts import ActorContext, PendingActionV1, PlanV1


PENDING_ACTION_FILENAME = "pending_action.json"


def pending_action_path(state_dir: Path | str, run_id: str) -> Path:
    return Path(state_dir) / "pending" / str(run_id or "").strip() / PENDING_ACTION_FILENAME


def build_pending_action(*, plan: PlanV1, actor: ActorContext) -> PendingActionV1:
    return PendingActionV1(
        run_id=plan.run_id,
        plan_hash=plan.plan_hash,
        policy_hash=plan.policy_hash,
        source_kind=plan.source_kind,
        created_at=datetime.now(timezone.utc).isoformat(),
        created_by=actor,
    )


def write_pending_action(state_dir: Path | str, pending_action: PendingActionV1) -> Path:
    path = pending_action_path(state_dir, pending_action.run_id)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp_path = path.with_suffix(".json.tmp")
    temp_path.write_text(
        json.dumps(pending_action.to_dict(), indent=2, sort_keys=True),
        encoding="utf-8",
    )
    temp_path.replace(path)
    return path


def load_pending_action(state_dir: Path | str, run_id: str) -> PendingActionV1 | None:
    path = pending_action_path(state_dir, run_id)
    if not path.exists():
        return None
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
        if not isinstance(payload, dict):
            return None
        return PendingActionV1.from_dict(payload)
    except Exception:
        return None


__all__ = [
    "PENDING_ACTION_FILENAME",
    "build_pending_action",
    "load_pending_action",
    "pending_action_path",
    "write_pending_action",
]
