# helix_cdc/superglyph.py
from __future__ import annotations
import json, hashlib, pathlib, time
from typing import Dict, Any

def _canon(obj: Dict[str, Any]) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")

def sha3_512_hex(b: bytes) -> str:
    return hashlib.sha3_512(b).hexdigest()

def file_sha256_hex(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

def make_manifest(
    seed_path: str,
    lattice: str = "FibPi3D-32x32x8",
    gates: Dict[str, float] | None = None,
    vows: list[str] | None = None,
    policy: Dict[str, Any] | None = None,
    extra_provenance: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
    p = pathlib.Path(seed_path)
    man = {
        "schema": "superglyph:v1",
        "seed": {
            "path": str(p),
            "sha256": file_sha256_hex(str(p)),
            "bytes": p.stat().st_size,
        },
        "vault": {
            "lattice": lattice,
            "guard_cell": {"size_cap_mb": 1024, "no_symlink": True, "o_no_follow": True},
            "policy": {
                "gates": gates or {"D_min": 14.6, "C_min": 0.75, "H_min": 3.7, "Se_min": 43.1},
                "target_entropy_floor": 9.03
            } | (policy or {}),
        },
        "glyphs": {
            "vows": vows or ["no_exfil", "no_self_write", "bounded_tokens"],
            "actuators": ["morph_sat", "rag_dedup", "se_filter"],
        },
        "provenance": {
            "timestamp_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        } | (extra_provenance or {}),
    }
    return man

def superglyph_id(manifest: Dict[str, Any]) -> str:
    return sha3_512_hex(_canon(manifest))

def stamp_receipt(receipt: Dict[str, Any], manifest_path: str) -> Dict[str, Any]:
    """
    Stamp a receipt with superglyph_id (non-destructive)

    Args:
        receipt: Receipt dict to stamp
        manifest_path: Path to superglyph.json

    Returns:
        Stamped receipt (modifies in place and returns)
    """
    import pathlib

    manifest = json.loads(pathlib.Path(manifest_path).read_text())
    sgid = superglyph_id(manifest)

    prov = receipt.setdefault("provenance", {})
    prov.setdefault("superglyph_id", sgid)
    prov.setdefault("superglyph_manifest", str(pathlib.Path(manifest_path).resolve()))

    return receipt
