#!/usr/bin/env python3
"""
FibPi3D Anchor Adapter - Vault-anchored CDC
============================================

Computes FibPi3D anchors for vault tile access.
"""
from __future__ import annotations
import importlib
import os
import hashlib
from dataclasses import dataclass


@dataclass
class Anchor:
    """FibPi3D anchor for vault tile lookup"""
    kind: str
    key: str  # stable string id
    meta: dict


def compute_anchor(ctx_bytes: bytes, step: int, seed_sha256: str) -> Anchor:
    """
    Prefer FibPi3D/Crystal Vault anchor. Fallback: deterministic, but DO NOT use
    if vault support is available.

    Args:
        ctx_bytes: Context bytes (last N tokens)
        step: Generation step number
        seed_sha256: Seed SHA256 hash

    Returns:
        Anchor with kind, key, and metadata
    """
    # Try crystal_vault helper(s)
    vault_mod = None
    try:
        vault_mod = importlib.import_module("crystal_vault")
    except Exception:
        # allow path injection via env
        vp = os.environ.get("HELIX_VAULT_PATH")
        if vp:
            import sys
            sys.path.insert(0, vp)
            try:
                vault_mod = importlib.import_module("crystal_vault")
            except Exception:
                vault_mod = None

    if vault_mod:
        # Try common names
        for fn_name in ("anchor_for", "compute_anchor", "fibpi3d_anchor_for"):
            fn = getattr(vault_mod, fn_name, None)
            if callable(fn):
                a = fn(seed_sha256=seed_sha256, context=ctx_bytes, step=step)
                # expect a dict-like with id/key
                key = a.get("key") or a.get("id") or a.get("addr")
                return Anchor(kind="fibpi3d", key=str(key), meta=a)

    # Last-resort deterministic fallback (allowed only if VAULT_DISABLED=1)
    if os.environ.get("VAULT_DISABLED") == "1":
        h = hashlib.sha3_256(seed_sha256.encode() + ctx_bytes + step.to_bytes(4, "little")).hexdigest()
        return Anchor(kind="fallback", key=h[:32], meta={"warn": "vault not active"})

    raise RuntimeError("Vault/FibPi3D anchor not available")
