"""Compare benchmark results and generate tables."""

from typing import Optional


def format_ms(value: float) -> str:
    """Format milliseconds, returns N/A if None/0."""
    if value is None or value == 0:
        return "N/A"
    return f"{value:.1f}ms"


def generate_table(results: dict, scenario: Optional[str] = None) -> str:
    """Generate a markdown comparison table from results.
    
    If scenario is None, shows all scenarios.
    """
    tools = ["browser-hybrid", "playwright", "selenium", "agent-browser"]

    if scenario:
        return _single_scenario_table(results.get(scenario, {}), scenario, tools)
    else:
        return _all_scenarios_table(results, tools)


def _single_scenario_table(scenario_results: dict, scenario_name: str, tools: list) -> str:
    """Generate table for a single scenario."""
    header = f"## {scenario_name}\n\n"
    header += "| Tool | Mean | P50 | P95 | P99 | Success |\n"
    header += "|------|------|-----|-----|-----|---------|\n"

    rows = []
    for tool in tools:
        r = scenario_results.get(tool)
        if r is None:
            rows.append(f"| {tool} | N/A | N/A | N/A | N/A | N/A |")
        else:
            success = "✅" if r["success_rate"] == 1.0 else f"{r['success_rate']:.0%}"
            rows.append(
                f"| {tool} | {format_ms(r['mean_ms'])} | "
                f"{format_ms(r['p50_ms'])} | {format_ms(r['p95_ms'])} | "
                f"{format_ms(r['p99_ms'])} | {success} |"
            )

    return header + "\n".join(rows) + "\n"


def _all_scenarios_table(all_results: dict, tools: list) -> str:
    """Generate a combined table for all scenarios."""
    header = "| Scenario | Tool | Mean | P50 | P95 | Success |\n"
    header += "|----------|------|------|-----|-----|--------|\n"

    rows = []
    for scenario_name, scenario_results in all_results.items():
        first_row = True
        for tool in tools:
            r = scenario_results.get(tool)
            if r is None:
                row = f"| {scenario_name if first_row else ''} | {tool} | N/A | N/A | N/A | N/A |"
            else:
                success = "✅" if r["success_rate"] == 1.0 else f"{r['success_rate']:.0%}"
                row = (
                    f"| {scenario_name if first_row else ''} | {tool} | "
                    f"{format_ms(r['mean_ms'])} | {format_ms(r['p50_ms'])} | "
                    f"{format_ms(r['p95_ms'])} | {success} |"
                )
            rows.append(row)
            first_row = False

    return header + "\n".join(rows) + "\n"


def speedup_table(baseline: str, results: dict) -> str:
    """Generate a speedup table relative to a baseline tool.
    
    baseline: tool name to use as reference (e.g., "playwright")
    """
    tools = ["browser-hybrid", "playwright", "selenium", "agent-browser"]

    header = f"## Speedup vs {baseline}\n\n"
    header += "| Scenario | Baseline | Competitor | Speedup |\n"
    header += "|----------|----------|------------|--------|\n"

    rows = []
    for scenario_name, scenario_results in results.items():
        base = scenario_results.get(baseline)
        if base is None or base.get("mean_ms", 0) == 0:
            continue

        base_ms = base["mean_ms"]
        for tool in tools:
            if tool == baseline:
                continue
            r = scenario_results.get(tool)
            if r is None or r.get("mean_ms", 0) == 0:
                continue
            speedup = base_ms / r["mean_ms"]
            emoji = "🚀" if speedup > 1.5 else ("🐢" if speedup < 0.67 else "≈")
            rows.append(
                f"| {scenario_name} | {tool} | {format_ms(base_ms)} | "
                f"{format_ms(r['mean_ms'])} | {speedup:.2f}x {emoji} |"
            )

    return header + "\n".join(rows) + "\n"


def generate_markdown_report(results: dict, title: str = "Browser Benchmark Results") -> str:
    """Generate a full markdown report."""
    report = f"# {title}\n\n"
    report += f"Generated: {datetime.now().isoformat()}\n\n"

    # Summary table
    report += "## Summary\n\n"
    report += generate_table(results) + "\n"

    # Speedup tables (vs each competitor)
    for baseline in ["playwright", "selenium", "agent-browser"]:
        report += speedup_table(baseline, results) + "\n"

    # Per-scenario detail
    report += "## Detailed Results\n\n"
    for scenario_name in results.keys():
        report += generate_table(results, scenario_name) + "\n"

    return report


from datetime import datetime
