"""agentkit ecosystem HTML report renderer — dark-theme State of AI Agent Readiness."""
from __future__ import annotations

from datetime import datetime, timezone
from typing import Optional

from agentkit_cli import __version__
from agentkit_cli.engines.ecosystem import EcosystemResult, LANG_EMOJI
from agentkit_cli.engines.topic_league import LeagueResult

# ---------------------------------------------------------------------------
# Grade colors
# ---------------------------------------------------------------------------

_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:
    if max_score <= 0:
        return 0
    return max(0, min(100, int(score / max_score * 100)))


def _score_bar_color(score: float) -> str:
    """Color-code bar green→yellow→red based on score."""
    if score >= 70:
        return "#3fb950"
    if score >= 45:
        return "#d29922"
    return "#f85149"


# ---------------------------------------------------------------------------
# EcosystemHTMLRenderer
# ---------------------------------------------------------------------------


class EcosystemHTMLRenderer:
    """Render a dark-theme HTML 'State of the Ecosystem' report for an EcosystemResult."""

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

        year = datetime.now(timezone.utc).year
        standings_rows = self._render_standings_rows(result.standings)
        detail_cards = self._render_detail_cards(result)
        winner_banner = self._render_winner_banner(result)
        insight_panel = self._render_insight_panel(result)

        preset_label = result.preset.title()
        n_topics = len(result.standings)

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

  <div class="page-header">
    <h1>🌐 State of AI Agent Readiness</h1>
    <p class="subtitle">{year} Edition &bull; {preset_label} preset &bull; {n_topics} ecosystems &bull; {timestamp}</p>
  </div>

{winner_banner}

  <div class="section-header">Standings</div>
  <table class="standings-table">
    <thead>
      <tr>
        <th style="width:50px">Rank</th>
        <th>Ecosystem</th>
        <th style="text-align:right;width:140px">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-Ecosystem Detail</div>
  <div class="detail-grid">
{detail_cards}
  </div>

{insight_panel}

  <div class="footer">
    Generated by
    <a href="https://github.com/mikiships/agentkit-cli">agentkit-cli v{__version__}</a>
    &bull; {timestamp}
    &bull; Scores based on GitHub public API data
    {self._token_notice()}
  </div>

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

    def _token_notice(self) -> str:
        return '<br><span class="token-notice">Set GITHUB_TOKEN for higher rate limits and more accurate results.</span>'

    def _render_winner_banner(self, result: EcosystemResult) -> str:
        if not result.winner:
            return ""
        w = result.winner
        gc = _grade_color(w.grade)
        emoji = LANG_EMOJI.get(w.topic, "🔷")
        bar_w = _score_bar_width(w.score)
        return f"""  <div class="winner-banner">
    <div class="winner-label">🏆 Winner</div>
    <div class="winner-name">{emoji} {w.topic}</div>
    <div class="winner-score" style="color:{gc}">{w.score:.1f} / 100</div>
    <span class="grade-pill winner-grade" style="color:{gc};border-color:{gc}">{w.grade}</span>
    <div class="winner-bar-wrap">
      <div class="winner-bar" style="width:{bar_w}%;background:{gc}"></div>
    </div>
    <div class="winner-sub">{w.repo_count} repos analyzed &bull; top: <a href="https://github.com/{w.top_repo}" target="_blank">{w.top_repo}</a></div>
  </div>
"""

    def _render_standings_rows(self, standings: list) -> 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_color = _score_bar_color(s.score)
            bar_width = _score_bar_width(s.score)
            emoji = LANG_EMOJI.get(s.topic, "🔷")
            rows += f"""      <tr>
        <td class="rank-cell">{rank_display}</td>
        <td class="topic-cell"><strong>{emoji} {s.topic}</strong></td>
        <td class="score-cell">
          <div class="score-bar-wrap">
            <div class="score-bar" style="width:{bar_width}%;background:{bar_color}"></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: EcosystemResult) -> str:
        cards = ""
        for standing in result.standings:
            topic = standing.topic
            topic_result = result.league_result.topic_results.get(topic)
            if not topic_result:
                continue
            gc = _grade_color(standing.grade)
            dist = standing.score_distribution
            emoji = LANG_EMOJI.get(topic, "🔷")

            repo_rows = ""
            for entry in topic_result.entries[:3]:
                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">{emoji} {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 _render_insight_panel(self, result: EcosystemResult) -> str:
        if len(result.standings) < 2:
            return ""
        standings = result.standings
        top = standings[0]
        bottom = standings[-1]
        spread = round(top.score - bottom.score, 1)

        # "Closest to Agent-Ready" — highest score
        closest = top

        # "Most Improved" placeholder — widest score spread as signal
        insight_note = (
            f"Score spread of {spread} points between {top.topic} "
            f"({top.score:.1f}) and {bottom.topic} ({bottom.score:.1f})."
        )

        return f"""  <div class="section-header">Insights</div>
  <div class="insight-panel">
    <div class="insight-item">
      <div class="insight-title">🚀 Closest to Agent-Ready</div>
      <div class="insight-body">
        <strong>{LANG_EMOJI.get(closest.topic, '🔷')} {closest.topic}</strong> 
        leads with a mean score of <strong>{closest.score:.1f}</strong> (grade {closest.grade}).
        Ecosystem tooling and documentation appear most mature for AI agent integration.
      </div>
    </div>
    <div class="insight-item">
      <div class="insight-title">📊 Score Spread</div>
      <div class="insight-body">{insight_note} Wide spread suggests significant variation in AI-agent readiness across ecosystems.</div>
    </div>
    <div class="insight-item">
      <div class="insight-title">📈 Most Improved (placeholder)</div>
      <div class="insight-body">Historical comparison requires multiple scans. Run <code>agentkit ecosystem</code> periodically to track trends.</div>
    </div>
  </div>
"""


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; font-size: 0.9rem; }
.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;
}
/* Winner banner */
.winner-banner {
    background: linear-gradient(135deg, #161b22 0%, #0d1117 100%);
    border: 1px solid #3fb950;
    border-radius: 8px;
    padding: 1.5rem 2rem;
    text-align: center;
    margin-bottom: 1.5rem;
}
.winner-label { font-size: 0.8rem; text-transform: uppercase; color: #8b949e; letter-spacing: 0.1em; margin-bottom: 0.5rem; }
.winner-name { font-size: 2rem; font-weight: bold; color: #e6edf3; margin-bottom: 0.5rem; }
.winner-score { font-size: 1.5rem; font-weight: bold; margin-bottom: 0.5rem; }
.winner-grade { font-size: 1rem; padding: 0.2rem 0.75rem; }
.winner-bar-wrap { width: 60%; margin: 0.75rem auto 0.5rem; height: 8px; background: #21262d; border-radius: 4px; overflow: hidden; }
.winner-bar { height: 100%; border-radius: 4px; transition: width 0.3s; }
.winner-sub { font-size: 0.8rem; color: #8b949e; margin-top: 0.5rem; }
.winner-sub a { color: #58a6ff; text-decoration: none; }
/* 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: 140px; }
.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 { 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; }
/* Insight panel */
.insight-panel {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1rem;
    margin-top: 0.5rem;
}
.insight-item {
    background: #0d1117;
    border: 1px solid #30363d;
    border-radius: 6px;
    padding: 1rem;
}
.insight-title { font-size: 0.85rem; font-weight: bold; color: #e6edf3; margin-bottom: 0.5rem; }
.insight-body { font-size: 0.8rem; color: #8b949e; line-height: 1.5; }
.insight-body strong { color: #e6edf3; }
.insight-body code { background: #21262d; padding: 0.1rem 0.3rem; border-radius: 3px; font-size: 0.75rem; }
/* 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; }
.token-notice { font-size: 0.7rem; color: #6e7681; }
"""
