"""agentkit topic-league HTML report renderer — dark-theme multi-topic standings."""
from __future__ import annotations

from datetime import datetime, timezone
from typing import Optional

from agentkit_cli import __version__
from agentkit_cli.engines.topic_league import TopicLeagueResult, LeagueResult

# ---------------------------------------------------------------------------
# Grade colors (consistent with topic_rank_html / topic_duel_html)
# ---------------------------------------------------------------------------

_GRADE_COLORS = {
    "A": "#3fb950",
    "B": "#58a6ff",
    "C": "#d29922",
    "D": "#f85149",
    "F": "#f85149",
}


def _grade_color(grade: str) -> str:
    return _GRADE_COLORS.get(grade, "#8b949e")


def _score_bar_width(score: float, max_score: float = 100.0) -> int:
    """Return percentage width (0-100) for score bar."""
    if max_score <= 0:
        return 0
    return max(0, min(100, int(score / max_score * 100)))


# ---------------------------------------------------------------------------
# TopicLeagueHTMLRenderer
# ---------------------------------------------------------------------------


class TopicLeagueHTMLRenderer:
    """Render a dark-theme HTML standings report for a TopicLeagueResult."""

    def render(
        self,
        result: TopicLeagueResult,
        timestamp: Optional[str] = None,
    ) -> str:
        if timestamp is None:
            timestamp = result.timestamp or datetime.now(timezone.utc).strftime(
                "%Y-%m-%d %H:%M UTC"
            )

        standings_rows = self._render_standings_rows(result.standings)
        detail_cards = self._render_detail_cards(result)

        title = "Topic League: " + " · ".join(result.topics)

        return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>{_css()}</style>
</head>
<body>
<div class="card">

  <div class="page-header">
    <h1>🏆 Topic League</h1>
    <p class="subtitle">Agent-readiness standings for {len(result.topics)} topics</p>
    <p class="topics-list">{" &bull; ".join(f"<span class='topic-tag'>{t}</span>" for t in result.topics)}</p>
  </div>

  <div class="section-header">Standings</div>
  <table class="standings-table">
    <thead>
      <tr>
        <th style="width:50px">Rank</th>
        <th>Topic</th>
        <th style="text-align:right;width:130px">Avg Score</th>
        <th style="text-align:center;width:60px">Grade</th>
        <th style="text-align:right;width:70px">Repos</th>
        <th>Top Repo</th>
      </tr>
    </thead>
    <tbody>
{standings_rows}
    </tbody>
  </table>

  <div class="section-header">Per-Topic Detail</div>
  <div class="detail-grid">
{detail_cards}
  </div>

  <div class="footer">
    Generated by
    <a href="https://github.com/mikiships/agentkit-cli">agentkit-cli v{__version__}</a>
    &bull; {timestamp}
  </div>

</div>
</body>
</html>"""

    def _render_standings_rows(self, standings: list[LeagueResult]) -> str:
        rows = ""
        for s in standings:
            rank_display = "🥇" if s.rank == 1 else ("🥈" if s.rank == 2 else ("🥉" if s.rank == 3 else str(s.rank)))
            gc = _grade_color(s.grade)
            bar_width = _score_bar_width(s.score)
            rows += f"""      <tr>
        <td class="rank-cell">{rank_display}</td>
        <td class="topic-cell"><strong>{s.topic}</strong></td>
        <td class="score-cell">
          <div class="score-bar-wrap">
            <div class="score-bar" style="width:{bar_width}%;background:{gc}"></div>
            <span class="score-num" style="color:{gc}">{s.score:.1f}</span>
          </div>
        </td>
        <td class="grade-cell">
          <span class="grade-pill" style="color:{gc};border-color:{gc}">{s.grade}</span>
        </td>
        <td class="repos-cell">{s.repo_count}</td>
        <td class="top-repo-cell"><a href="https://github.com/{s.top_repo}" target="_blank">{s.top_repo}</a></td>
      </tr>
"""
        return rows

    def _render_detail_cards(self, result: TopicLeagueResult) -> str:
        cards = ""
        for standing in result.standings:
            topic = standing.topic
            topic_result = result.topic_results.get(topic)
            if not topic_result:
                continue
            gc = _grade_color(standing.grade)
            dist = standing.score_distribution

            repo_rows = ""
            for entry in topic_result.entries[:5]:
                ec = _grade_color(entry.grade)
                repo_rows += f"""          <tr>
            <td class="rank-cell">{entry.rank}</td>
            <td><a href="https://github.com/{entry.repo_full_name}" target="_blank">{entry.repo_full_name}</a></td>
            <td style="text-align:right;color:{ec}">{entry.score:.1f}</td>
            <td style="text-align:center"><span class="grade-pill" style="color:{ec};border-color:{ec}">{entry.grade}</span></td>
            <td style="text-align:right;color:#8b949e">⭐ {entry.stars:,}</td>
          </tr>
"""

            cards += f"""    <div class="detail-card">
      <div class="detail-card-header">
        <span class="detail-rank">#{standing.rank}</span>
        <span class="detail-topic">{topic}</span>
        <span class="detail-score" style="color:{gc}">{standing.score:.1f}</span>
        <span class="grade-pill" style="color:{gc};border-color:{gc}">{standing.grade}</span>
      </div>
      <div class="dist-row">
        <span class="dist-label">min</span><span class="dist-val">{dist.min_score:.1f}</span>
        <span class="dist-label">mean</span><span class="dist-val" style="color:{gc}">{dist.mean_score:.1f}</span>
        <span class="dist-label">max</span><span class="dist-val">{dist.max_score:.1f}</span>
      </div>
      <table class="repo-table">
        <thead><tr><th>#</th><th>Repo</th><th style="text-align:right">Score</th><th style="text-align:center">Grade</th><th style="text-align:right">Stars</th></tr></thead>
        <tbody>
{repo_rows}        </tbody>
      </table>
    </div>
"""
        return cards


def _css() -> str:
    return """
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    background: #0d1117;
    color: #e6edf3;
    font-family: 'Courier New', Courier, monospace;
    min-height: 100vh;
    padding: 2rem;
}
.card {
    max-width: 1100px;
    margin: 0 auto;
    background: #161b22;
    border: 1px solid #30363d;
    border-radius: 8px;
    padding: 2rem;
}
.page-header {
    text-align: center;
    margin-bottom: 2rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid #30363d;
}
.page-header h1 { font-size: 2rem; color: #e6edf3; margin-bottom: 0.5rem; }
.subtitle { color: #8b949e; margin-bottom: 0.75rem; }
.topics-list { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center; }
.topic-tag {
    background: #21262d;
    border: 1px solid #30363d;
    border-radius: 12px;
    padding: 0.2rem 0.75rem;
    font-size: 0.85rem;
    color: #58a6ff;
}
.section-header {
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: #8b949e;
    border-bottom: 1px solid #30363d;
    padding-bottom: 0.4rem;
    margin-bottom: 0.75rem;
    margin-top: 1.5rem;
}
/* Standings table */
.standings-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 0.5rem;
}
.standings-table th {
    text-align: left;
    font-size: 0.72rem;
    color: #8b949e;
    padding: 0.35rem 0.5rem;
    border-bottom: 1px solid #30363d;
}
.standings-table td {
    padding: 0.6rem 0.5rem;
    border-bottom: 1px solid #21262d;
    vertical-align: middle;
    font-size: 0.85rem;
}
.rank-cell { color: #8b949e; text-align: center; }
.topic-cell { font-size: 0.95rem; }
.score-cell { width: 130px; }
.score-bar-wrap { display: flex; align-items: center; gap: 0.5rem; }
.score-bar { height: 6px; border-radius: 3px; min-width: 4px; }
.score-num { font-weight: bold; white-space: nowrap; }
.grade-cell { text-align: center; }
.grade-pill {
    display: inline-block;
    border: 1px solid;
    border-radius: 4px;
    padding: 0.1rem 0.45rem;
    font-size: 0.75rem;
    font-weight: bold;
}
.repos-cell { text-align: right; color: #8b949e; }
.top-repo-cell a { color: #58a6ff; text-decoration: none; font-size: 0.8rem; }
.top-repo-cell a:hover { text-decoration: underline; }
/* Detail grid */
.detail-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 1rem;
    margin-top: 0.5rem;
}
.detail-card {
    background: #0d1117;
    border: 1px solid #30363d;
    border-radius: 6px;
    padding: 1rem;
}
.detail-card-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 0.6rem;
}
.detail-rank { color: #8b949e; font-size: 0.85rem; }
.detail-topic { font-size: 1.1rem; font-weight: bold; flex: 1; color: #58a6ff; }
.detail-score { font-size: 1.2rem; font-weight: bold; }
.dist-row {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 0.75rem;
    font-size: 0.78rem;
    color: #8b949e;
}
.dist-label { color: #8b949e; }
.dist-val { color: #e6edf3; font-weight: bold; margin-right: 0.5rem; }
/* Repo table in cards */
.repo-table {
    width: 100%;
    border-collapse: collapse;
}
.repo-table th {
    font-size: 0.68rem;
    color: #8b949e;
    padding: 0.25rem 0.3rem;
    border-bottom: 1px solid #30363d;
    text-align: left;
}
.repo-table td {
    padding: 0.3rem 0.3rem;
    border-bottom: 1px solid #21262d;
    font-size: 0.78rem;
    vertical-align: middle;
}
.repo-table a { color: #58a6ff; text-decoration: none; }
.repo-table a:hover { text-decoration: underline; }
/* Footer */
.footer {
    font-size: 0.75rem;
    color: #8b949e;
    text-align: center;
    margin-top: 2rem;
    padding-top: 1rem;
    border-top: 1px solid #30363d;
}
.footer a { color: #58a6ff; text-decoration: none; }
"""
