#!/usr/bin/env python3
"""
Enhanced Landing Page Template — Reference for LLM-enriched card generation.

This file documents the HTML card pattern that Phase 2 (LLM enrichment)
produces. It is NOT meant to be executed directly — it's a structural
reference for agents rewriting ~/.hermes/landing/YYYY-MM-DD.html.

Pattern: vertical stack of cards, each containing:
  - Rank badge (absolute positioned top-left)
  - Header: repo name as link + star count badge
  - Meta badges: language tag, category tag
  - Problem section ("🎯 Problema que resolve" — full sentence)
  - Advantages section ("🌟 Vantagens" — 3-5 bullet points)
  - Footer: "Ver no GitHub →" link

The file is regenerated each day; index.html is updated separately.
"""

import re


CARD_HTML_TEMPLATE = '''
    <div class="card" data-rank="{rank}">
      <div class="rank-badge">#{rank}</div>
      <div class="card-content">
        <div class="card-header">
          <h3><a href="{url}" target="_blank" rel="noopener">{name}</a></h3>
          <div class="meta-badges">
            <span class="tag lang-{lang_slug}">{language}</span>
            <span class="tag stars">⭐ {stars_formatted}</span>
            <span class="tag category-tag">{category_label}</span>
          </div>
        </div>
        <div class="card-body">
          <div class="section problem-section">
            <strong>🎯 Problema que resolve</strong>
            <p>{problem}</p>
          </div>
          <div class="advantages">
            <strong>🌟 Vantagens</strong>
            <ul>
              {advantages_items}
            </ul>
          </div>
        </div>
        <div class="card-footer">
          <a href="{url}" target="_blank" rel="noopener" class="repo-link">Ver no GitHub →</a>
        </div>
      </div>
    </div>'''

PAGE_HTML_TEMPLATE = '''<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GitHub Trending — {date}</title>
<style>
*{{margin:0;padding:0;box-sizing:border-box}}
body{{background:#0d1117;color:#c9d1d9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;padding:2rem 1rem;min-height:100vh;position:relative}}
body::before{{content:'';position:fixed;top:0;left:0;right:0;height:4px;background:linear-gradient(90deg,#58a6ff,#3fb950,#f0883e,#bc8cff);z-index:100}}
.container{{max-width:860px;margin:0 auto}}
h1{{font-size:1.8rem;margin-bottom:.2rem;color:#f0f6fc;display:flex;align-items:center;gap:.5rem}}
.date-badge{{display:inline-block;font-size:.8rem;color:#8b949e;background:#21262d;padding:.15rem .6rem;border-radius:12px;margin-left:.5rem}}
.sub{{color:#8b949e;margin-bottom:.5rem;font-size:.9rem}}
.stats-line{{color:#484f58;font-size:.8rem;margin-bottom:1.5rem;display:flex;gap:1rem;flex-wrap:wrap}}
.stats-line span{{background:#161b22;padding:.15rem .6rem;border-radius:10px}}
.nav-top{{margin-bottom:1.2rem}}
.nav-top a{{color:#58a6ff;text-decoration:none;font-size:.85rem}}
.nav-top a:hover{{text-decoration:underline}}
.grid{{display:flex;flex-direction:column;gap:1rem}}
.card{{background:#161b22;border:1px solid #30363d;border-radius:10px;overflow:hidden;transition:all .2s ease;position:relative}}
.card:hover{{border-color:#58a6ff;transform:translateY(-2px);box-shadow:0 4px 12px rgba(88,166,255,.1)}}
.rank-badge{{position:absolute;top:0;left:0;background:linear-gradient(135deg,#1f2937,#161b22);color:#8b949e;font-size:.7rem;font-weight:600;padding:.3rem .7rem;border-radius:0 0 8px 0;border-right:1px solid #30363d;border-bottom:1px solid #30363d;letter-spacing:.5px;z-index:1}}
.card-content{{padding:1rem 1.2rem .8rem 1.2rem}}
.card-header{{margin-bottom:.6rem;padding-top:.2rem}}
.card-header h3{{font-size:1.05rem;margin-bottom:.4rem}}
.card-header h3 a{{color:#58a6ff;text-decoration:none;font-weight:500}}
.card-header h3 a:hover{{text-decoration:underline;color:#79c0ff}}
.meta-badges{{display:flex;flex-wrap:wrap;gap:.35rem;align-items:center}}
.tag{{display:inline-block;font-size:.7rem;padding:.1rem .5rem;border-radius:10px;background:#21262d;color:#8b949e}}
.stars{{background:#2d1f00;color:#d29922;font-weight:500}}
.category-tag{{background:#0d419d;color:#58a6ff}}
.card-body{{font-size:.83rem;line-height:1.55}}
.section{{margin-bottom:.5rem}}
.section strong{{color:#f0f6fc;display:block;margin-bottom:.15rem;font-size:.78rem;text-transform:uppercase;letter-spacing:.3px}}
.section p{{color:#8b949e}}
.problem-section p{{color:#c9d1d9}}
.advantages{{margin-top:.5rem;padding-top:.5rem;border-top:1px solid #21262d}}
.advantages ul{{list-style:none;padding:0;margin:.3rem 0 0 0}}
.advantages li{{color:#8b949e;padding:.2rem 0 .2rem 1.2rem;position:relative;font-size:.8rem}}
.advantages li::before{{content:'▸';position:absolute;left:0;color:#3fb950}}
.card-footer{{margin-top:.5rem;padding-top:.4rem;border-top:1px solid #21262d;text-align:right}}
.repo-link{{color:#484f58;text-decoration:none;font-size:.75rem;transition:color .15s}}
.repo-link:hover{{color:#58a6ff}}
.footer{{margin-top:1.5rem;padding-top:.8rem;border-top:1px solid #21262d;color:#484f58;text-align:center;font-size:.78rem;line-height:1.6}}
.footer a{{color:#484f58}}
.footer a:hover{{color:#8b949e}}
.source-link{{display:inline-block;background:#21262d;color:#58a6ff!important;padding:.2rem .7rem;border-radius:8px;font-size:.75rem;text-decoration:none;margin-top:.3rem}}
.source-link:hover{{background:#1f2937}}
@media(max-width:600px){{.card-content{{padding:.8rem}}h1{{font-size:1.4rem}}}}
</style>
</head>
<body>
<div class="container">
<div class="nav-top"><a href="index.html">← Arquivo Histórico</a></div>
<h1><span>🔥</span> GitHub Trending <span class="date-badge">{date}</span></h1>
<p class="sub">Análise aprimorada por IA dos 20 repositórios mais populares do dia</p>
<div class="stats-line">
<span>📦 20 repositórios</span>
<span>📊 Análise via README</span>
<span>🤖 Aprimorado por Hermes Agent</span>
</div>
<div class="grid">
{cards}
</div>
<div class="footer">
Gerado por Hermes Agent em {date}<br>
<a href="https://github.com/trending" class="source-link">📈 Fonte: GitHub Trending</a>
</div>
</div>
</body>
</html>'''

# ── Helpers ──────────────────────────────────────────────────────────

def esc(s: str) -> str:
    """HTML-escape a string."""
    return str(s).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;')


def format_stars(n) -> str:
    """Format star count with commas (e.g. 70260 → '70,260')."""
    if isinstance(n, str):
        n = int(n.replace(',', ''))
    return f"{n:,}"


def lang_slug(language: str) -> str:
    """Normalize language name into a CSS-safe class."""
    return re.sub(r'[^a-z0-9]', '-', language.lower())[:15] or 'outro'


def strip_html(text: str) -> str:
    """Remove HTML tags and collapse whitespace."""
    clean = re.sub(r'<[^>]+>', ' ', text)
    return re.sub(r'\s+', ' ', clean).strip()


# ── Card builders ────────────────────────────────────────────────────

def build_card(rank: int, name: str, url: str, language: str,
               stars: int, problem: str, advantages: list[str],
               category_label: str) -> str:
    """Generate a single enhanced card HTML block.

    All content args (problem, advantages, category_label) should be
    LLM-extracted clean text — not raw README fragments.
    """
    adv_items = ''.join(f'<li>{esc(a)}</li>' for a in advantages[:5])
    stars_fmt = format_stars(stars)
    return CARD_HTML_TEMPLATE.format(
        rank=rank,
        name=esc(name),
        url=url,
        language=esc(language),
        lang_slug=lang_slug(language),
        stars_formatted=stars_fmt,
        category_label=esc(category_label),
        problem=esc(problem),
        advantages_items=adv_items,
    )


def build_page(date: str, cards_html: str) -> str:
    """Wrap cards in the full HTML page including header, nav, footer."""
    return PAGE_HTML_TEMPLATE.format(date=date, cards=cards_html)


# ── Base README analysis (override in Phase 2 with LLM) ──────────────

def analyze_readme(readme_text: str, trending_description: str) -> tuple[str, list[str], str]:
    """Default heuristic analysis of a README.

    Returns (problem, advantages_list, category_string).
    
    NOTE: This heuristic is unreliable for HTML-rich READMEs.
    Override in Phase 2 (LLM enrichment) for quality results.
    See: phase-2-llm-enrichment in github-trending-reporting SKILL.md.
    """
    clean = strip_html(readme_text)
    lines = clean.split('\n')

    # Problem: first non-header paragraph >40 chars, or fallback to trending description
    problem = trending_description
    for line in lines:
        s = line.strip()
        if s and not s.startswith('#') and not s.startswith('[') and not s.startswith('<!--') and len(s) > 40:
            problem = s[:200]
            break

    # Advantages: bullet points under feature-like sections
    advantages = []
    in_features = False
    for line in lines:
        s = line.strip()
        if re.match(r'^##+\s*(Key )?Features|Why\s|Benefits|Capabilities', s, re.IGNORECASE):
            in_features = True
            continue
        if in_features:
            if s.startswith('##') and not s.startswith('###'):
                in_features = False
                continue
            bullet = re.sub(r'^[\s]*[-*•]\s*', '', s)
            if bullet and len(bullet) > 15 and not bullet.startswith('#'):
                advantages.append(bullet[:200])

    return problem, advantages[:5], _categorize(clean + ' ' + trending_description)


def _categorize(text: str) -> str:
    """Keyword-based category assignment.

    Common misclassifications to watch for in Phase 2:
      - 'Apollo-11' (historical/education) → wrongly tagged 'Mídia & Criativo'
      - 'awesome-*' lists → wrongly tagged 'Frontend & UI' or 'Ferramentas Dev'
      - 'croc' (networking tool) → wrongly tagged 'Ferramentas Dev' (should be Infra)
    """
    t = text.lower()
    cats = [
        ('🤖 Inteligência Artificial / ML', ['machine learning', 'artificial intelligence', 'deep learning', 'ai ',
                                              'llm', 'gpt', 'neural', 'transformer', 'nlp', 'computer vision',
                                              'model', 'inference', 'rag', 'agent', 'autonomous', 'chatbot']),
        ('🛠️ Ferramentas Dev', ['developer tool', 'cli', 'command line', 'terminal', 'debug', 'profiler',
                                  'code quality', 'lint', 'formatter', 'git', 'api', 'sdk', 'framework',
                                  'library', 'package', 'plugin', 'extension']),
        ('⚙️ Infraestrutura & DevOps', ['kubernetes', 'docker', 'container', 'orchestration', 'deployment',
                                         'serverless', 'cloud', 'monitoring', 'observability', 'terraform',
                                         'ansible', 'devops', 'database', 'cache', 'proxy', 'load balancer',
                                         'networking', 'message queue']),
        ('🎨 Frontend & UI', ['react', 'vue', 'angular', 'svelte', 'ui ', 'component', 'frontend', 'css',
                              'tailwind', 'bootstrap', 'design system', 'dashboard', 'visualization', 'chart',
                              'animation', 'responsive']),
        ('🔒 Segurança & Privacidade', ['security', 'privacy', 'encryption', 'authentication', 'authorization',
                                         'vulnerability', 'firewall', 'cryptography', 'zero trust', 'secret']),
        ('🎵 Mídia & Criativo', ['audio', 'video', 'music', 'voice', 'speech', 'tts', 'stt', 'image',
                                 'generation', 'render', '3d', 'animation', 'creative', 'design', 'photo',
                                 'editing', 'stream']),
        ('📚 Educação & Referência', ['tutorial', 'learn', 'course', 'documentation', 'wiki', 'knowledge base',
                                      'reference', 'awesome', 'list', 'curated', 'resource', 'guide', 'handbook']),
        ('📊 Dados & Análise', ['data', 'analytics', 'etl', 'pipeline', 'sql', 'big data', 'data science',
                                'statistics', 'spreadsheet', 'csv']),
    ]
    scored = [(sum(1 for kw in kws if kw in t), name) for name, kws in cats]
    scored = [(s, n) for s, n in scored if s > 0]
    scored.sort(reverse=True)
    return scored[0][1] if scored else '📦 Outro'
