"""
FlowTorch Op Dispatcher with SAT Gate Enforcement
Fail-closed: raises RuntimeError on unauthorized ops
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from flowtorch.sat_gate import SatGate

# Initialize SAT gate at module load
_SAT = SatGate(str(Path(__file__).parent.parent / "morph_sat" / "matrix.v1.json"))

def dispatch(op_name: str, *args, **kwargs):
    """
    Central op dispatcher with SAT gate enforcement.

    Args:
        op_name: Operation name (e.g., "conv1d_b64", "attn_b64")
        *args, **kwargs: Op-specific arguments

    Returns:
        Result from the dispatched operation

    Raises:
        RuntimeError: If op_name is not authorized by Morph-SAT matrix
    """
    # Hard gate: raises RuntimeError if op not in SAT matrix
    _SAT.allow(op_name)

    # Dispatch to real implementation
    # (This is a stub - actual implementations would be registered here)
    return _dispatch_impl(op_name, *args, **kwargs)


def _dispatch_impl(op_name: str, *args, **kwargs):
    """
    Actual op implementations (stub for now).
    In production, this would route to:
    - conv1d_b64 → compressed-domain 1D convolution
    - attn_b64 → base64 attention mechanism
    - gelu_b64 → compressed-domain GELU
    - etc.
    """
    # Stub implementation
    raise NotImplementedError(
        f"Op '{op_name}' is authorized by SAT matrix but not yet implemented. "
        f"Add implementation in flowtorch/ops/{op_name}.py"
    )


if __name__ == "__main__":
    # Self-test: verify fail-closed behavior
    print("Testing SAT gate enforcement in op_dispatch...")

    # Test 1: Known op should pass gate (but fail implementation)
    try:
        dispatch("conv1d_b64")
    except NotImplementedError:
        print("✅ Known op passed SAT gate (implementation stub raised as expected)")
    except RuntimeError as e:
        print(f"❌ Known op failed SAT gate: {e}")
        sys.exit(1)

    # Test 2: Unknown op should fail at gate
    try:
        dispatch("forbidden_op_xyz")
        print("❌ Forbidden op did NOT raise (fail-open vulnerability!)")
        sys.exit(1)
    except RuntimeError as e:
        if "not in satisfiability matrix" in str(e):
            print("✅ Forbidden op correctly blocked by SAT gate (fail-closed)")
        else:
            print(f"❌ Wrong error message: {e}")
            sys.exit(1)

    print("\n✅ All SAT gate enforcement tests passed")
