#!/usr/bin/env python3
"""format-comment.py — Format coderace JSON results as a GitHub PR comment.

Usage:
    python format-comment.py --json-file .coderace/mytask-results.json \\
                             --task-name "mytask" \\
                             --output /tmp/comment.md

Reads the JSON produced by coderace and writes a markdown comment body suitable
for posting to a GitHub PR.  The output includes:
  - A summary line (winner, scores)
  - A full results table (rank, agent, score, tests, lint, time, lines)
  - A collapsible details section with raw JSON

If --json-file does not exist or is empty, writes a "no results" placeholder.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


def _status(val: bool) -> str:
    return "✅" if val else "❌"


def format_results_table(results: list[dict]) -> str:
    """Build a markdown table from a list of result dicts (from JSON)."""
    lines: list[str] = []
    lines.append("| Rank | Agent | Score | Tests | Lint | Exit | Time (s) | Lines |")
    lines.append("|------|-------|------:|:-----:|:----:|:----:|---------:|------:|")

    for entry in results:
        b = entry.get("breakdown", {})
        rank = entry.get("rank", "?")
        agent = entry.get("agent", "?")
        score = entry.get("composite_score", 0.0)
        tests = _status(b.get("tests_pass", False))
        lint = _status(b.get("lint_clean", False))
        exit_ok = _status(b.get("exit_clean", False))
        wall = b.get("wall_time", 0.0)
        lines_changed = b.get("lines_changed", 0)

        lines.append(
            f"| {rank} | `{agent}` | {score:.1f} | {tests} | {lint} | {exit_ok} |"
            f" {wall:.1f} | {lines_changed} |"
        )

    return "\n".join(lines)


def format_summary(results: list[dict], task_name: str) -> str:
    """Build a one-line summary for the top of the comment."""
    if not results:
        return f"**coderace** — `{task_name}`: no results recorded."

    winner = results[0]  # already sorted by rank in JSON
    agent = winner.get("agent", "unknown")
    score = winner.get("composite_score", 0.0)
    n = len(results)

    tests_pass = winner.get("breakdown", {}).get("tests_pass", False)
    badge = "✅" if tests_pass else "⚠️"

    return (
        f"{badge} **coderace** — `{task_name}` | "
        f"**Winner: `{agent}`** ({score:.1f} pts) | {n} agent(s) raced"
    )


def format_comment(results: list[dict], task_name: str, json_raw: str = "") -> str:
    """Produce the full markdown comment body.

    Args:
        results: Parsed list of result dicts from JSON.
        task_name: Human-readable task name for the header.
        json_raw: Raw JSON string for the details collapsible.

    Returns:
        Markdown string ready to POST to GitHub API.
    """
    if not results:
        return (
            "<!-- coderace-results -->\n"
            f"**coderace** — `{task_name}`: no results found.\n\n"
            "_Run `coderace run` locally to generate results._"
        )

    summary = format_summary(results, task_name)
    table = format_results_table(results)

    parts: list[str] = [
        "<!-- coderace-results -->",
        "",
        summary,
        "",
        "## Results",
        "",
        table,
        "",
    ]

    if json_raw:
        parts += [
            "<details>",
            "<summary>Raw JSON</summary>",
            "",
            "```json",
            json_raw.strip(),
            "```",
            "",
            "</details>",
            "",
        ]

    parts += [
        "---",
        "_Generated by [coderace](https://github.com/mikiships/coderace)_",
    ]

    return "\n".join(parts)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Format coderace JSON results as a GitHub PR comment."
    )
    parser.add_argument(
        "--json-file",
        required=True,
        help="Path to the coderace JSON results file.",
    )
    parser.add_argument(
        "--task-name",
        default="",
        help="Task name to display in the comment header.",
    )
    parser.add_argument(
        "--output",
        default="-",
        help="Output file path (default: stdout).",
    )
    args = parser.parse_args(argv)

    json_path = Path(args.json_file)
    task_name = args.task_name or json_path.stem.replace("-results", "")

    if not json_path.exists():
        comment = format_comment([], task_name)
    else:
        try:
            raw = json_path.read_text(encoding="utf-8")
            data = json.loads(raw)
            results = data.get("results", [])
            comment = format_comment(results, task_name, json_raw=raw)
        except (json.JSONDecodeError, KeyError) as exc:
            print(f"Warning: could not parse results JSON: {exc}", file=sys.stderr)
            comment = format_comment([], task_name)

    if args.output == "-":
        sys.stdout.write(comment + "\n")
    else:
        Path(args.output).write_text(comment + "\n", encoding="utf-8")

    return 0


if __name__ == "__main__":
    sys.exit(main())
