"""
Visualization utilities for evaluation results.

Provides:
- Comparison summary table
- Text-based bar charts for metrics
- Detailed query analysis view
"""
from __future__ import annotations
from .framework import ComparisonResult


def format_comparison_table(comparison: ComparisonResult) -> str:
    """
    Format comparison results as a text table.

    Example:
    | Method | Recall@10 | NDCG@10 | Answer Hit |
    |--------|-----------|---------|------------|
    | graph  | 0.850     | 0.720   | 0.900      |
    | dense  | 0.450     | 0.380   | 0.500      |
    """
    # Header
    recall_key = f"Recall@{comparison.results['graph'].k}"
    ndcg_key = f"NDCG@{comparison.results['graph'].k}"
    header = f"| {'Method':<12} | {recall_key:<10} | {ndcg_key:<8} | {'Answer Hit':<10} |"
    sep = f"|{'-'*14}|{'-'*12}|{'-'*10}|{'-'*12}|"

    lines = [sep, header, sep]

    for name, result in comparison.results.items():
        line = (
            f"| {name:<12} "
            f"| {result.recall_at_k:<10.3f} "
            f"| {result.ndcg_at_k:<8.3f} "
            f"| {result.answer_hit_rate:<10.3f} |"
        )
        lines.append(line)

    lines.append(sep)
    lines.append(f"\nWinner: {comparison.winner} (+{comparison.improvement:.1%})")

    return "\n".join(lines)


def visualize_query_analysis(comparison: ComparisonResult, query_idx: int = 0) -> str:
    """
    Show detailed breakdown for a specific query.

    Visualizes which documents were retrieved by each method for the given query.
    """
    lines = ["Query Analysis", "=" * 60]

    # Get query from first method (assuming all use same examples)
    base_result = list(comparison.results.values())[0]
    if query_idx >= len(base_result.per_example):
        return f"Error: Query index {query_idx} out of range."

    example = base_result.per_example[query_idx]
    lines.append(f"Query: {example['query']}")
    lines.append("-" * 60)

    for name, result in comparison.results.items():
        ex = result.per_example[query_idx]
        lines.append(f"\nMethod: {name}")
        lines.append(f"  Recall: {ex.get('recall', 0):.2f}")
        lines.append(f"  Retrieved: {', '.join(ex.get('retrieved', []))}")

    return "\n".join(lines)


def print_comparison(comparison: ComparisonResult):
    """Print formatted comparison table."""
    print(format_comparison_table(comparison))
