#!/usr/bin/env python3
"""
Referenced Generative Representation + Equivalence Engine
==========================================================

A reference-first integration layer for existing synthesis backends.

Design:
  * A candidate is an executable generative specification, not a named object.
  * Backends remain responsible for synthesis and domain-specific verification.
  * Equivalence is typed and tiered: exact identity, exact semantic equivalence,
    structural relation, and measured/approximate similarity are never conflated.
  * The original geometric RC ladder is a first-class analog backend. Its
    recursive impedance is checked independently by a nodal MNA solver.

Python 3.10+, standard library only.

Boolean integration:
  BooleanComposerBackend wraps the already-working composer through explicit
  build/evaluate callbacks. This deliberately avoids guessing private APIs.
  The callbacks can call Synth.build(...) and Net.simulate(...) from the
  existing implementation without modifying that implementation.

Run:
  python referenced_generative.py --demo

Import:
  from referenced_generative import (
      Candidate, ReferenceEngine, RCLadderBackend,
      BooleanComposerBackend, npn_canonical_truth_table
  )
"""

from __future__ import annotations

import argparse
import cmath
import hashlib
import json
import math
import statistics
import time
from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Iterable, Mapping, Protocol, Sequence


# ---------------------------------------------------------------------------
# Canonical serialization and identity
# ---------------------------------------------------------------------------

def _stable(value: Any) -> Any:
    """Convert supported values to deterministic JSON-compatible data."""
    if isinstance(value, complex):
        return {"__complex__": [value.real.hex(), value.imag.hex()]}
    if isinstance(value, float):
        if math.isnan(value):
            return {"__float__": "nan"}
        if math.isinf(value):
            return {"__float__": "+inf" if value > 0 else "-inf"}
        return {"__float__": value.hex()}
    if isinstance(value, Mapping):
        return {str(k): _stable(value[k]) for k in sorted(value, key=str)}
    if isinstance(value, (list, tuple)):
        return [_stable(x) for x in value]
    if isinstance(value, (str, int, bool)) or value is None:
        return value
    if hasattr(value, "to_reference"):
        return _stable(value.to_reference())
    return {"__repr__": repr(value)}


def canonical_json(value: Any) -> str:
    return json.dumps(_stable(value), sort_keys=True, separators=(",", ":"))


def digest(value: Any) -> str:
    return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class Candidate:
    """
    Domain-neutral description of one generative object.

    `law` is an executable-backend identifier or a concise formal expression.
    `parameters` and `boundary` are supplied to the backend, not interpreted
    globally. `observables` names what the backend measures.
    """
    domain: str
    law: str
    state: Mapping[str, Any] = field(default_factory=dict)
    parameters: Mapping[str, Any] = field(default_factory=dict)
    boundary: Mapping[str, Any] = field(default_factory=dict)
    observables: tuple[str, ...] = ()
    provenance: Mapping[str, Any] = field(default_factory=dict)
    label: str | None = None

    def identity_payload(self) -> dict[str, Any]:
        return {
            "domain": self.domain,
            "law": self.law,
            "state": self.state,
            "parameters": self.parameters,
            "boundary": self.boundary,
            "observables": self.observables,
        }

    @property
    def candidate_id(self) -> str:
        return digest(self.identity_payload())


@dataclass
class Measurement:
    name: str
    value: Any
    method: str
    tolerance: float | None = None
    units: str | None = None


@dataclass
class Verification:
    name: str
    passed: bool
    detail: str
    metrics: dict[str, Any] = field(default_factory=dict)


@dataclass
class Realization:
    candidate_id: str
    backend: str
    measurements: list[Measurement]
    verifications: list[Verification]
    structure: Mapping[str, Any]
    semantic_key: str | None = None
    approximate_vector: tuple[float, ...] = ()
    created_at: float = field(default_factory=time.time)

    @property
    def verified(self) -> bool:
        return bool(self.verifications) and all(v.passed for v in self.verifications)


class Backend(Protocol):
    name: str
    domain: str

    def realize(self, candidate: Candidate) -> Realization:
        ...


# ---------------------------------------------------------------------------
# Equivalence relations: exact and approximate are deliberately separate
# ---------------------------------------------------------------------------

@dataclass
class EquivalenceResult:
    relation: str
    equivalent: bool
    confidence: str
    explanation: str
    distance: float | None = None
    tolerance: float | None = None


class ReferenceEngine:
    """
    Runs domain backends and indexes their realizations.

    It does not infer cross-domain equivalence. A Boolean truth table and an
    analog impedance curve can share measured features without becoming the
    same mathematical object.
    """

    def __init__(self) -> None:
        self.backends: dict[str, Backend] = {}
        self.references: dict[str, Realization] = {}
        self.candidates: dict[str, Candidate] = {}

    def register(self, backend: Backend) -> None:
        if backend.domain in self.backends:
            raise ValueError(f"backend already registered for domain {backend.domain!r}")
        self.backends[backend.domain] = backend

    def realize(self, candidate: Candidate) -> Realization:
        try:
            backend = self.backends[candidate.domain]
        except KeyError as exc:
            raise KeyError(f"no backend registered for domain {candidate.domain!r}") from exc
        result = backend.realize(candidate)
        self.references[result.candidate_id] = result
        self.candidates[result.candidate_id] = candidate
        return result

    @staticmethod
    def exact_identity(a: Candidate, b: Candidate) -> EquivalenceResult:
        same = a.candidate_id == b.candidate_id
        return EquivalenceResult(
            "candidate-identity", same, "exact",
            "Same canonical generative specification." if same
            else "Different generative specifications; semantic equivalence not implied."
        )

    @staticmethod
    def exact_semantic(a: Realization, b: Realization) -> EquivalenceResult:
        if a.backend != b.backend:
            return EquivalenceResult(
                "exact-semantic", False, "not-established",
                "No cross-backend exact semantic relation is registered."
            )
        if a.semantic_key is None or b.semantic_key is None:
            return EquivalenceResult(
                "exact-semantic", False, "not-established",
                "At least one backend did not provide an exact semantic key."
            )
        same = a.semantic_key == b.semantic_key
        return EquivalenceResult(
            "exact-semantic", same, "exact",
            "Backend canonical semantic keys match." if same
            else "Backend canonical semantic keys differ."
        )

    @staticmethod
    def approximate(
        a: Realization, b: Realization, tolerance: float
    ) -> EquivalenceResult:
        if a.backend != b.backend:
            return EquivalenceResult(
                "measured-similarity", False, "not-established",
                "Approximate comparison requires compatible feature vectors."
            )
        if not a.approximate_vector or len(a.approximate_vector) != len(b.approximate_vector):
            return EquivalenceResult(
                "measured-similarity", False, "not-established",
                "Feature vectors are absent or have different dimensions."
            )
        # Relative RMS distance, robust to differing overall scale.
        av, bv = a.approximate_vector, b.approximate_vector
        scale = max(
            math.sqrt(sum(x*x for x in av) / len(av)),
            math.sqrt(sum(x*x for x in bv) / len(bv)),
            1e-30,
        )
        distance = math.sqrt(sum((x-y)**2 for x, y in zip(av, bv)) / len(av)) / scale
        return EquivalenceResult(
            "measured-similarity", distance <= tolerance, "approximate",
            "Normalized feature-vector distance; this is not a proof of equivalence.",
            distance, tolerance
        )

    def compare(self, id_a: str, id_b: str, tolerance: float = 1e-3) -> list[EquivalenceResult]:
        ca, cb = self.candidates[id_a], self.candidates[id_b]
        ra, rb = self.references[id_a], self.references[id_b]
        return [
            self.exact_identity(ca, cb),
            self.exact_semantic(ra, rb),
            self.approximate(ra, rb, tolerance),
        ]

    def export(self, path: str) -> None:
        rows = []
        for cid, realization in self.references.items():
            candidate = self.candidates[cid]
            rows.append({
                "candidate": _stable(asdict(candidate)),
                "realization": _stable(asdict(realization)),
            })
        with open(path, "w", encoding="utf-8") as f:
            json.dump(rows, f, indent=2, sort_keys=True)


# ---------------------------------------------------------------------------
# Boolean backend adapter: exact NPN canonicalization for small local cells
# ---------------------------------------------------------------------------

def _permute_bits(table: int, n: int, perm: Sequence[int], negmask: int) -> int:
    out = 0
    for x in range(1 << n):
        src = 0
        for dst_bit, src_bit in enumerate(perm):
            bit = ((x >> dst_bit) & 1) ^ ((negmask >> dst_bit) & 1)
            src |= bit << src_bit
        if (table >> src) & 1:
            out |= 1 << x
    return out


def npn_canonical_truth_table(table: int, n: int) -> int:
    """
    Canonical representative under input permutation, input negation,
    and output negation. Intended for local cells (especially n <= 4).
    For larger n, factorial growth makes this a local-cell operation only.
    """
    if n < 0 or n > 4:
        raise ValueError("built-in NPN canonicalizer supports 0 <= n <= 4")
    mask = (1 << (1 << n)) - 1
    table &= mask
    best = mask
    import itertools
    for perm in itertools.permutations(range(n)):
        for neg in range(1 << n):
            t = _permute_bits(table, n, perm, neg)
            best = min(best, t, (~t) & mask)
    return best


class BooleanComposerBackend:
    """
    Adapter for the existing exact Boolean composer.

    `build(n, truth_table)` must call the existing composer and return its
    network/circuit object.

    `evaluate(network, n)` must return either:
      * an integer truth table, or
      * an iterable of 2**n output bits in input-row order.

    Optional `structure(network)` returns gate/depth/fanout metadata.
    Optional `canonicalize(n, truth_table)` can delegate to the existing NPN
    module for larger local functions or a future canonical representation.
    """

    name = "existing-boolean-composer"
    domain = "boolean"

    def __init__(
        self,
        build: Callable[[int, int], Any],
        evaluate: Callable[[Any, int], Any],
        structure: Callable[[Any], Mapping[str, Any]] | None = None,
        canonicalize: Callable[[int, int], int] | None = None,
    ) -> None:
        self.build_fn = build
        self.evaluate_fn = evaluate
        self.structure_fn = structure or (lambda net: {})
        self.canonicalize_fn = canonicalize

    def realize(self, candidate: Candidate) -> Realization:
        n = int(candidate.parameters["n"])
        table = int(candidate.parameters["truth_table"])
        if n < 0 or n > 24:
            raise ValueError("truth-table backend requires 0 <= n <= 24")
        expected_mask = (1 << (1 << n)) - 1
        table &= expected_mask

        network = self.build_fn(n, table)
        evaluated = self.evaluate_fn(network, n)
        if isinstance(evaluated, int):
            actual = evaluated & expected_mask
        else:
            bits = list(evaluated)
            if len(bits) != (1 << n):
                raise ValueError("evaluator returned wrong number of truth-table rows")
            actual = sum((int(bool(v)) << i) for i, v in enumerate(bits))

        passed = actual == table
        if self.canonicalize_fn:
            semantic = self.canonicalize_fn(n, table)
        elif n <= 4:
            semantic = npn_canonical_truth_table(table, n)
        else:
            # Exact truth-table identity (input order fixed); no false claim
            # that a large-N NPN canonical form has been computed.
            semantic = table

        structure = dict(self.structure_fn(network))
        structure.update({"n": n, "truth_table_hex": hex(table)})
        gate_count = structure.get("gates")
        measurements = [
            Measurement("truth_table_match", passed, "exhaustive 2^n-row simulation"),
        ]
        if gate_count is not None:
            measurements.append(Measurement("gate_count", gate_count, "backend network inspection", units="gates"))
        verifications = [
            Verification(
                "exhaustive-truth-table",
                passed,
                "Every input row matches." if passed else "At least one input row differs.",
                {"rows": 1 << n},
            )
        ]
        return Realization(
            candidate.candidate_id, self.name, measurements, verifications,
            structure, semantic_key=f"boolean:{n}:{semantic:x}"
        )


# ---------------------------------------------------------------------------
# Analog backend: original geometric RC ladder retained and independently checked
# ---------------------------------------------------------------------------

def _solve_complex(matrix: list[list[complex]], rhs: list[complex]) -> list[complex]:
    """Small dense Gaussian elimination with partial pivoting; stdlib only."""
    a = [row[:] + [rhs[i]] for i, row in enumerate(matrix)]
    n = len(a)
    for col in range(n):
        pivot = max(range(col, n), key=lambda r: abs(a[r][col]))
        if abs(a[pivot][col]) < 1e-28:
            raise ArithmeticError("singular MNA matrix")
        a[col], a[pivot] = a[pivot], a[col]
        p = a[col][col]
        for j in range(col, n + 1):
            a[col][j] /= p
        for r in range(n):
            if r == col:
                continue
            factor = a[r][col]
            if factor:
                for j in range(col, n + 1):
                    a[r][j] -= factor * a[col][j]
    return [a[i][n] for i in range(n)]


def rc_ladder_values(n: int, r0: float, c0: float, rho: float, gamma: float):
    if n < 1 or min(r0, c0, rho, gamma) <= 0:
        raise ValueError("n, R0, C0, rho, gamma must be positive; n >= 1")
    R = [r0 * rho**k for k in range(n)]
    C = [c0 * gamma**k for k in range(n)]
    return R, C


def rc_zin_recursive(f: float, R: Sequence[float], C: Sequence[float]) -> complex:
    """Original recursive impedance law, preserved as the primary realization."""
    if f <= 0:
        raise ValueError("frequency must be positive")
    if len(R) != len(C) or not R:
        raise ValueError("R and C must be nonempty and equal length")
    s = 2j * math.pi * f
    Y = s * C[-1]
    Z = R[-1] + 1 / Y
    for k in range(len(R) - 2, -1, -1):
        Y = s * C[k] + 1 / Z
        Z = R[k] + 1 / Y
    return Z


def rc_zin_mna(f: float, R: Sequence[float], C: Sequence[float]) -> complex:
    """
    Independent nodal solve of the same ladder.

    Nodes 0..n: R[k] joins node k to k+1; C[k] shunts node k+1 to ground.
    A 1 A current is injected at node 0; V[0] is Zin.
    """
    if f <= 0:
        raise ValueError("frequency must be positive")
    n = len(R)
    if n == 0 or len(C) != n:
        raise ValueError("R and C must be nonempty and equal length")
    s = 2j * math.pi * f
    size = n + 1
    Y = [[0j for _ in range(size)] for _ in range(size)]
    for k in range(n):
        g = 1.0 / R[k]
        i, j = k, k + 1
        Y[i][i] += g
        Y[j][j] += g + s * C[k]
        Y[i][j] -= g
        Y[j][i] -= g
    rhs = [0j] * size
    rhs[0] = 1.0 + 0j
    voltages = _solve_complex(Y, rhs)
    return voltages[0]


def _linspace_log(lo: float, hi: float, count: int) -> list[float]:
    if lo <= 0 or hi <= lo or count < 2:
        raise ValueError("invalid logarithmic frequency interval")
    a, b = math.log10(lo), math.log10(hi)
    return [10 ** (a + (b-a)*i/(count-1)) for i in range(count)]


def _regression_slope(xs: Sequence[float], ys: Sequence[float]) -> float:
    mx, my = statistics.fmean(xs), statistics.fmean(ys)
    den = sum((x-mx)**2 for x in xs)
    if den == 0:
        raise ArithmeticError("zero regression variance")
    return sum((x-mx)*(y-my) for x, y in zip(xs, ys)) / den


class RCLadderBackend:
    """
    First-class analog realization from the original fractal_synth.py.

    Parameters:
      n, R0, C0, rho, gamma, ppd

    Reports:
      fitted power exponent, predicted exponent, phase, ripple, frequency span,
      and recursive-vs-MNA maximum relative error.

    Exact semantic key identifies the exact normalized ladder specification.
    Approximate vector describes its measured log-frequency response and is
    used only for tolerance-based similarity.
    """

    name = "geometric-rc-ladder"
    domain = "analog_rc"

    def realize(self, candidate: Candidate) -> Realization:
        p = candidate.parameters
        n = int(p.get("n", 24))
        r0 = float(p.get("R0", 1.0))
        c0 = float(p.get("C0", 1.0))
        rho = float(p["rho"])
        gamma = float(p["gamma"])
        ppd = int(p.get("ppd", 40))
        R, C = rc_ladder_values(n, r0, c0, rho, gamma)

        tau0 = R[0] * C[0]
        ratio = rho * gamma
        w_hi = 0.15 / tau0
        w_lo = 6.0 / (tau0 * ratio ** (n-1))
        f_lo, f_hi = w_lo / (2*math.pi), w_hi / (2*math.pi)
        decades = math.log10(f_hi / f_lo)
        freqs = _linspace_log(f_lo, f_hi, max(2, int(ppd * decades) + 1))

        zvals = [rc_zin_recursive(f, R, C) for f in freqs]
        mags = [abs(z) for z in zvals]
        phases = [math.degrees(cmath.phase(z)) for z in zvals]
        lx = [math.log10(f) for f in freqs]
        ly = [math.log10(z) for z in mags]
        slope = _regression_slope(lx, ly)
        alpha_fit = -slope
        alpha_pred = math.log(rho) / math.log(ratio) if ratio != 1 else float("nan")
        intercept = statistics.fmean(ly) - slope * statistics.fmean(lx)
        residuals = [y - (slope*x + intercept) for x, y in zip(lx, ly)]
        # Ripple is deviation from the fitted power law, not the full
        # end-to-end magnitude drop across the scaling band.
        ripple_db = 20 * (max(residuals) - min(residuals))
        phase_mean = statistics.fmean(phases)

        # Independent MNA cross-check at up to 17 logarithmically distributed points.
        check_freqs = _linspace_log(f_lo, f_hi, min(17, len(freqs)))
        errors = []
        for f in check_freqs:
            zr = rc_zin_recursive(f, R, C)
            zm = rc_zin_mna(f, R, C)
            errors.append(abs(zr-zm) / max(abs(zr), abs(zm), 1e-30))
        max_mna_error = max(errors)

        # Response signature: dimensionless log-magnitude shape after removing
        # the median level. The exact sample count is fixed for comparability.
        sig_freqs = _linspace_log(f_lo, f_hi, 32)
        sig = [math.log10(abs(rc_zin_recursive(f, R, C))) for f in sig_freqs]
        center = statistics.median(sig)
        vector = tuple(x-center for x in sig)

        scale_ratio = ratio
        semantic = {
            "n": n, "R0": r0.hex(), "C0": c0.hex(),
            "rho": rho.hex(), "gamma": gamma.hex(),
        }
        structure = {
            "topology": "series-R / shunt-C ladder",
            "stage_count": n,
            "R": [x.hex() for x in R],
            "C": [x.hex() for x in C],
            "scale_ratio_rho_gamma": scale_ratio,
        }
        measurements = [
            Measurement("alpha_predicted", alpha_pred, "ln(rho)/ln(rho*gamma)"),
            Measurement("alpha_fitted", alpha_fit, "log-log least-squares fit"),
            Measurement("phase_mean_deg", phase_mean, "complex impedance phase"),
            Measurement("ripple_db", ripple_db, "peak-to-peak log-magnitude variation"),
            Measurement("frequency_decades", decades, "geometric ladder band"),
            Measurement("mna_max_relative_error", max_mna_error, "independent nodal solve"),
        ]
        verifications = [
            Verification(
                "recursive-vs-mna",
                max_mna_error < 1e-7,
                "Independent nodal solution agrees." if max_mna_error < 1e-7
                else "Recursive and MNA solutions disagree beyond tolerance.",
                {"max_relative_error": max_mna_error, "sample_count": len(check_freqs)},
            ),
            Verification(
                "finite-positive-network",
                all(x > 0 and math.isfinite(x) for x in R+C),
                "All ladder elements are finite and positive.",
            ),
        ]
        return Realization(
            candidate.candidate_id, self.name, measurements, verifications,
            structure, semantic_key="rc-ladder:" + digest(semantic),
            approximate_vector=vector,
        )


# ---------------------------------------------------------------------------
# Reference records and relation helpers
# ---------------------------------------------------------------------------

def measurement_map(realization: Realization) -> dict[str, Any]:
    return {m.name: m.value for m in realization.measurements}


def candidate_from_json(data: Mapping[str, Any]) -> Candidate:
    return Candidate(
        domain=data["domain"],
        law=data["law"],
        state=data.get("state", {}),
        parameters=data.get("parameters", {}),
        boundary=data.get("boundary", {}),
        observables=tuple(data.get("observables", ())),
        provenance=data.get("provenance", {}),
        label=data.get("label"),
    )


def _demo() -> None:
    engine = ReferenceEngine()
    engine.register(RCLadderBackend())

    # These are parameterized generative instances, not named-fractal entries.
    examples = [
        Candidate(
            domain="analog_rc",
            law="geometric-series-resistance / geometric-shunt-capacitance",
            state={"stage_index": "k", "state": "impedance seen looking into stage k"},
            parameters={"n": 24, "R0": 1.0, "C0": 1.0, "rho": 2.0, "gamma": 2.0},
            boundary={"termination": "open capacitive tail"},
            observables=("Zin(f)", "alpha", "phase", "ripple", "MNA_error"),
            provenance={"source": "user-provided fractal_synth.py realization"},
            label="RC instance A",
        ),
        Candidate(
            domain="analog_rc",
            law="geometric-series-resistance / geometric-shunt-capacitance",
            state={"stage_index": "k", "state": "impedance seen looking into stage k"},
            parameters={"n": 24, "R0": 1.0, "C0": 1.0, "rho": 1.618033988749895, "gamma": 1.618033988749895},
            boundary={"termination": "open capacitive tail"},
            observables=("Zin(f)", "alpha", "phase", "ripple", "MNA_error"),
            provenance={"source": "user-provided fractal_synth.py realization"},
            label="RC instance B",
        ),
    ]
    realized = [engine.realize(c) for c in examples]
    for candidate, result in zip(examples, realized):
        print(f"\n{candidate.label}: {candidate.candidate_id[:16]}")
        print(f"  verified: {result.verified}")
        for m in result.measurements:
            print(f"  {m.name:26s} {m.value}")
        for v in result.verifications:
            print(f"  [{ 'PASS' if v.passed else 'FAIL' }] {v.name}: {v.detail}")

    print("\nComparison:")
    for relation in engine.compare(realized[0].candidate_id, realized[1].candidate_id, tolerance=0.05):
        print(f"  {relation.relation}: equivalent={relation.equivalent}; "
              f"confidence={relation.confidence}; distance={relation.distance}; "
              f"{relation.explanation}")

    engine.export("reference_index.json")
    print("\nWrote reference_index.json")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--demo", action="store_true", help="run two analog ladder references")
    args = parser.parse_args()
    if args.demo:
        _demo()
    else:
        parser.print_help()
