from pathlib import Path
import hashlib
import json
from typing import Any, cast
from datetime import datetime, timezone
from ketju.core.utils.hash import get_file_hash

def manifest_key(path: Path) -> str:
    return hashlib.sha256(str(path.resolve()).encode("utf-8")).hexdigest()[:16]

def manifest_path(cache_dir:Path, pdf_path: Path) -> Path:
    return cache_dir / f"{pdf_path.stem}-{manifest_key(pdf_path)}.manifest.json"

def load_pdf_manifest(cache_dir:Path, pdf_path: Path) -> dict[str, Any] | None:
    out = manifest_path(cache_dir, pdf_path)
    if not out.exists():
        return None
    try:
        data = json.loads(out.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return None
    if isinstance(data, dict):
        return cast(dict[str, Any], data)
    return None

def save_pdf_manifest(cache_dir:Path, pdf_path: Path, *, metadata: dict[str, Any] | None = None) -> None:
    """Persist a small manifest for an ingested PDF (optional helper)."""

    manifest: dict[str, Any] = {
        "file": pdf_path.name,
        "path": str(pdf_path),
        "hash": get_file_hash(pdf_path) if pdf_path.exists() else None,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "metadata": metadata or {},
    }
    out = manifest_path(cache_dir, pdf_path)
    out.write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
