#!/usr/bin/env python3
"""
krisper_bridge.py

Elevated from R&D (shotgun_flowtorch_krisper_adapter.py).

Technical function:
- Natural language command routing to different execution backends
- Parses commands and routes to: helixz models, shell, or LLM

Notes:
- This is not "quantum" anything, it's a simple command parser.
- Integrated as OPTIONAL natural language interface.
"""

from pathlib import Path
from typing import Dict, Literal, Optional
from datetime import datetime, timezone


RouteType = Literal["helixz", "shell", "llm", "unknown"]


class KRISPERBridge:
    """
    Natural language command router.

    Parses simple commands and routes them to appropriate backends:
    - .helixz files → Load and track in memory
    - !shell commands → Execute shell
    - llm: prompts → Send to LLM
    """

    def __init__(self,
                 helixz_dir: Optional[Path] = None,
                 model_path: Optional[Path] = None):
        """
        Initialize KRISPER bridge.

        Args:
            helixz_dir: Directory containing .helixz capsules
            model_path: Path to LLM model file
        """
        self.helixz_dir = helixz_dir or Path.home() / "EchoLivingSystem/genesis/fibpi3d/helixz"
        self.model_path = model_path
        self.loaded_capsules: Dict[str, Dict] = {}

    def detect_route_type(self, command: str) -> RouteType:
        """
        Detect the type of command.

        Args:
            command: User command string

        Returns:
            Route type identifier
        """
        command = command.strip()

        if command.endswith(".helixz"):
            return "helixz"
        elif command.startswith("!"):
            return "shell"
        elif command.startswith("llm:"):
            return "llm"
        else:
            return "unknown"

    def entropy_score(self, glyph: str) -> float:
        """
        Calculate simple entropy score from glyph.

        Args:
            glyph: String content

        Returns:
            Entropy score (0.0 to 1.0)
        """
        if not glyph:
            return 0.0

        unique_chars = len(set(glyph))
        # Normalize to 7 (original implementation)
        return round(unique_chars / 7.0, 4)

    def route_helixz(self, capsule_name: str) -> Dict:
        """
        Route helixz capsule command.

        Args:
            capsule_name: Name of .helixz file

        Returns:
            Dict with routing metadata
        """
        capsule_path = self.helixz_dir / capsule_name

        if not capsule_path.exists():
            return {
                "status": "error",
                "route": "helixz",
                "error": f"Capsule not found: {capsule_name}"
            }

        # Load capsule content
        try:
            with open(capsule_path) as f:
                content = "".join([line for line in f if not line.startswith("#")])

            entropy = self.entropy_score(content)
            label = capsule_path.stem
            soul = label.split("_")[-1] if "_" in label else "unknown"

            # Calculate port from soul hash
            try:
                port = int(soul[:4], 16) % 144
            except (ValueError, IndexError):
                port = 0

            metadata = {
                "status": "success",
                "route": "helixz",
                "capsule": capsule_name,
                "label": label,
                "entropy": entropy,
                "soul": soul,
                "port": port,
                "timestamp": datetime.now(timezone.utc).isoformat()
            }

            # Store in memory
            self.loaded_capsules[label] = metadata

            return metadata

        except Exception as e:
            return {
                "status": "error",
                "route": "helixz",
                "error": str(e)
            }

    def route_shell(self, shell_command: str) -> Dict:
        """
        Route shell command (no execution, just metadata).

        Args:
            shell_command: Shell command (without ! prefix)

        Returns:
            Dict with routing metadata
        """
        return {
            "status": "ready",
            "route": "shell",
            "command": shell_command,
            "note": "Shell execution not implemented in bridge (security)"
        }

    def route_llm(self, prompt: str) -> Dict:
        """
        Route LLM prompt (no execution, just metadata).

        Args:
            prompt: LLM prompt (without llm: prefix)

        Returns:
            Dict with routing metadata
        """
        return {
            "status": "ready",
            "route": "llm",
            "prompt": prompt,
            "model_path": str(self.model_path) if self.model_path else "not configured",
            "note": "LLM execution requires external integration"
        }

    def parse_command(self, command: str) -> Dict:
        """
        Parse command and generate routing metadata.

        Args:
            command: User command string

        Returns:
            Dict with routing metadata and status
        """
        route_type = self.detect_route_type(command)

        if route_type == "helixz":
            return self.route_helixz(command.strip())

        elif route_type == "shell":
            # Remove ! prefix
            shell_cmd = command[1:].strip()
            return self.route_shell(shell_cmd)

        elif route_type == "llm":
            # Remove llm: prefix
            prompt = command[4:].strip()
            return self.route_llm(prompt)

        else:
            return {
                "status": "error",
                "route": "unknown",
                "error": "Unknown command type. Use: .helixz file, !shell, or llm:prompt"
            }

    def get_loaded_capsules(self) -> Dict[str, Dict]:
        """
        Get all loaded capsule metadata.

        Returns:
            Dict mapping capsule label to metadata
        """
        return self.loaded_capsules.copy()

    def clear_loaded_capsules(self):
        """Clear all loaded capsule metadata from memory."""
        self.loaded_capsules.clear()


# Convenience function for quick use

def parse_command(command: str,
                  helixz_dir: Optional[Path] = None) -> Dict:
    """
    Quick command parsing.

    Args:
        command: User command string
        helixz_dir: Optional helixz directory path

    Returns:
        Routing metadata dict
    """
    bridge = KRISPERBridge(helixz_dir=helixz_dir)
    return bridge.parse_command(command)
