#!/usr/bin/env python3
"""
Generate an HTML candidate review page from the latest CSV.
Outputs to /var/www/drafts-preview/candidates.html
"""

import csv
import sys
from datetime import datetime, timezone
from pathlib import Path

CSV_PATH = Path(__file__).parent / "output" / f"candidates_{datetime.now(timezone.utc).strftime('%Y-%m-%d')}.csv"
OUT_PATH = Path("/var/www/drafts-preview/candidates.html")


def score_color(score: float) -> str:
    if score >= 0.8:
        return "#16a34a"  # green
    elif score >= 0.6:
        return "#ca8a04"  # yellow
    else:
        return "#6b7280"  # gray


def escape(text: str) -> str:
    return (text or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")


def main():
    if not CSV_PATH.exists():
        print(f"CSV not found: {CSV_PATH}", file=sys.stderr)
        sys.exit(1)

    with open(CSV_PATH) as f:
        rows = list(csv.DictReader(f))

    today = datetime.now(timezone.utc).strftime("%Y-%m-%d")

    cards = []
    for i, r in enumerate(rows, 1):
        score = float(r.get("score", 0))
        color = score_color(score)
        name = escape(r.get("name", "Unknown"))
        title = escape(r.get("current_title", ""))
        company = escape(r.get("current_company", ""))
        location = escape(r.get("location", ""))
        url = escape(r.get("profile_url", ""))
        work = escape(r.get("work_history", ""))
        desc = escape(r.get("profile_description", ""))

        # Truncate description for card view
        desc_short = desc[:300] + "..." if len(desc) > 300 else desc

        cards.append(f"""
    <div class="card" data-score="{score}" data-name="{name.lower()}">
      <div class="card-header">
        <span class="rank">#{i}</span>
        <span class="score" style="background:{color}">{score:.2f}</span>
        <h3>{name}</h3>
      </div>
      <div class="card-body">
        <p class="title">{title}</p>
        <p class="company">{company}</p>
        <p class="location">📍 {location or '—'}</p>
        {'<p class="desc">' + desc_short + '</p>' if desc_short else ''}
        {'<details><summary>Work History</summary><p class="work">' + work.replace(' | ', '<br>') + '</p></details>' if work else ''}
        <a href="{url}" target="_blank" rel="noopener" class="profile-link">View LinkedIn Profile →</a>
      </div>
    </div>""")

    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>OpenTrack Co. — Sales Engineer Candidates ({today})</title>
  <style>
    * {{ margin: 0; padding: 0; box-sizing: border-box; }}
    body {{
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #f8fafc;
      color: #1e293b;
      padding: 20px;
      max-width: 1400px;
      margin: 0 auto;
    }}
    h1 {{
      font-size: 1.5rem;
      margin-bottom: 4px;
    }}
    .subtitle {{
      color: #64748b;
      font-size: 0.9rem;
      margin-bottom: 20px;
    }}
    .controls {{
      display: flex;
      gap: 12px;
      margin-bottom: 20px;
      flex-wrap: wrap;
    }}
    .controls input {{
      padding: 8px 12px;
      border: 1px solid #cbd5e1;
      border-radius: 8px;
      font-size: 0.9rem;
      flex: 1;
      min-width: 200px;
    }}
    .controls select {{
      padding: 8px 12px;
      border: 1px solid #cbd5e1;
      border-radius: 8px;
      font-size: 0.9rem;
      background: white;
    }}
    .grid {{
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
      gap: 16px;
    }}
    .card {{
      background: white;
      border: 1px solid #e2e8f0;
      border-radius: 12px;
      overflow: hidden;
      transition: box-shadow 0.2s;
    }}
    .card:hover {{
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    }}
    .card-header {{
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 12px 16px;
      border-bottom: 1px solid #f1f5f9;
    }}
    .rank {{
      color: #94a3b8;
      font-weight: 600;
      font-size: 0.85rem;
      min-width: 28px;
    }}
    .score {{
      color: white;
      font-weight: 700;
      font-size: 0.8rem;
      padding: 3px 8px;
      border-radius: 6px;
      min-width: 36px;
      text-align: center;
    }}
    .card-header h3 {{
      font-size: 1rem;
      font-weight: 600;
    }}
    .card-body {{
      padding: 12px 16px;
    }}
    .title {{
      font-weight: 500;
      color: #334155;
      font-size: 0.92rem;
      margin-bottom: 2px;
    }}
    .company {{
      color: #64748b;
      font-size: 0.88rem;
      margin-bottom: 6px;
    }}
    .location {{
      color: #64748b;
      font-size: 0.82rem;
      margin-bottom: 8px;
    }}
    .desc {{
      font-size: 0.85rem;
      color: #475569;
      line-height: 1.4;
      margin-bottom: 8px;
    }}
    details {{
      margin-bottom: 10px;
    }}
    details summary {{
      cursor: pointer;
      font-size: 0.82rem;
      color: #3b82f6;
      font-weight: 500;
    }}
    .work {{
      font-size: 0.8rem;
      color: #64748b;
      margin-top: 6px;
      line-height: 1.5;
    }}
    .profile-link {{
      display: inline-block;
      color: #2563eb;
      text-decoration: none;
      font-size: 0.85rem;
      font-weight: 500;
    }}
    .profile-link:hover {{
      text-decoration: underline;
    }}
    .footer {{
      margin-top: 24px;
      text-align: center;
      color: #94a3b8;
      font-size: 0.8rem;
    }}
  </style>
</head>
<body>
  <h1>OpenTrack Co. — Sales Engineer Candidates</h1>
  <p class="subtitle">{len(rows)} candidates sourced and ranked on {today}</p>

  <div class="controls">
    <input type="text" id="search" placeholder="Filter by name, title, company..." oninput="filterCards()">
    <select id="sortby" onchange="sortCards()">
      <option value="score">Sort by score</option>
      <option value="name">Sort by name</option>
    </select>
  </div>

  <div class="grid" id="grid">
    {''.join(cards)}
  </div>

  <div class="footer">
    Generated by OpenTrack candidate sourcing pipeline · <a href="https://drafts.multiplyme.co/">← Back to drafts</a>
  </div>

  <script>
    function filterCards() {{
      const q = document.getElementById('search').value.toLowerCase();
      document.querySelectorAll('.card').forEach(c => {{
        const text = c.textContent.toLowerCase();
        c.style.display = text.includes(q) ? '' : 'none';
      }});
    }}

    function sortCards() {{
      const grid = document.getElementById('grid');
      const cards = Array.from(grid.querySelectorAll('.card'));
      const mode = document.getElementById('sortby').value;
      cards.sort((a, b) => {{
        if (mode === 'score') {{
          return parseFloat(b.dataset.score) - parseFloat(a.dataset.score);
        }} else {{
          return a.dataset.name.localeCompare(b.dataset.name);
        }}
      }});
      cards.forEach(c => grid.appendChild(c));
    }}
  </script>
</body>
</html>"""

    OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    with open(OUT_PATH, "w") as f:
        f.write(html)

    print(f"Written {len(rows)} candidates to {OUT_PATH}")


if __name__ == "__main__":
    main()
