#!/usr/bin/env python3
"""
GitHub Trending - Landing Page Generator
Reads collected JSON data, generates daily HTML landing page + home index.
"""
import json, re, sys, os
from pathlib import Path

LANDING_DIR = os.path.expanduser("~/.hermes/landing")
os.makedirs(LANDING_DIR, exist_ok=True)

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

def extract_readme_info(readme_text, description, language, topics):
    """Extract structured info from README text."""
    info = {
        'problem': description,
        'advantages': [],
        'category': categorize_repo(description, language, readme_text, topics),
    }
    if not readme_text:
        return info

    # Extract better problem statement from README
    # Try to get the first meaningful paragraph after the title
    lines = readme_text.split('\n')
    clean_lines = []
    for line in lines:
        stripped = line.strip()
        if stripped and not stripped.startswith('#') and not stripped.startswith('!') and not stripped.startswith('[') and not stripped.startswith('<!--'):
            if len(stripped) > 40:  # meaningful paragraph
                clean_lines.append(stripped)

    if clean_lines:
        info['problem'] = clean_lines[0]

    # Extract advantages/features from README
    advantages = []
    in_features = False
    for line in lines:
        stripped = line.strip()
        # Detect feature sections
        if re.match(r'^##+\s*(Key )?Features|Why\s|Benefits|Capabilities|What.*(do|can)|Highlights', stripped, re.IGNORECASE):
            in_features = True
            continue
        if in_features:
            if stripped.startswith('##') and not stripped.startswith('###'):
                in_features = False
                continue
            # Extract bullet points
            bullet = re.sub(r'^[\s]*[-*•]\s*', '', stripped)
            if bullet and len(bullet) > 15 and not bullet.startswith('#'):
                advantages.append(bullet[:200])  # limit length

    info['advantages'] = advantages[:5]  # max 5 advantages
    return info

def categorize_repo(description, language, readme_text, topics):
    """Categorize a repository based on all available info."""
    text = (description + ' ' + (readme_text or '') + ' ' + ' '.join(topics)).lower()

    categories = [
        ('🤖 Inteligência Artificial / ML', [
            'machine learning', 'artificial intelligence', 'deep learning', 'ai ', 'llm', 'gpt',
            'neural network', 'transformer', 'nlp', 'computer vision', 'tensorflow', 'pytorch',
            'model', 'inference', 'rag', 'agent', 'autonomous', 'chatbot', 'openai', 'claude'
        ]),
        ('🛠️ Ferramentas para Dev', [
            'developer tool', 'cli', 'command line', 'terminal', 'debugger', 'profiler',
            'code quality', 'lint', 'formatter', 'git', 'github', 'ci/cd', 'automation',
            'api', 'sdk', 'framework', 'library', 'package', 'plugin', 'extension'
        ]),
        ('⚙️ Infraestrutura & DevOps', [
            'kubernetes', 'docker', 'container', 'orchestration', 'deployment', 'serverless',
            'cloud', 'infrastructure', 'monitoring', 'observability', 'prometheus', 'grafana',
            'terraform', 'ansible', 'devops', 'database', 'cache', 'message queue', 'proxy',
            'reverse proxy', 'load balancer', 'networking'
        ]),
        ('🎨 Frontend & UI', [
            'react', 'vue', 'angular', 'svelte', 'ui ', 'component', 'frontend', 'css',
            'tailwind', 'bootstrap', 'design system', 'web', 'browser', 'dashboard',
            'visualization', 'chart', 'animation', 'responsive'
        ]),
        ('🔒 Segurança & Privacidade', [
            'security', 'privacy', 'encryption', 'authentication', 'authorization',
            'vulnerability', 'penetration', 'firewall', 'cryptography', 'ssl', 'tls',
            'zero trust', 'secret', 'compliance'
        ]),
        ('🎵 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', 'nosql', 'big data',
            'data science', 'statistics', 'visualization', 'report', 'dashboard',
            'spreadsheet', 'csv'
        ]),
    ]

    scores = []
    for cat_name, keywords in categories:
        score = sum(1 for kw in keywords if kw in text)
        if score > 0:
            scores.append((score, cat_name))

    scores.sort(reverse=True)
    if scores:
        return scores[0][1]
    return '📦 Outro'

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

def generate_daily_page(data, daily_path):
    """Generate the daily landing page with enhanced cards."""
    repos = data['repos']
    date_label = data['date']

    cards = []
    for r in repos:
        info = extract_readme_info(
            r.get('readme', ''),
            r.get('description', ''),
            r.get('language', ''),
            r.get('topics', [])
        )

        advantages_html = ''
        if info['advantages']:
            adv_items = ''.join(f'<li>{esc(a)}</li>' for a in info['advantages'])
            advantages_html = f'<div class="advantages"><strong>🌟 Vantagens:</strong><ul>{adv_items}</ul></div>'

        stars_fmt = format_stars(r.get('stars', 0))
        lang_cls = re.sub(r'[^a-z0-9]', '', r['language'].lower())[:12] or 'outro'

        cards.append(f'''
    <div class="card">
      <div class="rank">#{r['rank']}</div>
      <div class="card-header">
        <h3><a href="{r['url']}" target="_blank" rel="noopener">{esc(r['name'])}</a></h3>
        <span class="stars-count">⭐ {stars_fmt}</span>
      </div>
      <div class="card-body">
        <div class="meta-row">
          <span class="tag">{esc(r['language'])}</span>
          <span class="category">{esc(info['category'])}</span>
        </div>
        <div class="section">
          <strong>📋 Problema que resolve:</strong>
          <p>{esc(info['problem'])}</p>
        </div>
        {advantages_html}
      </div>
    </div>''')

    html = f'''<!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_label}</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}}
h1{{font-size:1.8rem;margin-bottom:.3rem;color:#58a6ff}}
.sub{{color:#8b949e;margin-bottom:1.5rem;font-size:.9rem}}
.nav-top{{margin-bottom:1.5rem}}
.nav-top a{{color:#58a6ff;text-decoration:none;font-size:.9rem}}
.nav-top a:hover{{text-decoration:underline}}
.grid{{display:grid;gap:1.2rem}}
.card{{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:1.2rem;position:relative;transition:border-color .2s,border-width .1s}}
.card:hover{{border-color:#58a6ff;border-width:1.5px}}
.rank{{position:absolute;top:.6rem;right:.8rem;font-size:.75rem;color:#484f58;font-weight:600}}
.card-header{{margin-bottom:.6rem;padding-right:1.8rem}}
.card-header h3{{font-size:1.1rem;display:inline}}
.card-header h3 a{{color:#58a6ff;text-decoration:none}}
.card-header h3 a:hover{{text-decoration:underline}}
.stars-count{{display:inline-block;margin-left:.6rem;font-size:.85rem;color:#d29922;font-weight:500}}
.card-body{{font-size:.85rem;line-height:1.5}}
.meta-row{{display:flex;flex-wrap:wrap;gap:.4rem;margin-bottom:.8rem;align-items:center}}
.tag{{background:#1f2937;color:#c9d1d9;padding:.15rem .5rem;border-radius:12px;font-size:.75rem}}
.category{{background:#0d419d;color:#58a6ff;padding:.15rem .5rem;border-radius:12px;font-size:.75rem}}
.section{{margin-bottom:.6rem}}
.section strong{{color:#f0f6fc;display:block;margin-bottom:.2rem}}
.section p{{color:#8b949e}}
.advantages{{margin-top:.6rem}}
.advantages strong{{color:#f0f6fc;display:block;margin-bottom:.2rem}}
.advantages ul{{margin:.2rem 0 0 1.2rem;color:#8b949e}}
.advantages li{{margin-bottom:.15rem}}
.footer{{margin-top:1.5rem;padding-top:.8rem;border-top:1px solid #21262d;color:#484f58;text-align:center;font-size:.8rem}}
.footer a{{color:#484f58}}
</style>
</head>
<body>
<div class="nav-top"><a href="index.html">← Home</a></div>
<h1>🔥 GitHub Trending — {date_label}</h1>
<p class="sub">Análise dos 20 repositórios mais populares do dia</p>
<div class="grid">{"".join(cards)}</div>
<div class="footer">Gerado por Hermes Agent · <a href="https://github.com/trending">github.com/trending</a></div>
</body>
</html>'''

    Path(daily_path).write_text(html, encoding='utf-8')
    return repos

def generate_index(landing_dir, today_date):
    """Generate index.html with links to all daily pages."""
    html_files = sorted(Path(landing_dir).glob('2*.html'))
    
    links = []
    for f in html_files:
        date_str = f.stem  # e.g., "2026-07-23"
        if date_str == 'index':
            continue
        links.append(f'        <li><a href="{f.name}">📅 {date_str}</a></li>')

    links_html = '\n'.join(links) if links else '        <li class="empty">Nenhum relatório disponível ainda.</li>'

    index_html = f'''<!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 — Home</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:3rem 1.5rem}}
h1{{font-size:2rem;margin-bottom:.5rem;color:#58a6ff}}
.sub{{color:#8b949e;font-size:1rem;margin-bottom:2rem}}
.desc{{color:#8b949e;font-size:.9rem;margin-bottom:2rem;line-height:1.6}}
.report-list{{list-style:none;padding:0}}
.report-list li{{margin:.5rem 0}}
.report-list a{{color:#58a6ff;text-decoration:none;font-size:1.05rem;display:inline-block;padding:.4rem .8rem;background:#161b22;border:1px solid #30363d;border-radius:6px;transition:border-color .2s}}
.report-list a:hover{{border-color:#58a6ff}}
.empty{{color:#484f58;font-style:italic}}
.footer{{margin-top:2rem;padding-top:1rem;border-top:1px solid #21262d;color:#484f58;text-align:center;font-size:.8rem}}
</style>
</head>
<body>
<h1>📈 GitHub Trending — Arquivo Histórico</h1>
<p class="sub">Relatórios diários dos repositórios em alta no GitHub</p>
<p class="desc">Cada relatório contém análise dos 20 repositórios mais populares com resumo do README, categorização, vantagens e links diretos.</p>
<ul class="report-list">
{links_html}
</ul>
<div class="footer">Gerado por Hermes Agent · <a href="https://github.com/trending">github.com/trending</a></div>
</body>
</html>'''

    Path(landing_dir / 'index.html').write_text(index_html, encoding='utf-8')

def main():
    json_path = sys.argv[1] if len(sys.argv) > 1 else None
    if not json_path or not os.path.exists(json_path):
        print("❌ JSON path required. Usage: generate_landing.py <json_path>")
        sys.exit(1)

    with open(json_path) as f:
        data = json.load(f)

    today = data['date']
    daily_file = os.path.join(LANDING_DIR, f"{today}.html")
    
    print(f"📄 Generating daily page: {daily_file}")
    repos = generate_daily_page(data, daily_file)
    
    print(f"🏠 Updating index.html")
    generate_index(Path(LANDING_DIR), today)
    
    # Output summary for Telegram delivery
    print(f"\n{'='*60}")
    print(f"🔥 GitHub Trending Diário — {today}")
    print(f"{'='*60}")
    for r in repos:
        stars_fmt = format_stars(r.get('stars', 0))
        info = extract_readme_info(
            r.get('readme', ''),
            r.get('description', ''),
            r.get('language', ''),
            r.get('topics', [])
        )
        print(f"\n#{r['rank']} {r['name']}")
        print(f"   🛠️  {r['language']}  |  ⭐ {stars_fmt}  |  {info['category']}")
        print(f"   📋 {r.get('description', 'Sem descrição.')[:120]}")
        if info['advantages']:
            print(f"   🌟 {info['advantages'][0][:100]}")
        print(f"   🔗 {r['url']}")
    
    print(f"\n🌐 Landing page: {daily_file}")
    print(f"🏠 Home: {os.path.join(LANDING_DIR, 'index.html')}")

if __name__ == '__main__':
    main()
