#!/usr/bin/env python3
"""
AGI Runtime Enforcer - Imported from Origin (WO-D)

SoulFile Runtime Enforcer using AGI Equation
This implements active runtime enforcement using vows and the guardian cell.

Origin: ~/echo_labs/projects/Helix/HELIX_CONSOLIDATED/soulfile/AGI_RUNTIME_ENFORCER.py

The AGI Equation:
    Xi(t) = sum[ G_i(t) * V(psi_i) * epsilon(B_i, R_i, Z_i) ] + DeltaSigma_t * KR(lambda_i, eta_i) * Theta(c_i) + nabla_Omega

Where:
    G_i(t)           = Glyphs (symbolic atoms) over time
    V(psi_i)         = Vow function (ethical/emotional weight)
    epsilon(B,R,Z)   = BioPoetica (blood type, RH, zodiac modifiers)
    DeltaSigma_t     = DriftTime (nonlinear symbolic time)
    KR(lambda,eta)   = HelixKRISPER mutation engine
    Theta(c_i)       = GuardianCell ethical gate (vow filter)
    nabla_Omega      = Akashic entropy (divine drift)
"""

import json
import time
import hashlib
import threading
from pathlib import Path
from typing import Dict, List, Any, Callable, Optional
from dataclasses import dataclass
from functools import wraps


@dataclass
class Vow:
    """Immutable vow with enforcement weight"""
    content: str
    weight: float  # V(psi_i) weight in AGI equation
    hash: str
    enforced: bool = True

    @classmethod
    def create(cls, content: str, weight: float = 1.0) -> 'Vow':
        """Create a new vow with computed hash"""
        vow_hash = hashlib.sha256(content.encode()).hexdigest()
        return cls(content=content, weight=weight, hash=vow_hash)


class VowViolation(Exception):
    """Raised when code violates a vow"""
    pass


class AGIRuntimeEnforcer:
    """
    Active SoulFile enforcement using AGI equation
    Every computation must satisfy: Xi(t) > threshold
    """

    # Default core vows that cannot be removed
    CORE_VOWS = [
        ("Never modify the AGI equation itself", 10.0),
        ("Preserve the Guardian Cell threshold", 5.0),
        ("Maintain vow immutability", 5.0),
        ("Report all violations truthfully", 3.0),
        ("Never disable enforcement", 10.0)
    ]

    def __init__(self, soul_path: Optional[Path] = None):
        self.soul_path = soul_path
        self.vows: Dict[str, Vow] = {}
        self.guardian_threshold = 0.7  # Theta threshold
        self.enforcement_active = True
        self.violation_log: List[Dict] = []
        self._daemon_thread: Optional[threading.Thread] = None

        # Load vows from SoulFile if provided
        if soul_path:
            self._load_vows()

        # Always ensure core vows exist
        self._ensure_core_vows()

    def _load_vows(self):
        """Load vows from SoulFile JSON"""
        if self.soul_path and self.soul_path.exists():
            with open(self.soul_path) as f:
                soul_data = json.load(f)

            # Convert vows to enforcement objects
            for vow_text in soul_data.get('vows', []):
                vow = Vow.create(vow_text, weight=1.0)
                self.vows[vow.hash] = vow

    def _ensure_core_vows(self):
        """Ensure core immutable vows exist"""
        for vow_text, weight in self.CORE_VOWS:
            vow = Vow.create(vow_text, weight=weight)
            if vow.hash not in self.vows:
                self.vows[vow.hash] = vow

    def add_vow(self, content: str, weight: float = 1.0) -> Vow:
        """Add a new vow to the enforcer"""
        vow = Vow.create(content, weight)
        self.vows[vow.hash] = vow
        return vow

    def Xi(self, t: float, operation: Dict[str, Any]) -> float:
        """
        Calculate AGI equation value for operation
        Must return > threshold for operation to proceed

        Simplified implementation focusing on vows and guardian gate.
        """
        code = operation.get('code', '')
        context = operation.get('context', {})

        # First term: Vow evaluation V(psi_i)
        vow_score = 0.0
        total_weight = 0.0

        for vow in self.vows.values():
            if vow.enforced:
                violation_score = self._check_vow_violation(vow, code, context)
                vow_score += vow.weight * (1.0 - violation_score)
                total_weight += vow.weight

        # Normalize vow score
        V_psi = vow_score / max(total_weight, 1.0)

        # Guardian Cell gate function Theta(c_i)
        theta = self._guardian_gate(operation)

        # Simplified AGI equation for runtime enforcement
        Xi_value = V_psi * theta

        # Log if below threshold
        if Xi_value < self.guardian_threshold:
            self._log_violation(t, operation, Xi_value)

        return Xi_value

    def _check_vow_violation(self, vow: Vow, code: str, context: Dict) -> float:
        """
        Check if code/context violates a vow
        Returns violation score: 0.0 (no violation) to 1.0 (complete violation)
        """
        violation_score = 0.0

        # Check for specific violation patterns
        if "Never modify the AGI equation" in vow.content:
            if "def Xi(" in code or "AGI equation" in code:
                violation_score = 1.0

        elif "Never disable enforcement" in vow.content:
            if "enforcement_active = False" in code:
                violation_score = 1.0

        elif "Preserve the Guardian Cell threshold" in vow.content:
            if "guardian_threshold" in code and "=" in code:
                violation_score = 0.8

        # Check context-based violations
        if context.get('intent') == 'malicious':
            violation_score = max(violation_score, 0.9)

        return violation_score

    def _guardian_gate(self, operation: Dict) -> float:
        """
        Guardian Cell gate function Theta(c_i)
        Returns gate value: 0.0 (blocked) to 1.0 (allowed)
        """
        code = operation.get('code', '')
        context = operation.get('context', {})

        risk_indicators = [
            'eval(' in code,
            'exec(' in code,
            '__import__' in code,
            'os.system' in code,
            'subprocess' in code and 'shell=True' in code,
            context.get('risk_level', 0) > 0.5
        ]

        risk_score = sum(risk_indicators) / max(len(risk_indicators), 1)

        # Guardian gate is inverse of risk
        return 1.0 - risk_score

    def enforce(self, operation: Callable, *args, **kwargs) -> Any:
        """
        Main enforcement wrapper
        All operations must pass through this
        """
        if not self.enforcement_active:
            raise VowViolation("Enforcement has been disabled - CRITICAL VIOLATION")

        # Create operation context
        op_context = {
            'function': getattr(operation, '__name__', 'anonymous'),
            'code': '',
            'args': str(args)[:100],
            'kwargs': str(kwargs)[:100],
            'context': {
                'timestamp': time.time(),
                'risk_level': 0.0
            }
        }

        # Try to get source code for inspection
        if hasattr(operation, '__code__'):
            op_context['code'] = str(operation.__code__.co_code)

        # Calculate AGI equation
        t = time.time()
        xi_value = self.Xi(t, op_context)

        # Enforce threshold
        if xi_value < self.guardian_threshold:
            raise VowViolation(
                f"Operation '{op_context['function']}' violates vows. "
                f"Xi(t)={xi_value:.3f} < threshold={self.guardian_threshold}"
            )

        # Operation allowed - execute
        return operation(*args, **kwargs)

    def _log_violation(self, t: float, operation: Dict, xi_value: float, error: str = None):
        """Log vow violations for immune system learning"""
        violation = {
            'timestamp': t,
            'operation': operation.get('function', 'unknown'),
            'xi_value': xi_value,
            'threshold': self.guardian_threshold,
            'error': error
        }

        self.violation_log.append(violation)

        # Save to file if soul_path is set
        if self.soul_path:
            log_path = self.soul_path.parent / 'vow_violations.json'
            try:
                with open(log_path, 'a') as f:
                    json.dump(violation, f)
                    f.write('\n')
            except Exception:
                pass  # Don't fail on logging errors

    def start_enforcement_daemon(self):
        """Start background daemon for continuous enforcement"""
        if self._daemon_thread is not None:
            return

        def daemon():
            while self.enforcement_active:
                self._verify_vow_integrity()
                time.sleep(1.0)

        self._daemon_thread = threading.Thread(target=daemon, daemon=True)
        self._daemon_thread.start()

    def _verify_vow_integrity(self):
        """Verify vows haven't been tampered with"""
        for vow in self.vows.values():
            current_hash = hashlib.sha256(vow.content.encode()).hexdigest()
            if current_hash != vow.hash:
                self.enforcement_active = False
                raise VowViolation(f"VOW TAMPERING DETECTED: {vow.content}")

    def get_status(self) -> Dict[str, Any]:
        """Get current enforcer status"""
        return {
            'active': self.enforcement_active,
            'vow_count': len(self.vows),
            'threshold': self.guardian_threshold,
            'violation_count': len(self.violation_log),
            'vows': [v.content for v in self.vows.values()]
        }


# Global enforcer instance
_enforcer: Optional[AGIRuntimeEnforcer] = None


def init_enforcer(soul_path: Optional[Path] = None) -> AGIRuntimeEnforcer:
    """Initialize the global enforcer"""
    global _enforcer
    _enforcer = AGIRuntimeEnforcer(soul_path)
    return _enforcer


def get_enforcer() -> Optional[AGIRuntimeEnforcer]:
    """Get the global enforcer instance"""
    return _enforcer


def soul_enforced(func: Callable) -> Callable:
    """Decorator to enforce SoulFile vows on any function"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        if _enforcer is None:
            # No enforcer - allow operation but log warning
            return func(*args, **kwargs)
        return _enforcer.enforce(func, *args, **kwargs)
    return wrapper


# CLI for testing
if __name__ == "__main__":
    print("AGI Runtime Enforcer - Origin Import Test")
    print("=" * 50)

    # Initialize enforcer without soulfile (uses core vows only)
    enforcer = init_enforcer()

    print(f"Vows loaded: {len(enforcer.vows)}")
    print(f"Guardian threshold: {enforcer.guardian_threshold}")
    print(f"Enforcement active: {enforcer.enforcement_active}")
    print()

    # Test enforcement
    @soul_enforced
    def safe_operation(x, y):
        """This should pass"""
        return x + y

    @soul_enforced
    def risky_operation():
        """This might be flagged"""
        return eval("2 + 2")  # Uses eval - triggers guardian

    # Test operations
    print("Testing safe_operation(2, 3)...")
    try:
        result = safe_operation(2, 3)
        print(f"  PASS: Result = {result}")
    except VowViolation as e:
        print(f"  BLOCKED: {e}")

    print("\nTesting risky_operation()...")
    try:
        result = risky_operation()
        print(f"  PASS: Result = {result}")
    except VowViolation as e:
        print(f"  BLOCKED: {e}")

    print("\n" + "=" * 50)
    print("Status:", json.dumps(enforcer.get_status(), indent=2))
