"""Dark-theme HTML + Markdown renderer for the weekly digest report."""
from __future__ import annotations

from datetime import datetime, timezone

from agentkit_cli import __version__
from agentkit_cli.weekly_digest_engine import DigestReport


_CSS = """\
* { 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: 960px;
    margin: 0 auto;
    background: #161b22;
    border: 1px solid #30363d;
    border-radius: 8px;
    padding: 2rem;
}
h1 { font-size: 1.6rem; color: #58a6ff; margin-bottom: 0.25rem; }
.subtitle { font-size: 0.85rem; color: #8b949e; margin-bottom: 1.5rem; }
.summary {
    display: flex; gap: 1.5rem; margin-bottom: 1.5rem;
    padding: 1rem; background: #0d1117;
    border-radius: 6px; border: 1px solid #21262d;
}
.stat { text-align: center; flex: 1; }
.stat-value { font-size: 2rem; font-weight: bold; color: #58a6ff; }
.stat-label { font-size: 0.75rem; color: #8b949e; margin-top: 0.25rem; }
table { width: 100%; border-collapse: collapse; margin-bottom: 1.5rem; font-size: 0.88rem; }
th { text-align: left; color: #8b949e; padding: 0.5rem 0.75rem; border-bottom: 1px solid #30363d; }
td { padding: 0.5rem 0.75rem; border-bottom: 1px solid #21262d; vertical-align: top; }
.repo-name { font-weight: bold; color: #e6edf3; }
.score-high { color: #3fb950; font-weight: bold; }
.score-mid  { color: #d29922; }
.score-low  { color: #f85149; }
.grade-badge {
    display: inline-block;
    padding: 0.15rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: bold;
    background: #21262d;
    color: #58a6ff;
    border: 1px solid #30363d;
}
.footer {
    font-size: 0.75rem; color: #8b949e; text-align: center; margin-top: 1rem;
    padding-top: 1rem; border-top: 1px solid #21262d;
}
.footer a { color: #58a6ff; text-decoration: none; }
.cta {
    text-align: center; margin: 1.5rem 0;
    padding: 0.75rem; background: #0d1117;
    border: 1px solid #30363d; border-radius: 6px; font-size: 0.85rem; color: #8b949e;
}
.cta code { color: #58a6ff; }
.top-scorer { color: #58a6ff; }
"""


def _score_class(score: float) -> str:
    if score >= 80:
        return "score-high"
    if score >= 60:
        return "score-mid"
    return "score-low"


def _week_of_str(generated_at: str) -> str:
    """Return 'Month D, YYYY' from ISO timestamp."""
    try:
        dt = datetime.fromisoformat(generated_at.replace("Z", "+00:00"))
    except Exception:
        dt = datetime.now(timezone.utc)
    return dt.strftime("%B %-d, %Y")


def render_html(report: DigestReport) -> str:
    """Return full HTML string for the digest report."""
    week_of = _week_of_str(report.generated_at)
    stats = report.week_stats

    # Hero header
    header = 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 — Week of {week_of}</title>
<style>{_CSS}</style>
</head>
<body>
<div class="card">
<h1>State of AI Agent Readiness</h1>
<div class="subtitle">Week of {week_of} &mdash; generated by agentkit-cli v{__version__}</div>
"""

    # Week stats section
    total = stats.get("total_analyses", 0)
    avg = stats.get("avg_score", 0.0)
    top_scorer = stats.get("top_scorer", "")
    avg_display = f"{avg:.1f}" if total else "N/A"
    top_display = f'<span class="top-scorer">{top_scorer}</span>' if top_scorer else "N/A"

    stats_section = f"""<div class="summary">
  <div class="stat">
    <div class="stat-value">{total}</div>
    <div class="stat-label">Analyses This Week</div>
  </div>
  <div class="stat">
    <div class="stat-value">{avg_display}</div>
    <div class="stat-label">Avg Score</div>
  </div>
  <div class="stat">
    <div class="stat-value">{top_display}</div>
    <div class="stat-label">Top Scorer</div>
  </div>
</div>
"""

    # Top repos table
    rows_html = ""
    for i, repo_info in enumerate(report.top_repos, 1):
        repo = repo_info.get("repo", "")
        score = repo_info.get("score", 0.0)
        grade = repo_info.get("grade", "")
        sc = _score_class(float(score))
        rows_html += f"""<tr>
  <td class="repo-name">{repo}</td>
  <td class="{sc}">{score}</td>
  <td><span class="grade-badge">{grade}</span></td>
</tr>
"""

    table = f"""<table>
<thead><tr><th>Repository</th><th>Score</th><th>Grade</th></tr></thead>
<tbody>
{rows_html}</tbody>
</table>
"""

    # CTA footer
    cta = """<div class="cta">Install: <code>pip install agentkit-cli</code> &mdash; run <code>agentkit weekly-digest</code></div>
"""

    footer = f"""<div class="footer">
  Generated {week_of} &mdash; <a href="https://pypi.org/project/agentkit-cli/">agentkit-cli v{__version__}</a>
</div>
</div>
</body>
</html>
"""

    return header + stats_section + table + cta + footer


def render_markdown(report: DigestReport) -> str:
    """Return a markdown summary of the digest report."""
    week_of = _week_of_str(report.generated_at)
    stats = report.week_stats
    total = stats.get("total_analyses", 0)
    avg = stats.get("avg_score", 0.0)
    top_scorer = stats.get("top_scorer", "")

    lines = [
        f"## State of AI Agent Readiness — Week of {week_of}",
        "",
        f"**Analyses this week:** {total}  ",
        f"**Average score:** {avg:.1f}  ",
        f"**Top scorer:** {top_scorer or 'N/A'}",
        "",
        "### Top Repositories",
        "",
        "| Repository | Score | Grade |",
        "|------------|-------|-------|",
    ]
    for repo_info in report.top_repos:
        repo = repo_info.get("repo", "")
        score = repo_info.get("score", 0.0)
        grade = repo_info.get("grade", "")
        lines.append(f"| {repo} | {score} | {grade} |")

    lines += [
        "",
        "---",
        "_Install: `pip install agentkit-cli` | Run: `agentkit weekly-digest`_",
    ]
    return "\n".join(lines)
