"""Sauvegarde JSON + journal d'exécution."""
import json
from datetime import datetime, timezone
from pathlib import Path

DEFAULT_OUT = Path("output/v2")


def save_result(result: dict, out_dir: Path | str = DEFAULT_OUT) -> Path:
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    result["_meta"] = {
        "pipeline_version": "v1",
        "ocr_model": "zai-org/GLM-OCR",
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
    }
    out_path = out_dir / f"{result['fichier']}.json"
    out_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    return out_path
