#!/usr/bin/env python3
"""CLI tool for testing denes-router-classifier package."""

import sys
import time
from pathlib import Path

# Add src to path for local testing
sys.path.insert(0, str(Path(__file__).parent / "src"))

import typer
from rich.console import Console
from rich.table import Table

from denes_router_classifier import classify_domain, classify_batch, __version__

app = typer.Typer(help="CLI for testing denes-router-classifier")
console = Console()


@app.command()
def classify(
    text: str = typer.Argument(..., help="Text to classify"),
    threshold: float = typer.Option(0.7, "--threshold", "-t", help="Confidence threshold (0-1)"),
    multi_label: bool = typer.Option(False, "--multi-label", "-m", help="Return all domains above threshold"),
):
    """Classify a single text query.

    Examples:
        python classify_cli.py classify "Busca el clima en Asunción"
        python classify_cli.py classify "No tengo internet" --threshold 0.5
        python classify_cli.py classify "Busca ayuda para mi PC" --multi-label
    """
    console.print(f"\n[bold blue]Classifying:[/bold blue] '{text}'")
    console.print(f"[dim]Threshold: {threshold} | Multi-label: {multi_label}[/dim]\n")

    start = time.perf_counter()
    result = classify_domain(text, threshold=threshold, multi_label=multi_label)
    latency = (time.perf_counter() - start) * 1000

    # Display results
    table = Table(title="Classification Result")
    table.add_column("Property", style="cyan")
    table.add_column("Value", style="green")

    table.add_row("Primary Domain", f"[bold]{result.primary}[/bold]")
    table.add_row("Confidence", f"{result.confidence:.4f} ({result.confidence * 100:.2f}%)")
    table.add_row("Includes Generic", str(result.includes_generic))
    table.add_row("Latency", f"{latency:.2f}ms")

    if result.all_predictions:
        table.add_row("All Predictions", f"{len(result.all_predictions)} domain(s)")

    console.print(table)

    if result.all_predictions:
        console.print("\n[bold]All Predictions:[/bold]")
        for pred in result.all_predictions:
            console.print(f"  • {pred.domain}: {pred.confidence:.4f} ({pred.confidence * 100:.2f}%)")

    console.print()


@app.command()
def batch(
    file: str = typer.Argument(..., help="File with one query per line (plain text)"),
    threshold: float = typer.Option(0.7, "--threshold", "-t", help="Confidence threshold (0-1)"),
    batch_size: int = typer.Option(32, "--batch-size", "-b", help="Batch size for inference"),
):
    """Classify multiple queries from a text file (one per line).

    Examples:
        python classify_cli.py batch queries.txt
        python classify_cli.py batch queries.txt --threshold 0.5 --batch-size 16
    """
    file_path = Path(file)

    if not file_path.exists():
        console.print(f"[red]Error:[/red] File not found: {file}", style="bold red")
        raise typer.Exit(1)

    # Read queries
    with open(file_path) as f:
        queries = [line.strip() for line in f if line.strip()]

    if not queries:
        console.print(f"[red]Error:[/red] No queries found in file", style="bold red")
        raise typer.Exit(1)

    console.print(f"\n[bold blue]Processing {len(queries)} queries from:[/bold blue] {file}")
    console.print(f"[dim]Threshold: {threshold} | Batch size: {batch_size}[/dim]\n")

    # Classify batch
    start = time.perf_counter()
    results = classify_batch(queries, threshold=threshold, batch_size=batch_size)
    total_time = (time.perf_counter() - start) * 1000

    # Display results
    table = Table(title=f"Batch Results ({len(queries)} queries)")
    table.add_column("#", style="dim", width=4)
    table.add_column("Query", style="cyan", max_width=50)
    table.add_column("Domain", style="green", width=12)
    table.add_column("Confidence", style="yellow", justify="right", width=10)

    for i, (query, result) in enumerate(zip(queries, results), 1):
        query_short = query[:47] + "..." if len(query) > 50 else query
        conf_str = f"{result.confidence * 100:.1f}%"
        table.add_row(str(i), query_short, result.primary, conf_str)

    console.print(table)

    # Summary
    console.print(f"\n[bold]Summary:[/bold]")
    console.print(f"  Total queries: {len(queries)}")
    console.print(f"  Total time: {total_time:.2f}ms")
    console.print(f"  Per query: {total_time / len(queries):.2f}ms")
    console.print(f"  Throughput: {len(queries) / (total_time / 1000):.1f} req/s\n")

    # Domain distribution
    domain_counts = {}
    for result in results:
        domain_counts[result.primary] = domain_counts.get(result.primary, 0) + 1

    console.print("[bold]Domain Distribution:[/bold]")
    for domain, count in sorted(domain_counts.items(), key=lambda x: x[1], reverse=True):
        percentage = (count / len(queries)) * 100
        console.print(f"  • {domain}: {count} ({percentage:.1f}%)")

    console.print()


@app.command()
def interactive(
    threshold: float = typer.Option(0.7, "--threshold", "-t", help="Confidence threshold (0-1)"),
):
    """Interactive mode for testing queries.

    Examples:
        python classify_cli.py interactive
        python classify_cli.py interactive --threshold 0.5
    """
    console.print(f"\n[bold blue]Denes Router Classifier v{__version__}[/bold blue]")
    console.print(f"[dim]Threshold: {threshold} | Type 'exit' or 'quit' to stop[/dim]\n")

    # Pre-load model
    console.print("[dim]Loading model...[/dim]", end="")
    start = time.perf_counter()
    classify_domain("test", threshold=threshold)  # Warm-up
    load_time = (time.perf_counter() - start) * 1000
    console.print(f" [green]✓[/green] ({load_time:.0f}ms)\n")

    while True:
        try:
            # Get input
            query = console.input("[bold cyan]Query:[/bold cyan] ")

            if not query or query.strip() in ["exit", "quit", "q"]:
                console.print("\n[dim]Goodbye![/dim]\n")
                break

            # Classify
            start = time.perf_counter()
            result = classify_domain(query, threshold=threshold)
            latency = (time.perf_counter() - start) * 1000

            # Display result
            conf_pct = result.confidence * 100
            console.print(
                f"  → [bold green]{result.primary}[/bold green] "
                f"([yellow]{conf_pct:.1f}%[/yellow], {latency:.1f}ms)"
            )

            if result.includes_generic:
                console.print("  [dim]⚠️  Low confidence - consider Generic fallback[/dim]")

            console.print()

        except KeyboardInterrupt:
            console.print("\n\n[dim]Interrupted. Goodbye![/dim]\n")
            break
        except Exception as e:
            console.print(f"\n[red]Error:[/red] {e}\n")


@app.command()
def version():
    """Show package version and model info."""
    from denes_router_classifier.model_loader import get_model_path

    console.print(f"\n[bold]Denes Router Classifier[/bold]")
    console.print(f"Version: {__version__}")

    model_path = get_model_path()
    if model_path.exists():
        model_size = sum(f.stat().st_size for f in model_path.rglob("*") if f.is_file())
        console.print(f"Model path: {model_path}")
        console.print(f"Model size: {model_size / (1024**2):.1f} MB")
    else:
        console.print(f"[red]Model not found at:[/red] {model_path}")

    console.print()


if __name__ == "__main__":
    app()
