"""Shared access to Cloud's email catalog contract for cross-repo tests."""
from __future__ import annotations

import json
import subprocess
from pathlib import Path


BE_ROOT = Path(__file__).resolve().parents[1]
CLOUD_ROOT = BE_ROOT.parent / "P2HSCloud"
CLOUD_META = CLOUD_ROOT / "apps" / "pc-gateway" / "src" / "lib" / "email-template-catalog-meta.ts"
CLOUD_EXPORT = CLOUD_ROOT / "scripts" / "export-email-template-catalog-meta.mjs"


def load_cloud_catalog_meta() -> dict[str, dict]:
    result = subprocess.run(
        ["node", str(CLOUD_EXPORT), str(CLOUD_META)],
        cwd=CLOUD_ROOT,
        check=False,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        raise AssertionError(
            "Cloud email catalog AST export failed "
            f"(exit {result.returncode}):\n{result.stderr.strip()}"
        )
    try:
        catalog = json.loads(result.stdout)
    except json.JSONDecodeError as exc:
        raise AssertionError(f"Cloud email catalog exporter returned invalid JSON: {exc}") from exc
    if not isinstance(catalog, dict) or not catalog:
        raise AssertionError("Cloud email catalog exporter returned an empty/non-object catalog")
    return catalog
