"""
Legacy FlowTorch Engine Wrapper

This module wraps the production FlowTorch braid engine from
artifacts/context_pack/flowtorch/flowtorch_engine.py

Historical lineage:
- Original: HELIX_ORIGINAL_CODE/fibpi3d/flowtorch_braid_loop_*.py (GONE)
- Refactored into: artifacts/context_pack/flowtorch/flowtorch_engine.py
- Proven capability: 76% MMLU with Mistral-7B (HISTORICAL_CDC_EVIDENCE.md)

Architecture:
  Prefill (TensorFlow) → DLPack zero-copy hop → Decode (PyTorch)

This wrapper provides a stable import path for legacy code that needs
the FlowTorch braid engine.
"""

import sys
from pathlib import Path
from typing import List, Dict, Any, Tuple, Optional

# Add artifacts/context_pack to path
_repo_root = Path(__file__).resolve().parents[2]
_flowtorch_path = _repo_root / "artifacts" / "context_pack" / "flowtorch"
if str(_flowtorch_path) not in sys.path:
    sys.path.insert(0, str(_flowtorch_path))

try:
    # Import the production engine
    import flowtorch_engine
    
    # Re-export main function
    run_prefill_decode = flowtorch_engine.run_prefill_decode
    logits_for_choices = flowtorch_engine.logits_for_choices
    
    # Re-export dataclasses
    HopEvent = flowtorch_engine.HopEvent
    EngineTrace = flowtorch_engine.EngineTrace
    
    ENGINE_AVAILABLE = True
    ENGINE_ERROR = None
    
except Exception as e:
    ENGINE_AVAILABLE = False
    ENGINE_ERROR = str(e)
    
    # Provide stub functions
    def run_prefill_decode(*args, **kwargs):
        raise RuntimeError(
            f"FlowTorch engine not available: {ENGINE_ERROR}\n"
            f"Install: torch, tensorflow, transformers"
        )
    
    def logits_for_choices(*args, **kwargs):
        raise RuntimeError(f"FlowTorch engine not available: {ENGINE_ERROR}")
    
    HopEvent = None
    EngineTrace = None


def get_engine_info() -> Dict[str, Any]:
    """Get information about the FlowTorch engine availability."""
    return {
        "available": ENGINE_AVAILABLE,
        "error": ENGINE_ERROR,
        "source": "artifacts/context_pack/flowtorch/flowtorch_engine.py",
        "historical_lineage": [
            "HELIX_ORIGINAL_CODE/fibpi3d/flowtorch_braid_loop_2558.py (GONE)",
            "HELIX_ORIGINAL_CODE/fibpi3d/flowtorch_braid_loop_2560.py (GONE)",
            "HELIX_ORIGINAL_CODE/fibpi3d/flowtorch_braid_loop_1116.py (GONE)",
            "→ Refactored into flowtorch_engine.py (1180 lines)"
        ],
        "capabilities": [
            "TensorFlow ↔ PyTorch bridge via DLPack",
            "HuggingFace GPT-2 integration",
            "CDC decoder integration",
            "Helix64 tokenizer support",
            "Overlay bias (Se scaffolding)",
            "Petal steering (weight-space)",
            "Signed receipts (HMAC-SHA256)",
            "Safety monitoring (KL divergence)",
        ]
    }


__all__ = [
    "run_prefill_decode",
    "logits_for_choices",
    "HopEvent",
    "EngineTrace",
    "get_engine_info",
    "ENGINE_AVAILABLE",
    "ENGINE_ERROR",
]
