"""Evaluation logic for running tasks."""

import json
import time
from pathlib import Path

from rich.console import Console
from rich.live import Live
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn

from mangodesk.core.runner import execute_task
from mangodesk.core.api import MangoAPIClient

console = Console()


def load_tasks(env_path: Path, task_ids: list[str] | None = None) -> tuple[str, list[dict]]:
    """Load tasks from environment directory.

    Args:
        env_path: Path to environment directory
        task_ids: Optional list of specific task IDs to run

    Returns:
        Tuple of (environment_name, list of tasks)
    """
    tasks_file = env_path / "tasks.json"

    if not tasks_file.exists():
        raise FileNotFoundError(f"No tasks.json found in {env_path}")

    with open(tasks_file) as f:
        data = json.load(f)

    env_name = data.get("environment", env_path.name)
    all_tasks = data.get("tasks", [])

    if task_ids:
        tasks = [t for t in all_tasks if t["id"] in task_ids]
        if not tasks:
            raise ValueError(f"No tasks found matching: {task_ids}")
    else:
        tasks = all_tasks

    return env_name, tasks


def create_results_table(results: list[dict], model: str) -> Table:
    """Create a rich table showing evaluation results."""
    table = Table(title=f"Evaluation Results - {model}")

    table.add_column("Task", style="cyan")
    table.add_column("Status", justify="center")
    table.add_column("Duration", justify="right")
    table.add_column("Tokens", justify="right")

    for result in results:
        status = "[green]PASS[/green]" if result["passed"] else "[red]FAIL[/red]"
        duration = f"{result['duration_ms']}ms"
        tokens = str(result["token_count"])

        table.add_row(
            result["task_id"],
            status,
            duration,
            tokens,
        )

    return table


def run_evaluation(
    env_path: Path,
    model: str,
    task_ids: list[str] | None = None,
    api_url: str | None = None,
    api_key: str | None = None,
) -> None:
    """Run evaluation on tasks and upload results.

    Args:
        env_path: Path to environment directory
        model: Model name for evaluation
        task_ids: Optional list of specific task IDs
        api_url: API URL for uploading results
        api_key: API key for authentication
    """
    console.print(f"[bold]MangoDesk Evaluation[/bold]")
    console.print(f"Environment: {env_path}")
    console.print(f"Model: {model}")
    console.print()

    # Load tasks
    try:
        env_name, tasks = load_tasks(env_path, task_ids)
    except (FileNotFoundError, ValueError) as e:
        console.print(f"[red]Error:[/red] {e}")
        raise SystemExit(1)

    console.print(f"Found {len(tasks)} task(s) to run")
    console.print()

    # Execute tasks with progress
    results = []

    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TaskProgressColumn(),
        console=console,
    ) as progress:
        task_progress = progress.add_task("Running tasks...", total=len(tasks))

        for task in tasks:
            progress.update(task_progress, description=f"Running {task['id']}...")

            result = execute_task(task, model, env_path)
            results.append(result)

            progress.advance(task_progress)

    # Show results table
    console.print()
    table = create_results_table(results, model)
    console.print(table)

    # Summary
    passed = sum(1 for r in results if r["passed"])
    total = len(results)
    pass_rate = (passed / total * 100) if total > 0 else 0

    console.print()
    if passed == total:
        console.print(f"[green bold]All {total} tasks passed![/green bold]")
    else:
        console.print(f"[yellow]{passed}/{total} passed ({pass_rate:.1f}%)[/yellow]")

    # Upload results
    if api_key and api_url:
        console.print()
        console.print("Uploading results...")

        client = MangoAPIClient(api_url, api_key)

        # Prepare rollouts for upload
        rollouts = []
        for result in results:
            # Find the original task to get the prompt
            task = next((t for t in tasks if t["id"] == result["task_id"]), None)
            rollouts.append({
                "task_id": result["task_id"],
                "prompt": task["prompt"] if task else "",
                "trace": result["trace"],
                "passed": result["passed"],
                "score": result["score"],
                "duration_ms": result["duration_ms"],
                "token_count": result["token_count"],
                "failure_reason": result["failure_reason"],
            })

        try:
            response = client.create_run(
                environment_name=env_name,
                model=model,
                rollouts=rollouts,
            )
            dashboard_url = f"{api_url}{response['dashboard_url']}"
            console.print(f"[green]Uploaded![/green]")
            console.print()
            console.print(f"[bold]View results:[/bold] {dashboard_url}")
        except Exception as e:
            console.print(f"[red]Failed to upload:[/red] {e}")
    else:
        console.print()
        console.print("[dim]Results not uploaded (no API key configured)[/dim]")
