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

Elevated from R&D (flowtorch_format_router.py).

Technical function:
- Universal model format detection and routing
- Detects .gguf, .hx, .hxz, .bin, .safetensors formats

Notes:
- This is not "quantum routing", it's file extension-based dispatch.
- Integrated as OPTIONAL format detection layer.
"""

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


ModelFormat = Literal["gguf", "helix_hx", "helix_hxz", "hf_bin", "hf_safetensors", "unknown"]


class FormatRouter:
    """
    Universal model format detector and router.

    Identifies model file formats and provides routing information.
    """

    def __init__(self):
        self.format_handlers = {
            ".gguf": "gguf",
            ".hx": "helix_hx",
            ".hxz": "helix_hxz",
            ".bin": "hf_bin",
            ".safetensors": "hf_safetensors"
        }

    def detect_format(self, path: Path) -> ModelFormat:
        """
        Detect model format from file extension.

        Args:
            path: Path to model file

        Returns:
            Model format identifier
        """
        ext = path.suffix.lower()
        return self.format_handlers.get(ext, "unknown")

    def route_model(self, path: Path) -> Dict:
        """
        Generate routing information for a model file.

        Args:
            path: Path to model file

        Returns:
            Dict with routing metadata
        """
        format_type = self.detect_format(path)

        return {
            "path": str(path),
            "name": path.stem,
            "format": format_type,
            "extension": path.suffix.lower(),
            "detected_at": datetime.now().isoformat()
        }

    def scan_directory(self, directory: Path, recursive: bool = False) -> List[Dict]:
        """
        Scan directory for model files and generate routing info.

        Args:
            directory: Directory to scan
            recursive: If True, scan subdirectories

        Returns:
            List of routing metadata dicts
        """
        results = []

        pattern = "**/*" if recursive else "*"
        for path in directory.glob(pattern):
            if path.is_file():
                format_type = self.detect_format(path)
                if format_type != "unknown":
                    results.append(self.route_model(path))

        return results

    def get_handler_suggestion(self, format_type: ModelFormat) -> Optional[str]:
        """
        Get suggested handler tool for a given format.

        Args:
            format_type: Model format

        Returns:
            Suggested handler name or None
        """
        handlers = {
            "gguf": "llama.cpp / gguf_runner",
            "helix_hx": "helix_runner",
            "helix_hxz": "helixz_runtime_boot",
            "hf_bin": "huggingface transformers",
            "hf_safetensors": "huggingface transformers"
        }

        return handlers.get(format_type)

    def format_report(self, models: List[Dict]) -> str:
        """
        Generate human-readable routing report.

        Args:
            models: List of model routing dicts

        Returns:
            Formatted report string
        """
        if not models:
            return "No models found."

        lines = [
            f"Model Format Routing Report ({len(models)} models)",
            "=" * 60,
            ""
        ]

        # Group by format
        by_format: Dict[str, List[Dict]] = {}
        for model in models:
            fmt = model["format"]
            if fmt not in by_format:
                by_format[fmt] = []
            by_format[fmt].append(model)

        # Report each format group
        for fmt, group in sorted(by_format.items()):
            handler = self.get_handler_suggestion(fmt)
            lines.append(f"{fmt.upper()} ({len(group)} files)")
            if handler:
                lines.append(f"  Handler: {handler}")
            for model in group:
                lines.append(f"  - {model['name']}{model['extension']}")
            lines.append("")

        return "\n".join(lines)


# Convenience functions for quick use

def detect_format(path: Path) -> ModelFormat:
    """Quick format detection"""
    router = FormatRouter()
    return router.detect_format(path)


def route_model(path: Path) -> Dict:
    """Quick routing info generation"""
    router = FormatRouter()
    return router.route_model(path)


def scan_models(directory: Path, recursive: bool = False) -> List[Dict]:
    """Quick directory scan"""
    router = FormatRouter()
    return router.scan_directory(directory, recursive)
