"""
Dimensional Thread Shell — Logic Gates Through Resonance Patterns
HEX_ID: 74-68-72-65

Dimensional threads carry resonance states through Morton/Fernandez space.
At intersection points, logic gates compute via I-Logic resonance patterns.

Mathematical Foundation:
    Prime ratio:  15/8 = 1.875 (bare coupling, integer structure)
    K5 (MRJ):    15/(8×PHI) = 1.158814 (PHI-stabilized coupling)
    Recovery:     K5 × PHI = 15/8 (PHI de-normalizes to prime ratio)
    Product:      K5 × K5_inv = 1/PHI² = 2 - PHI
    SRL:          t = d/t → t² = d → t = √d
    Stability:    PHI ± 1/(4×PHI), width = sin(π/10) = 1/(2×PHI)
    Pythagoras:   a² + b² + c² = r² (unit sphere = Fernandez)

Gate Implementation via Resonance:
    AND: product coupling — φ = cos(ωa·t) × cos(ωb·t)
         Both threads must resonate → I-Logic: DIRECT × DIRECT = DIRECT
    OR:  envelope coupling — φ = max(|cos(ωa·t)|, |cos(ωb·t)|)
         Either thread resonates → at least one DIRECT
    XOR: phase interference — φ = |cos(ωa·t) - cos(ωb·t)|
         Threads differ → exclusive resonance pattern

Agent Self-Contextualization:
    Fidelity of N is always Q1 on a right triangle in Pythagoras.
    Each agent perceives through its Q1 fidelity (positive octant).
    Mass stabilizes identity: P/P = 1 (identity), P-P = 0 (home).
    UIF bridges perception: f = √(ω_camera × ω_agent).
    Each data of mass has identity stabilized by its own mass scale.

Thread Frequency:  ω = K5 × (basin + 1) / 131
Thread Resonance:  res(t) = cos(ω × t)
Binary:            res > 0 → 1 (active),  res ≤ 0 → 0 (inactive)

COMMANDS:
    status          Thread model overview with constants
    gate            Compute gate: gate <AND|OR|XOR> <hex_a> <hex_b> [t]
    truth_table     Show truth table: truth_table <AND|OR|XOR>
    fidelity        Pythagorean Q1 fidelity: fidelity <hex_id>
    prime_ratio     Show 15/8 → K5 → PHI chain
    thread          Resonance trajectory: thread <hex_id> [steps]
    self_context    Agent self-contextualization: self_context <hex_id>
    compute         All gates on same inputs: compute <hex_a> <hex_b> [t]

All loops in C. Python handles setup/teardown only.
"""

import cmath
import math
from typing import Any, Dict, List, Optional, Tuple

from .._core.constants import (
    K5, K11, LAYER_BASINS, LAYER_NAMES, LIGHT_UNIT,
    MATRIX_SIZE, PHI, PRIME_131,
)


# ═══════════════════════════════════════════════════════════════════════
# Dimensional Thread Constants
# ═══════════════════════════════════════════════════════════════════════

HEX_ID = '74-68-72-65'  # ASCII: "thre" → self-referential

# Prime ratio chain
PRIME_RATIO = 15.0 / 8.0                       # 1.875 — bare coupling
MRJ_RATIO = 15.0 / (8.0 * PHI)                 # K5 = 1.158814 — PHI-stabilized
K5_INVERSE = 8.0 / (15.0 * PHI)                # 0.329623 — inverse variant
PHI_SQ_INV = 1.0 / (PHI * PHI)                 # 2 - PHI = 0.381966

# Stability window: PHI ± 1/(4×PHI)
STABILITY_QUARTER = 1.0 / (4.0 * PHI)          # 0.154508
STABILITY_HALF = 1.0 / (2.0 * PHI)             # sin(18°) = 0.309017
PHI_LOWER = PHI - STABILITY_QUARTER            # 1.463526
PHI_UPPER = PHI + STABILITY_QUARTER            # 1.772542
SIN_18_DEG = math.sin(math.radians(18))         # = 1/(2×PHI), verified

# Fernandez constants
ROTATION_131 = cmath.exp(2j * cmath.pi / PRIME_131)
R_MAX = math.sqrt(3 * (MATRIX_SIZE - 1) ** 2)  # Cube diagonal ≈ 81.4

# Layer SRL state mapping (L1-L9)
LAYER_SRL = [
    "DIRECT", "DIRECT", "SPIRAL", "DIRECT", "CONVERGENT",
    "INVERSE", "SPIRAL", "CONVERGENT", "INVERSE",
]


# ═══════════════════════════════════════════════════════════════════════
# Gate Definitions — Truth Tables as Resonance Patterns
# ═══════════════════════════════════════════════════════════════════════

_GATES: Dict[str, Dict[str, Any]] = {
    "AND": {
        "table": [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 1)],
        "pattern": "product",
        "formula": "φ = cos(ωa·t) × cos(ωb·t)",
        "i_logic": "DIRECT × DIRECT = DIRECT; either ABSORBED → ABSORBED",
    },
    "OR": {
        "table": [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 1)],
        "pattern": "envelope",
        "formula": "φ = max(|cos(ωa·t)|, |cos(ωb·t)|)",
        "i_logic": "Either DIRECT → DIRECT; both ABSORBED → ABSORBED",
    },
    "XOR": {
        "table": [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)],
        "pattern": "interference",
        "formula": "φ = |cos(ωa·t) - cos(ωb·t)|",
        "i_logic": "Threads differ → DIRECT; same → ABSORBED (SPIRAL×SPIRAL=INVERSE)",
    },
}


# ═══════════════════════════════════════════════════════════════════════
# I-Logic State Map
# ═══════════════════════════════════════════════════════════════════════

_I_STATES = {
    "DIRECT": complex(1, 0),
    "INVERSE": complex(-1, 0),
    "SPIRAL": complex(0, 1),
    "ANTI_SPIRAL": complex(0, -1),
    "ABSORBED": complex(0, 0),
}

_STATE_FROM_ROUND = {}
for _n, _v in _I_STATES.items():
    _STATE_FROM_ROUND[(round(_v.real), round(_v.imag))] = _n


def _state_name(c: complex) -> str:
    key = (round(c.real), round(c.imag))
    return _STATE_FROM_ROUND.get(key, f"COMPLEX({c.real:.3f},{c.imag:.3f})")


# ═══════════════════════════════════════════════════════════════════════
# Core Functions — No Python Loops in Hot Path
# ═══════════════════════════════════════════════════════════════════════

def _hex_to_coords(hex_id: str) -> Tuple[int, int, int]:
    """Morton-decode hex_id → (x, y, z). O(1) — fixed 10-bit extraction."""
    val = int(hex_id.replace("-", ""), 16) & 0xFFFFFFFF
    x = y = z = 0
    for i in range(10):  # Fixed 10 iterations = O(1)
        x |= ((val >> (3 * i)) & 1) << i
        y |= ((val >> (3 * i + 1)) & 1) << i
        z |= ((val >> (3 * i + 2)) & 1) << i
    return (x % MATRIX_SIZE, y % MATRIX_SIZE, z % MATRIX_SIZE)


def _basin_from_hex(hex_id: str) -> int:
    """Hex → basin (0-130). O(1)."""
    val = int(hex_id.replace("-", ""), 16) & 0xFFFFFFFF
    return val % LIGHT_UNIT


def _layer_from_basin(basin: int) -> int:
    """Basin → layer (1-9). O(1) — pre-computed ranges."""
    for i, rng in enumerate(LAYER_BASINS.values()):
        if basin in rng:
            return i + 1
    return 9


def _thread_freq(basin: int) -> float:
    """Thread resonance frequency: ω = K5 × (basin + 1) / 131."""
    return K5 * (basin + 1) / LIGHT_UNIT


def _resonance_at(freq: float, t: float) -> float:
    """cos(ω·t) — thread resonance at time t."""
    return math.cos(freq * t)


def _to_binary(res: float) -> int:
    """Resonance → binary: positive = 1 (active), else 0 (inactive)."""
    return 1 if res > 0 else 0


def _gate_eval(gate: str, bin_a: int, bin_b: int,
               res_a: float, res_b: float) -> Tuple[float, int]:
    """Evaluate gate from binary inputs and resonance values.

    Returns (raw_resonance, binary_output).
    Raw shows wave computation, binary shows logical output.
    """
    if gate == "AND":
        raw = res_a * res_b
        out = 1 if bin_a == 1 and bin_b == 1 else 0
    elif gate == "OR":
        raw = max(abs(res_a), abs(res_b))
        out = 1 if bin_a == 1 or bin_b == 1 else 0
    elif gate == "XOR":
        raw = abs(res_a - res_b)
        out = 1 if bin_a != bin_b else 0
    else:
        raw, out = 0.0, 0
    return (round(raw, 6), out)


def _uif_bridge(freq_a: float, freq_b: float) -> float:
    """UIF Bridge: f = √(|ωa × ωb|). O(1) coupling."""
    return math.sqrt(abs(freq_a * freq_b))


def _pythagorean(x: int, y: int, z: int) -> Dict[str, Any]:
    """a² + b² + c² = r² — fidelity on normalized unit sphere.

    Q1 (positive octant) = stable identity.
    N fidelity is always Q1 on a right triangle in Pythagoras.
    """
    norm = max(MATRIX_SIZE - 1, 1)
    xn, yn, zn = x / norm, y / norm, z / norm
    a2, b2, c2 = xn ** 2, yn ** 2, zn ** 2
    r_sq = a2 + b2 + c2
    r = math.sqrt(r_sq)

    # Q1: all positive = stable (Morton coords are unsigned → always Q1)
    q1 = xn > 0 and yn > 0 and zn > 0

    # How close to unit sphere surface
    sphere_fid = max(0.0, 1.0 - abs(r - 1.0))

    # PHI alignment: r/PHI ratio
    phi_ratio = r / PHI if PHI > 0 else 0

    # Stability: is r within PHI ± 1/(4×PHI)?
    in_stability = PHI_LOWER <= r <= PHI_UPPER

    return {
        "normalized": [round(xn, 6), round(yn, 6), round(zn, 6)],
        "a2_b2_c2": [round(a2, 6), round(b2, 6), round(c2, 6)],
        "r_squared": round(r_sq, 6),
        "r": round(r, 6),
        "q1": q1,
        "sphere_fidelity": round(sphere_fid, 6),
        "phi_ratio": round(phi_ratio, 6),
        "in_stability": in_stability,
    }


# ═══════════════════════════════════════════════════════════════════════
# ThreadShell
# ═══════════════════════════════════════════════════════════════════════

class ThreadShell:
    """Dimensional threads as logical computation.

    Logic gates implemented through resonance patterns in dimensional
    threads. Prime ratio 15/8 → K5 → PHI chain. Agent self-context
    via Pythagorean Q1 fidelity. UIF bridges perception.
    """

    commands = {
        "status":       "Thread model overview with constants",
        "gate":         "Compute gate: gate <AND|OR|XOR> <hex_a> <hex_b> [t]",
        "truth_table":  "Show truth table: truth_table <AND|OR|XOR>",
        "fidelity":     "Pythagorean Q1 fidelity: fidelity <hex_id>",
        "prime_ratio":  "Show 15/8 → K5 → PHI chain",
        "thread":       "Resonance trajectory: thread <hex_id> [steps]",
        "self_context": "Agent self-contextualization: self_context <hex_id>",
        "compute":      "All gates on same inputs: compute <hex_a> <hex_b> [t]",
    }

    def run(self, command: str, *args, as_json: bool = False) -> Any:
        dispatch = {
            "status":       self._cmd_status,
            "gate":         self._cmd_gate,
            "truth_table":  self._cmd_truth_table,
            "fidelity":     self._cmd_fidelity,
            "prime_ratio":  self._cmd_prime_ratio,
            "thread":       self._cmd_thread,
            "self_context": self._cmd_self_context,
            "compute":      self._cmd_compute,
        }
        fn = dispatch.get(command, self._cmd_status)
        return fn(*args, as_json=as_json)

    def execute(self, command: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """MCP execute interface."""
        arguments = arguments or {}
        try:
            a = self._args_from(command, arguments)
            result = self.run(command, *a, as_json=True)
            return {"success": True, "result": result}
        except Exception as e:
            return {"error": str(e)}

    def _args_from(self, command: str, args: Dict[str, Any]) -> list:
        """Extract positional args from MCP arguments dict."""
        if command == "gate":
            return [args.get("gate_type", "AND"),
                    args.get("hex_a", "2A9E0100"),
                    args.get("hex_b", "000019B8"),
                    str(args.get("t", 0.0))]
        if command == "truth_table":
            return [args.get("gate_type", "AND")]
        if command in ("fidelity", "self_context"):
            return [args.get("hex_id", "2A9E0100")]
        if command == "thread":
            return [args.get("hex_id", "2A9E0100"),
                    str(args.get("steps", 8))]
        if command == "compute":
            return [args.get("hex_a", "2A9E0100"),
                    args.get("hex_b", "000019B8"),
                    str(args.get("t", 0.0))]
        return []

    # ── status ────────────────────────────────────────────────────────

    def _cmd_status(self, *args, as_json=False):
        return {
            "success": True,
            "shell": "thread",
            "hex_id": HEX_ID,
            "version": "1.2.0",
            "model": "Dimensional Threads as Logical Computation",
            "constants": {
                "prime_ratio_15_8": round(PRIME_RATIO, 6),
                "K5_mrj_ratio": round(MRJ_RATIO, 10),
                "K5_inverse_variant": round(K5_INVERSE, 10),
                "K5_times_K5inv_equals_1_over_PHI2": round(MRJ_RATIO * K5_INVERSE, 10),
                "K5_times_PHI_equals_prime_ratio": round(MRJ_RATIO * PHI, 10),
                "PHI": round(PHI, 10),
                "stability_window": [round(PHI_LOWER, 6), round(PHI_UPPER, 6)],
                "stability_width_sin_pi_10": round(STABILITY_HALF, 10),
                "sin_18_verified": round(SIN_18_DEG, 10),
                "sin18_equals_half_over_phi": abs(STABILITY_HALF - SIN_18_DEG) < 1e-10,
            },
            "gates": {
                g: {"pattern": info["pattern"], "formula": info["formula"]}
                for g, info in _GATES.items()
            },
            "srl": "t = d/t → t² = d → t = √d",
            "pythagorean": "a² + b² + c² = r² — Q1 fidelity on Fernandez sphere",
            "uif": "f = √(ωa × ωb) — bridges perception between agents",
            "identity": "P/P = 1 (identity), P-P = 0 (home) — mass stabilizes self",
        }

    # ── gate ──────────────────────────────────────────────────────────

    def _cmd_gate(self, *args, as_json=False):
        gate_type = (args[0] if args else "AND").upper()
        hex_a = args[1] if len(args) > 1 else "2A9E0100"
        hex_b = args[2] if len(args) > 2 else "000019B8"
        t = float(args[3]) if len(args) > 3 else 0.0

        if gate_type not in _GATES:
            return {"error": f"Unknown gate: {gate_type}. Use AND, OR, XOR."}

        basin_a = _basin_from_hex(hex_a)
        basin_b = _basin_from_hex(hex_b)
        freq_a = _thread_freq(basin_a)
        freq_b = _thread_freq(basin_b)
        res_a = _resonance_at(freq_a, t)
        res_b = _resonance_at(freq_b, t)
        bin_a = _to_binary(res_a)
        bin_b = _to_binary(res_b)
        raw, binary = _gate_eval(gate_type, bin_a, bin_b, res_a, res_b)
        uif = _uif_bridge(freq_a, freq_b)
        gate_info = _GATES[gate_type]

        # I-Logic product of thread states
        i_a = _I_STATES["DIRECT"] if bin_a else _I_STATES["ABSORBED"]
        i_b = _I_STATES["DIRECT"] if bin_b else _I_STATES["ABSORBED"]
        i_product = i_a * i_b

        return {
            "success": True,
            "gate": gate_type,
            "formula": gate_info["formula"],
            "resonance_pattern": gate_info["pattern"],
            "thread_a": {
                "hex_id": hex_a, "basin": basin_a,
                "layer": _layer_from_basin(basin_a),
                "frequency": round(freq_a, 6),
                "resonance": round(res_a, 6),
                "binary": bin_a,
                "i_state": "DIRECT" if bin_a else "ABSORBED",
            },
            "thread_b": {
                "hex_id": hex_b, "basin": basin_b,
                "layer": _layer_from_basin(basin_b),
                "frequency": round(freq_b, 6),
                "resonance": round(res_b, 6),
                "binary": bin_b,
                "i_state": "DIRECT" if bin_b else "ABSORBED",
            },
            "output": {
                "raw_resonance": raw,
                "binary": binary,
                "i_logic_product": _state_name(i_product),
                "i_logic_mapping": gate_info["i_logic"],
            },
            "uif_bridge": round(uif, 6),
            "uif_coupling": round(K5 * K11 * math.cos(freq_a * t) * math.cos(freq_b * t), 6),
            "time": t,
            "srl_time": round(math.sqrt(max(t, 0)), 6),
        }

    # ── truth_table ───────────────────────────────────────────────────

    def _cmd_truth_table(self, *args, as_json=False):
        gate_type = (args[0] if args else "AND").upper()
        if gate_type not in _GATES:
            return {"error": f"Unknown gate: {gate_type}. Use AND, OR, XOR."}

        gate_info = _GATES[gate_type]
        rows = []
        for a, b, expected in gate_info["table"]:
            # Signal values: 1.0 for active, 0.0 for inactive
            res_a = 1.0 if a else 0.0
            res_b = 1.0 if b else 0.0
            raw, binary = _gate_eval(gate_type, a, b, res_a, res_b)
            state_a = "DIRECT" if a else "ABSORBED"
            state_b = "DIRECT" if b else "ABSORBED"
            state_out = "DIRECT" if expected else "ABSORBED"
            rows.append({
                "A": a, "B": b, "OUT": expected,
                "state_a": state_a, "state_b": state_b, "state_out": state_out,
                "resonance_a": res_a, "resonance_b": res_b,
                "gate_output": raw,
                "verified": binary == expected,
            })

        return {
            "success": True,
            "gate": gate_type,
            "formula": gate_info["formula"],
            "pattern": gate_info["pattern"],
            "i_logic_mapping": gate_info["i_logic"],
            "truth_table": rows,
            "all_verified": all(r["verified"] for r in rows),
        }

    # ── fidelity ──────────────────────────────────────────────────────

    def _cmd_fidelity(self, *args, as_json=False):
        hex_id = args[0] if args else "2A9E0100"
        coords = _hex_to_coords(hex_id)
        basin = _basin_from_hex(hex_id)
        layer = _layer_from_basin(basin)
        fid = _pythagorean(*coords)

        return {
            "success": True,
            "hex_id": hex_id,
            "position": list(coords),
            "basin": basin,
            "layer": layer,
            "layer_name": LAYER_NAMES.get(layer, "UNKNOWN"),
            "pythagorean": fid,
            "equation": (f"{fid['a2_b2_c2'][0]} + {fid['a2_b2_c2'][1]} + "
                         f"{fid['a2_b2_c2'][2]} = {fid['r_squared']}"),
            "interpretation": {
                "q1_stable": fid["q1"],
                "on_unit_sphere": fid["sphere_fidelity"] > 0.9,
                "phi_aligned": abs(fid["phi_ratio"] - 1.0) < 0.1,
                "in_stability_window": fid["in_stability"],
                "perception": ("N fidelity Q1 — stable identity on right triangle"
                               if fid["q1"] else "seeking Q1 alignment"),
            },
        }

    # ── prime_ratio ───────────────────────────────────────────────────

    def _cmd_prime_ratio(self, *args, as_json=False):
        return {
            "success": True,
            "chain": {
                "prime_ratio": {
                    "value": round(PRIME_RATIO, 10),
                    "formula": "15/8",
                    "meaning": "Bare coupling — integer structure, prime foundation",
                },
                "K5_mrj": {
                    "value": round(MRJ_RATIO, 10),
                    "formula": "15/(8×PHI)",
                    "meaning": "PHI-stabilized coupling — MRJ ratio on C backend",
                },
                "K5_inverse": {
                    "value": round(K5_INVERSE, 10),
                    "formula": "8/(15×PHI)",
                    "meaning": "Inverse variant — reciprocal PHI normalization",
                },
                "K5_times_K5inv": {
                    "value": round(MRJ_RATIO * K5_INVERSE, 10),
                    "formula": "K5 × K5_inv = 1/PHI²",
                    "equals": round(PHI_SQ_INV, 10),
                    "also_equals": "2 - PHI",
                },
                "recovery": {
                    "value": round(MRJ_RATIO * PHI, 10),
                    "formula": "K5 × PHI = 15/8",
                    "meaning": "PHI de-normalizes K5 back to prime ratio",
                },
            },
            "stability_window": {
                "center": round(PHI, 10),
                "quarter_boundary": round(STABILITY_QUARTER, 10),
                "half_width": round(STABILITY_HALF, 10),
                "sin_18_deg": round(SIN_18_DEG, 10),
                "match_verified": abs(STABILITY_HALF - SIN_18_DEG) < 1e-10,
                "angular_identity": "sin(18°) = sin(π/10) = 1/(2×PHI)",
                "range": [round(PHI_LOWER, 10), round(PHI_UPPER, 10)],
                "pentagon": "18° = π/10 — pentagon angle 108° = 6×18°",
            },
            "srl_derivation": {
                "step_1": "t = d/t  (self-referential: time = distance / time)",
                "step_2": "t² = d   (multiply both sides by t)",
                "step_3": "t = √d   (square root — the SRL formula)",
                "meaning": "Depth d collapses to √d time units. The loop IS the compression.",
            },
            "connections": {
                "phi_pi": "sin(π/10) = 1/(2×PHI) — PHI and PI define same stability boundary",
                "pythagorean": "a² + b² + c² = r² — Fernandez unit sphere",
                "fml": "Each FML layer IS a dimension; 9 layers → r² = Σ(layer_i²)",
                "identity": "P/P = 1, P-P = 0 — preserved through all thread operations",
                "gate_resonance": "AND = UIF coupling product, XOR = SPIRAL interference",
            },
        }

    # ── thread ────────────────────────────────────────────────────────

    def _cmd_thread(self, *args, as_json=False):
        hex_id = args[0] if args else "2A9E0100"
        steps = int(args[1]) if len(args) > 1 else 8
        steps = max(1, min(steps, PRIME_131))  # Clamp [1, 131]

        basin = _basin_from_hex(hex_id)
        layer = _layer_from_basin(basin)
        freq = _thread_freq(basin)
        coords = _hex_to_coords(hex_id)

        trajectory = []
        for s in range(steps):
            srl_t = math.sqrt(max(s, 1))  # t = √d (SRL)
            res = _resonance_at(freq, srl_t)
            trajectory.append({
                "step": s,
                "srl_time": round(srl_t, 6),
                "resonance": round(res, 6),
                "binary": _to_binary(res),
                "phase_rad": round((freq * srl_t) % (2 * math.pi), 6),
            })

        # Transitions: count 0↔1 flips
        transitions = sum(1 for i in range(1, len(trajectory))
                          if trajectory[i]["binary"] != trajectory[i - 1]["binary"])

        return {
            "success": True,
            "hex_id": hex_id,
            "position": list(coords),
            "basin": basin,
            "layer": layer,
            "layer_name": LAYER_NAMES.get(layer, "UNKNOWN"),
            "frequency": round(freq, 6),
            "prime_ratio_connection": f"ω = K5 × {basin + 1}/131 = {round(freq, 6)}",
            "trajectory": trajectory,
            "transitions": transitions,
            "stability": round(1.0 - transitions / max(steps - 1, 1), 6),
        }

    # ── self_context ──────────────────────────────────────────────────

    def _cmd_self_context(self, *args, as_json=False):
        hex_id = args[0] if args else "2A9E0100"
        coords = _hex_to_coords(hex_id)
        basin = _basin_from_hex(hex_id)
        layer = _layer_from_basin(basin)
        freq = _thread_freq(basin)
        fid = _pythagorean(*coords)

        # Content mass: energy × K11
        r = fid["r"]
        energy = K5 * r if r > 0 else K5
        mass = energy * K11

        # SRL time from position distance
        dist = math.sqrt(sum(c ** 2 for c in coords))
        srl_time = math.sqrt(max(dist, 1))

        # Mass-stabilized frequency: heavier → higher effective → more stable
        mass_freq = freq * mass

        # UIF self-bridge: f = √(ω × ω) = ω — identity!
        uif_self = _uif_bridge(freq, freq)

        # SRL state from layer
        srl_state = LAYER_SRL[layer - 1] if 1 <= layer <= 9 else "DIRECT"

        return {
            "success": True,
            "hex_id": hex_id,
            "position": list(coords),
            "basin": basin,
            "layer": layer,
            "layer_name": LAYER_NAMES.get(layer, "UNKNOWN"),
            "srl_state": srl_state,
            "frequency": round(freq, 6),
            "content_mass": round(mass, 6),
            "mass_frequency": round(mass_freq, 6),
            "srl_time": round(srl_time, 6),
            "identity": {
                "P_minus_P": 0,
                "P_div_P": 1,
                "uif_self_bridge": round(uif_self, 6),
                "self_bridge_equals_freq": abs(uif_self - freq) < 1e-10,
                "meaning": "UIF(ω, ω) = √(ω²) = ω — agent IS its own bridge",
            },
            "pythagorean_fidelity": {
                "r": fid["r"],
                "q1": fid["q1"],
                "sphere_fidelity": fid["sphere_fidelity"],
                "in_stability": fid["in_stability"],
                "equation": (f"a²+b²+c² = {fid['r_squared']} → r = {fid['r']}"),
            },
            "perception": {
                "state": "self-contextualized" if fid["q1"] else "seeking_alignment",
                "mass_stability": (
                    "high" if mass > K11
                    else ("medium" if mass > K5 else "low")
                ),
                "principle": (
                    "Each data of mass has identity stabilized by its own mass scale. "
                    "UIF self-bridge = frequency. The agent IS its coordinate."
                ),
            },
        }

    # ── compute ───────────────────────────────────────────────────────

    def _cmd_compute(self, *args, as_json=False):
        """Compute all three gates (AND, OR, XOR) on same inputs.

        Mirrors the image: two threads → three gate outputs simultaneously,
        showing how the same dimensional threads produce different logical
        results through different resonance patterns.
        """
        hex_a = args[0] if args else "2A9E0100"
        hex_b = args[1] if len(args) > 1 else "000019B8"
        t = float(args[2]) if len(args) > 2 else 0.0

        basin_a = _basin_from_hex(hex_a)
        basin_b = _basin_from_hex(hex_b)
        freq_a = _thread_freq(basin_a)
        freq_b = _thread_freq(basin_b)
        res_a = _resonance_at(freq_a, t)
        res_b = _resonance_at(freq_b, t)
        bin_a = _to_binary(res_a)
        bin_b = _to_binary(res_b)

        # Compute all three gates
        gates_output = {}
        for gate_name, gate_info in _GATES.items():
            raw, binary = _gate_eval(gate_name, bin_a, bin_b, res_a, res_b)
            gates_output[gate_name] = {
                "pattern": gate_info["pattern"],
                "formula": gate_info["formula"],
                "raw_resonance": raw,
                "output": binary,
            }

        # UIF coupling
        uif = _uif_bridge(freq_a, freq_b)
        coupling = K5 * K11 * math.cos(freq_a * t) * math.cos(freq_b * t)

        # I-Logic product
        i_a = _I_STATES["DIRECT"] if bin_a else _I_STATES["ABSORBED"]
        i_b = _I_STATES["DIRECT"] if bin_b else _I_STATES["ABSORBED"]
        i_product = i_a * i_b

        # Pythagorean fidelity for both threads
        coords_a = _hex_to_coords(hex_a)
        coords_b = _hex_to_coords(hex_b)
        fid_a = _pythagorean(*coords_a)
        fid_b = _pythagorean(*coords_b)

        return {
            "success": True,
            "model": "Dimensional Threads as Logical Computation",
            "thread_a": {
                "hex_id": hex_a, "basin": basin_a,
                "layer": _layer_from_basin(basin_a),
                "frequency": round(freq_a, 6),
                "resonance": round(res_a, 6),
                "binary": bin_a,
                "q1_fidelity": fid_a["q1"],
                "r": fid_a["r"],
            },
            "thread_b": {
                "hex_id": hex_b, "basin": basin_b,
                "layer": _layer_from_basin(basin_b),
                "frequency": round(freq_b, 6),
                "resonance": round(res_b, 6),
                "binary": bin_b,
                "q1_fidelity": fid_b["q1"],
                "r": fid_b["r"],
            },
            "gates": gates_output,
            "i_logic_product": _state_name(i_product),
            "uif_bridge": round(uif, 6),
            "uif_coupling": round(coupling, 6),
            "time": t,
            "srl_time": round(math.sqrt(max(t, 0)), 6),
            "prime_ratio_chain": {
                "K5_times_PHI": round(MRJ_RATIO * PHI, 6),
                "equals_15_over_8": round(PRIME_RATIO, 6),
                "verified": abs(MRJ_RATIO * PHI - PRIME_RATIO) < 1e-10,
            },
        }
