"""Pre-mutation snapshots for script-edit director notes."""
from __future__ import annotations

import hashlib
from datetime import datetime, timezone
from pathlib import Path

from recoil.core.atomic_write import atomic_write_bytes


def snapshot_artifact(src: Path, kind: str, note_id: str, episode_root: Path) -> Path:
    """Snapshot a script-edit artifact before mutation.

    v1 is intentionally narrow: only ``kind="script_edits"`` is accepted.
    """
    if kind != "script_edits":
        raise ValueError(f"kind: {kind}")

    src = Path(src)
    data = src.read_bytes()
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    hash8 = hashlib.sha256(data).hexdigest()[:8]
    directory = Path(episode_root) / "_history" / kind
    directory.mkdir(parents=True, exist_ok=True)
    snapshot_path = directory / f"{note_id}__{stamp}__{hash8}{src.suffix}"
    atomic_write_bytes(snapshot_path, data)
    return snapshot_path


__all__ = ["snapshot_artifact"]
