"""Helix CLI for evaluation and management commands."""

from __future__ import annotations

import argparse
import asyncio
import os
import sys


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="helix",
        description="Helix: Temporal GraphRAG - LightRAG + Graphiti",
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Available commands")
    
    # Info command
    info_parser = subparsers.add_parser("info", help="Show Helix information")
    
    # Serve command
    serve_parser = subparsers.add_parser("serve", help="Start the Helix API server")
    serve_parser.add_argument(
        "--host",
        type=str,
        default=os.getenv("HELIX_HOST", "0.0.0.0"),
        help="Host to bind the server to (default: 0.0.0.0)",
    )
    serve_parser.add_argument(
        "--port",
        type=int,
        default=int(os.getenv("HELIX_PORT", "9621")),
        help="Port to listen on (default: 9621)",
    )
    serve_parser.add_argument(
        "--reload",
        action="store_true",
        default=False,
        help="Enable auto-reload for development",
    )
    serve_parser.add_argument(
        "--workers",
        type=int,
        default=1,
        help="Number of worker processes (default: 1)",
    )
    
    # Eval command
    eval_parser = subparsers.add_parser("eval", help="Run benchmarks")
    eval_parser.add_argument(
        "--dataset",
        type=str,
        choices=[
            "time-longqa", "ect-qa", "multitq", "tsqa",
            "musique", "2wikimhqa", "hotpotqa",
            "fever", "legal-qa", "medical-qa",
            "ultradomain",
        ],
        help="Dataset to evaluate on",
    )
    eval_parser.add_argument(
        "--max-samples",
        type=int,
        default=100,
        help="Maximum number of samples to evaluate",
    )
    eval_parser.add_argument(
        "--output",
        type=str,
        default="eval_results.json",
        help="Output file for results",
    )
    
    # Version command
    version_parser = subparsers.add_parser("version", help="Show version")
    
    args = parser.parse_args()
    
    if args.command == "info":
        show_info()
    elif args.command == "serve":
        run_server(args)
    elif args.command == "eval":
        asyncio.run(run_eval(args))
    elif args.command == "version":
        show_version()
    else:
        parser.print_help()


def show_info():
    """Show Helix system information."""
    from helix import __version__
    
    print("=" * 50)
    print("🧬 Helix: Temporal GraphRAG")
    print("=" * 50)
    print(f"Version: {__version__}")
    print()
    print("Components:")
    print("  ✓ LightRAG (Retrieval)")
    print("  ✓ Graphiti (Temporal KG)")
    print("  ✓ TemporalQueryHandler")
    print("  ✓ HallucinationDetector")
    print("  ✓ MultiHopRetriever")
    print("  ✓ Helix API Server")
    print()
    
    # Check environment
    print("Environment:")
    neo4j_configured = bool(os.getenv("NEO4J_URI"))
    supabase_configured = bool(os.getenv("SUPABASE_URL"))
    llm_configured = bool(os.getenv("LLM_API_KEY"))
    
    print(f"  Neo4j: {'✓ Configured' if neo4j_configured else '✗ Not configured'}")
    print(f"  Supabase: {'✓ Configured' if supabase_configured else '○ Optional'}")
    print(f"  LLM: {'✓ Configured' if llm_configured else '✗ Not configured'}")
    print()
    print("Commands:")
    print("  helix serve              Start the API server")
    print("  helix serve --port 8000  Start on custom port")
    print("  helix eval --help        Run evaluations")


def run_server(args):
    """Start the Helix API server using uvicorn."""
    try:
        import uvicorn
    except ImportError:
        print("Error: uvicorn is required to run the Helix API server.")
        print("Install with: pip install helix-rag[api]")
        sys.exit(1)

    from helix import __version__

    print("=" * 50)
    print("🧬 Helix API Server")
    print("=" * 50)
    print(f"Version:  {__version__}")
    print(f"Host:     {args.host}")
    print(f"Port:     {args.port}")
    print(f"Workers:  {args.workers}")
    print(f"Reload:   {args.reload}")
    print(f"Docs:     http://{args.host}:{args.port}/docs")
    print("=" * 50)

    uvicorn.run(
        "helix.api.server:app",
        host=args.host,
        port=args.port,
        reload=args.reload,
        workers=args.workers,
        log_level="info",
    )


def show_version():
    """Show version."""
    from helix import __version__
    print(f"helix-rag {__version__}")


async def run_eval(args):
    """Run benchmark evaluation."""
    import json
    
    from helix.eval import (
        TemporalBenchmark,
        MultiHopBenchmark,
        HallucinationBenchmark,
        ScalabilityBenchmark,
    )
    
    dataset = args.dataset
    max_samples = args.max_samples
    
    print(f"🧪 Running evaluation on {dataset}...")
    print(f"   Max samples: {max_samples}")
    print()
    
    # Determine benchmark type
    if dataset in ["time-longqa", "ect-qa", "multitq", "tsqa"]:
        benchmark = TemporalBenchmark(dataset, max_samples=max_samples)
    elif dataset in ["musique", "2wikimhqa", "hotpotqa"]:
        benchmark = MultiHopBenchmark(dataset, max_samples=max_samples)
    elif dataset in ["fever", "legal-qa", "medical-qa"]:
        benchmark = HallucinationBenchmark(dataset, max_samples=max_samples)
    elif dataset in ["ultradomain"]:
        benchmark = ScalabilityBenchmark(dataset, max_samples=max_samples)
    else:
        print(f"Unknown dataset: {dataset}")
        sys.exit(1)
    
    result = await benchmark.run()
    
    print()
    print("📊 Results:")
    print("-" * 40)
    for key, value in result.metrics.items():
        if isinstance(value, float):
            print(f"  {key}: {value:.4f}")
        else:
            print(f"  {key}: {value}")
    print("-" * 40)
    print(f"  Samples: {result.num_samples}")
    print(f"  Runtime: {result.runtime_seconds:.2f}s")
    
    # Save results
    with open(args.output, "w") as f:
        json.dump(result.to_dict(), f, indent=2)
    print(f"\n✓ Results saved to {args.output}")


if __name__ == "__main__":
    main()
