"""
Report Generator
================
Generates a shareable Markdown Agent Card from local EvalMonkey run history.

Usage:
    evalmonkey report [--output evalmonkey_report.md] [--agent-name "My Agent"]
"""
from __future__ import annotations

import os
from collections import defaultdict
from datetime import datetime, timezone
from typing import Optional

from evalmonkey.reporting.history import get_history, calculate_production_reliability


def _badge_color(score: int) -> str:
    if score >= 80:
        return "brightgreen"
    elif score >= 60:
        return "yellow"
    else:
        return "red"


def _badge_url(score: int) -> str:
    """Generate a shields.io badge URL for the given overall score."""
    color = _badge_color(score)
    label = f"Score%3A{score}"
    return f"https://img.shields.io/badge/EvalMonkey-{label}-{color}"


def generate_report(
    output_path: str = "evalmonkey_report.md",
    agent_name: str = "My Agent",
) -> str:
    """
    Reads ~/.evalmonkey/history.json, aggregates the latest baseline and chaos
    scores per scenario, and writes a Markdown report to output_path.

    Returns the full Markdown content as a string.
    """
    history = get_history()

    # Group: scenario → { baseline: int|None, chaos: int|None }
    scores: dict[str, dict[str, Optional[int]]] = defaultdict(lambda: {"baseline": None, "chaos": None})

    for record in history:
        scenario = record.get("scenario", "unknown")
        run_type = record.get("run_type", "")
        score = record.get("score")
        if run_type == "baseline" and score is not None:
            scores[scenario]["baseline"] = score
        elif run_type == "chaos" and score is not None:
            scores[scenario]["chaos"] = score

    # Overall score = average of all latest baseline scores
    baseline_scores = [v["baseline"] for v in scores.values() if v["baseline"] is not None]
    overall_score = int(sum(baseline_scores) / len(baseline_scores)) if baseline_scores else 0
    badge_url = _badge_url(overall_score)

    now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")

    lines: list[str] = [
        f"# Agent Benchmark Report — {agent_name}",
        "",
        f"[![EvalMonkey Score]({badge_url})](https://github.com/Corbell-AI/evalmonkey)",
        "",
        f"> Generated by [EvalMonkey](https://github.com/Corbell-AI/evalmonkey) on {now_str}",
        "",
        "## Benchmark Scores",
        "",
        "| Scenario | Baseline | Chaos | Production Reliability |",
        "|----------|:--------:|:-----:|:----------------------:|",
    ]

    for scenario in sorted(scores.keys()):
        s = scores[scenario]
        baseline = s["baseline"]
        chaos = s["chaos"]
        reliability = calculate_production_reliability(scenario)

        b_str = f"**{baseline}**" if baseline is not None else "—"
        c_str = str(chaos) if chaos is not None else "—"
        r_str = f"{reliability:.1f}" if reliability else "—"
        lines.append(f"| `{scenario}` | {b_str} | {c_str} | {r_str} |")

    if not scores:
        lines.append("| *(no runs recorded yet)* | — | — | — |")

    lines += [
        "",
        "## What is Production Reliability?",
        "",
        "Production Reliability = `(baseline_score × 0.6) + (chaos_score × 0.4)`",
        "",
        "It combines how well your agent performs on clean inputs with how resilient it is",
        "under adversarial conditions (typos, prompt injection, schema mutations, etc.).",
        "",
        "---",
        "",
        f"*Embed this badge in your README:*",
        f"```markdown",
        f"[![EvalMonkey Score]({badge_url})](https://github.com/Corbell-AI/evalmonkey)",
        f"```",
    ]

    content = "\n".join(lines)

    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(content)

    return content
