"""agentkit search — HTML report generation and share support."""
from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional

from agentkit_cli import __version__
from agentkit_cli.search import SearchResult

_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.4rem; color: #58a6ff; margin-bottom: 0.25rem; }
.ref { font-size: 0.85rem; color: #8b949e; margin-bottom: 1.5rem; }
.hero {
    display: flex;
    gap: 2rem;
    padding: 1.5rem 0;
    margin-bottom: 1.5rem;
    border-top: 1px solid #30363d;
    border-bottom: 1px solid #30363d;
    align-items: center;
}
.badge {
    background: #f85149;
    color: #fff;
    border-radius: 6px;
    padding: 0.4rem 0.8rem;
    font-size: 2rem;
    font-weight: bold;
    min-width: 80px;
    text-align: center;
}
.badge-label { font-size: 0.85rem; color: #8b949e; margin-top: 0.25rem; }
.badge-green { background: #3fb950; }
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; }
a { color: #58a6ff; text-decoration: none; }
a:hover { text-decoration: underline; }
.missing { color: #f85149; }
.present { color: #3fb950; }
.footer { font-size: 0.75rem; color: #8b949e; text-align: center; margin-top: 1rem; }
.footer a { color: #58a6ff; text-decoration: none; }
.action-btn {
    background: #21262d;
    border: 1px solid #30363d;
    color: #58a6ff;
    padding: 0.2rem 0.5rem;
    border-radius: 4px;
    font-size: 0.78rem;
    font-family: monospace;
    cursor: pointer;
}
"""


def _bool_cell(val: bool) -> str:
    if val:
        return '<span class="present">✓</span>'
    return '<span class="missing">✗</span>'


def generate_search_report(
    results: List[SearchResult],
    query: str = "",
    generated_at: Optional[str] = None,
) -> str:
    """Generate dark-theme HTML report for search results."""
    if generated_at is None:
        generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

    total = len(results)
    missing_count = sum(1 for r in results if r.missing_context)
    has_both = sum(1 for r in results if r.has_claude_md and r.has_agents_md)

    rows = []
    for r in results:
        action = f"agentkit analyze github:{r.full_name}"
        rows.append(f"""
        <tr>
          <td><a href="{r.url}" target="_blank">{r.full_name}</a></td>
          <td>★ {r.stars:,}</td>
          <td>{r.language or '—'}</td>
          <td>{_bool_cell(r.has_claude_md)}</td>
          <td>{_bool_cell(r.has_agents_md)}</td>
          <td><button class="action-btn" onclick="navigator.clipboard.writeText('{action}')" title="Copy command">{action[:40]}…</button></td>
        </tr>""")

    rows_html = "\n".join(rows)
    title = f"agentkit search — {query}" if query else "agentkit search results"

    return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{title}</title>
<style>{_CSS}</style>
</head>
<body>
<div class="card">
  <h1>{title}</h1>
  <div class="ref">generated {generated_at} · agentkit-cli v{__version__}</div>
  <div class="hero">
    <div>
      <div class="badge">{missing_count}</div>
      <div class="badge-label">Missing context files</div>
    </div>
    <div>
      <div class="badge badge-green">{total - missing_count}</div>
      <div class="badge-label">Have context files</div>
    </div>
    <div style="margin-left:auto;font-size:0.9rem;color:#8b949e;">
      {total} repos scanned<br>
      {has_both} have both CLAUDE.md + AGENTS.md
    </div>
  </div>
  <table>
    <thead>
      <tr>
        <th>Repository</th>
        <th>Stars</th>
        <th>Language</th>
        <th>CLAUDE.md</th>
        <th>AGENTS.md</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
{rows_html}
    </tbody>
  </table>
  <div class="footer">
    Generated by <a href="https://pypi.org/project/agentkit-cli/">agentkit-cli</a> v{__version__} ·
    <a href="https://github.com/mikiships/agentkit-cli">GitHub</a>
  </div>
</div>
</body>
</html>"""


def upload_search_report(results: List[SearchResult], query: str = "") -> Optional[str]:
    """Generate HTML and upload to here.now. Returns URL or None."""
    try:
        from agentkit_cli.publish import (
            _json_post,
            _put_file,
            _finalize,
            HERENOW_API_BASE,
        )
        import os

        api_key = os.environ.get("HERENOW_API_KEY")
        if not api_key:
            return None

        html = generate_search_report(results, query=query)
        content = html.encode("utf-8")

        publish_resp = _json_post(
            f"{HERENOW_API_BASE}/api/v1/publish",
            {
                "files": [{"path": "index.html", "size": len(content), "content_type": "text/html"}]
            },
            api_key=api_key,
        )
        upload_url = publish_resp["files"][0]["upload_url"]
        _put_file(upload_url, content, "text/html")
        site_id = publish_resp["site_id"]
        finalize_resp = _finalize(
            f"{HERENOW_API_BASE}/api/v1/publish/{site_id}/finalize",
            api_key=api_key,
        )
        return finalize_resp.get("url")
    except Exception:
        return None
