"""Generate and publish a dark-theme trending repos HTML report to here.now."""
from __future__ import annotations

import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

from agentkit_cli import __version__
from agentkit_cli.publish import (
    PublishError,
    _json_post,
    _put_file,
    _finalize,
    HERENOW_API_BASE,
)

_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: 900px;
    margin: 0 auto;
    background: #161b22;
    border: 1px solid #30363d;
    border-radius: 8px;
    padding: 2rem;
}
h1 { font-size: 1.5rem; 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; }
td a { color: #58a6ff; text-decoration: none; }
td a:hover { text-decoration: underline; }
.grade-A { color: #3fb950; font-weight: bold; }
.grade-B { color: #3fb950; }
.grade-C { color: #d29922; }
.grade-D { color: #f85149; }
.grade-F { color: #f85149; font-weight: bold; }
.grade-NA { color: #8b949e; }
.score-high { color: #3fb950; }
.score-mid  { color: #d29922; }
.score-low  { color: #f85149; }
.score-na   { color: #8b949e; }
.rank { color: #8b949e; font-weight: bold; }
.footer { font-size: 0.75rem; color: #8b949e; text-align: center; margin-top: 1rem; }
.footer a { color: #58a6ff; text-decoration: none; }
"""


def _grade_class(grade: str) -> str:
    return f"grade-{grade}" if grade in ("A", "B", "C", "D", "F") else "grade-NA"


def _score_class(score: Optional[float]) -> str:
    if score is None:
        return "score-na"
    if score >= 80:
        return "score-high"
    if score >= 60:
        return "score-mid"
    return "score-low"


def generate_html(results: list[dict]) -> str:
    """Generate dark-theme HTML ranking report.

    Parameters
    ----------
    results:
        List of dicts with keys: rank, full_name, stars, score, grade, url.
        score and grade may be None when --no-analyze was used.

    Returns
    -------
    str: Complete self-contained HTML.
    """
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    analyzed = [r for r in results if r.get("score") is not None]
    avg_score: Optional[float] = None
    top_scorer: Optional[str] = None
    if analyzed:
        avg_score = sum(r["score"] for r in analyzed) / len(analyzed)
        top_scorer = max(analyzed, key=lambda r: r["score"])["full_name"]

    rows_html = ""
    for r in results:
        score = r.get("score")
        grade = r.get("grade") or "N/A"
        score_disp = f"{int(round(score))}" if score is not None else "N/A"
        gc = _grade_class(grade)
        sc = _score_class(score)
        stars = f"{r.get('stars', 0):,}"
        full_name = r.get("full_name", "")
        url = r.get("url", f"https://github.com/{full_name}")
        rows_html += (
            f"<tr>"
            f"<td class='rank'>#{r.get('rank', '?')}</td>"
            f"<td><a href='{url}' target='_blank' rel='noopener'>{full_name}</a></td>"
            f"<td>⭐ {stars}</td>"
            f"<td class='{sc}'>{score_disp}</td>"
            f"<td class='{gc}'>{grade}</td>"
            f"</tr>\n"
        )

    # Summary cards
    repos_count = len(results)
    avg_disp = f"{avg_score:.0f}" if avg_score is not None else "N/A"
    top_disp = top_scorer or "N/A"

    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Trending Repos: Agent Quality Rankings</title>
<style>{_CSS}</style>
</head>
<body>
<div class="card">
  <h1>Trending Repos: Agent Quality Rankings</h1>
  <p class="subtitle">Generated by agentkit-cli v{__version__} | {now}</p>

  <div class="summary">
    <div class="stat">
      <div class="stat-value">{repos_count}</div>
      <div class="stat-label">Repos Analyzed</div>
    </div>
    <div class="stat">
      <div class="stat-value">{avg_disp}</div>
      <div class="stat-label">Avg Score</div>
    </div>
    <div class="stat">
      <div class="stat-value" style="font-size:1rem;padding-top:.5rem">{top_disp}</div>
      <div class="stat-label">Top Scorer</div>
    </div>
  </div>

  <table>
    <thead>
      <tr>
        <th>Rank</th>
        <th>Repo</th>
        <th>Stars</th>
        <th>Score</th>
        <th>Grade</th>
      </tr>
    </thead>
    <tbody>
{rows_html}    </tbody>
  </table>

  <div class="footer">
    <a href="https://pypi.org/project/agentkit-cli/" target="_blank" rel="noopener">agentkit-cli v{__version__}</a>
    &nbsp;|&nbsp;
    pip install agentkit-cli
  </div>
</div>
</body>
</html>
"""
    return html


def publish_report(html: str, api_key: Optional[str] = None) -> str:
    """Upload HTML to here.now using the 3-step API.

    Parameters
    ----------
    html:
        The rendered HTML string.
    api_key:
        Optional here.now API key. Falls back to HERENOW_API_KEY env var.

    Returns
    -------
    str: Live URL of the published report.

    Raises
    ------
    PublishError if any step fails.
    """
    resolved_key = api_key or os.environ.get("HERENOW_API_KEY")
    headers: dict = {}
    if resolved_key:
        headers["Authorization"] = f"Bearer {resolved_key}"

    content_bytes = html.encode("utf-8")

    # Step 1: request upload URLs (use same schema as publish.publish_html)
    publish_url = f"{HERENOW_API_BASE}/publish"
    body = {"files": [{"path": "index.html", "contentType": "text/html; charset=utf-8", "size": len(content_bytes)}]}
    resp = _json_post(publish_url, body, headers=headers)

    upload_info = resp.get("upload") or {}
    uploads: list = upload_info.get("uploads") or resp.get("uploadUrls") or []
    version_id: Optional[str] = upload_info.get("versionId") or resp.get("versionId")
    finalize_url: Optional[str] = upload_info.get("finalizeUrl") or resp.get("finalizeUrl")
    live_url: Optional[str] = resp.get("siteUrl") or resp.get("url")

    if not uploads or not finalize_url:
        raise PublishError(f"Unexpected response from here.now publish: {resp}")

    # Step 2: PUT file content
    upload = uploads[0]
    put_url = upload.get("url") or upload.get("uploadUrl")
    if not put_url:
        raise PublishError(f"No upload URL in response: {upload}")
    _put_file(put_url, content_bytes, content_type="text/html; charset=utf-8")

    # Step 3: finalize
    final_resp = _finalize(finalize_url, version_id=version_id)
    if not live_url:
        live_url = final_resp.get("url") or final_resp.get("deployUrl") or final_resp.get("siteUrl")
    if not live_url:
        raise PublishError(f"No URL in finalize response: {final_resp}")

    return live_url
