import os
import json
import argparse
import re
from jinja2 import Template

def slugify(text):
    """Converts job titles into clean lowercase url slugs"""
    if not text:
        return ""
    text = text.lower()
    text = re.sub(re.compile(r'[^a-z0-9\s-]'), '', text)
    text = re.sub(re.compile(r'[\s-]+'), '-', text)
    return text.strip('-')

def load_jobs_from_json(json_file):
    """Reads the ndjson file and gets the latest jobs."""
    job_list = []
    if not os.path.exists(json_file):
        print(f"Error: {json_file} not found.")
        return job_list

    with open(json_file, 'r', encoding='utf-8') as f:
        for line in f:
            try:
                job_list.append(json.loads(line))
            except:
                continue
    return job_list[::-1]

def main(json_file, output_dir):
    all_jobs = load_jobs_from_json(json_file)
    selected_jobs = all_jobs[:60] # Show latest 60
    
    # 1. Scan your actual server folder to see exactly what files exist
    job_folder = os.path.join(output_dir, "job")
    existing_html_files = []
    if os.path.exists(job_folder):
        existing_html_files = [f for f in os.listdir(job_folder) if f.endswith('.html')]

    # 2. Match each job listing to its real filename on the server
    for job in selected_jobs:
        job_title_slug = slugify(job.get('title', ''))
        matched_slug = ""
        
        # Look for the file that starts with this title slug
        for file_name in existing_html_files:
            clean_file_base = file_name.replace('.html', '')
            if clean_file_base.startswith(job_title_slug) or job_title_slug in clean_file_base:
                matched_slug = clean_file_base
                break
        
        # Fallback if a perfect match isn't found in the directory scan
        if not matched_slug:
            job_id = job.get('id', 'job')
            matched_slug = f"{job_title_slug}-{job_id}" if job_title_slug else str(job_id)
            
        job['clean_url'] = matched_slug

    template_home = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <meta name="google-site-verification" content="w23B7WrErgi3PM93GoCpZuc70FCth4M6GN1upzlaGI8" />
    
    <title>JobHoga | Find Your Next Remote Job</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #4f46e5;
            --dark: #111827;
            --bg: #fcfcfd;
            --text-gray: #6b7280;
            --border: #f1f5f9;
        }
        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background: var(--bg);
            color: var(--dark);
            margin: 0;
            padding: 0;
            line-height: 1.5;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        header {
            background: white;
            border-bottom: 1px solid var(--border);
            padding: 20px 5%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .logo {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--dark);
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .logo span { color: var(--primary); }
        
        .hero {
            padding: 60px 5% 15px;
            text-align: center;
            max-width: 800px;
            margin: 0 auto;
        }
        .hero h1 {
            font-size: 3.5rem;
            font-weight: 800;
            margin-bottom: 20px;
            letter-spacing: -0.02em;
            line-height: 1.1;
        }
        .hero p {
            font-size: 1.25rem;
            color: var(--text-gray);
            margin-bottom: 20px;
        }
        
        /* Premium Ad Placement Styling */
        .ad-container {
            max-width: 800px;
            margin: 15px auto;
            padding: 0 20px;
            text-align: center;
            box-sizing: border-box;
            width: 100%;
        }
        .ad-wrapper {
            background: white;
            border: 1px dashed #cbd5e1;
            border-radius: 12px;
            padding: 12px;
            display: inline-block;
            width: 100%;
            max-width: 492px;
            box-sizing: border-box;
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.01);
        }
        .ad-label {
            font-size: 10px;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 6px;
            font-weight: 600;
        }

        /* Horizontal Category Filters Row */
        .category-filters {
            display: flex;
            gap: 10px;
            margin: 10px auto 35px;
            max-width: 800px;
            padding: 0 20px;
            overflow-x: auto;
            white-space: nowrap;
            box-sizing: border-box;
        }
        .category-filters::-webkit-scrollbar {
            display: none;
        }
        .category-badge {
            background: white;
            color: var(--dark);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            text-decoration: none;
            border: 1px solid var(--border);
            transition: all 0.2s ease-in-out;
        }
        .category-badge:hover, .category-badge.active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto 60px;
            padding: 0 20px;
            flex: 1;
            width: 100%;
            box-sizing: border-box;
        }
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }
        .section-header h2 {
            font-size: 1.25rem;
            font-weight: 700;
        }

        .job-list {
            display: grid;
            gap: 12px;
        }
        .job-card {
            background: white;
            padding: 20px 24px;
            border-radius: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            text-decoration: none;
            border: 1px solid var(--border);
            transition: all 0.2s ease-in-out;
        }
        .job-card:hover {
            border-color: var(--primary);
            box-shadow: 0 10px 20px rgba(0,0,0,0.02);
            transform: translateY(-2px);
        }
        .job-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 4px;
        }
        .job-meta {
            font-size: 0.9rem;
            color: var(--text-gray);
            display: flex;
            gap: 12px;
            align-items: center;
        }
        .job-pill {
            background: #eff6ff;
            color: #1d4ed8;
            padding: 3px 8px;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .apply-btn {
            background: #f5f3ff;
            color: var(--primary);
            padding: 10px 18px;
            border-radius: 10px;
            font-weight: 700;
            font-size: 0.9rem;
            transition: 0.2s;
        }
        .job-card:hover .apply-btn {
            background: var(--primary);
            color: white;
        }

        footer {
            background: white;
            border-top: 1px solid var(--border);
            padding: 30px 5%;
            text-align: center;
            margin-top: auto;
        }
        .footer-links {
            margin-bottom: 15px;
            display: flex;
            justify-content: center;
            gap: 20px;
        }
        .footer-links a {
            color: var(--text-gray);
            text-decoration: none;
            font-size: 0.85rem;
            font-weight: 500;
            transition: color 0.2s;
        }
        .footer-links a:hover {
            color: var(--primary);
        }

        @media (max-width: 600px) {
            .hero h1 { font-size: 2.5rem; }
            .job-card { flex-direction: column; align-items: flex-start; gap: 15px; }
            .apply-btn { width: 100%; text-align: center; box-sizing: border-box; }
        }
    </style>
</head>
<body>
    <header>
        <a href="/" class="logo">Job<span>Hoga</span></a>
    </header>

    <div class="ad-container" style="margin-top: 25px;">
        <div class="ad-wrapper">
            <div class="ad-label">Advertisement</div>
            <script>
                atOptions = {
                    'key' : '1a3228e92dc53e303f6535c4b403ab8f',
                    'format' : 'iframe',
                    'height' : 60,
                    'width' : 468,
                    'params' : {}
                };
            </script>
            <script src="https://www.highperformanceformat.com/1a3228e92dc53e303f6535c4b403ab8f/invoke.js"></script>
        </div>
    </div>

    <section class="hero">
        <h1>Find your next cozy remote job.</h1>
        <p>A curated list of the best work-from-home opportunities in tech, support, and more.</p>
    </section>

    <div class="category-filters">
        <a href="/" class="category-badge active">✨ All Jobs</a>
        <a href="#" class="category-badge">💻 Tech & Dev</a>
        <a href="#" class="category-badge">🎧 Customer Support</a>
        <a href="#" class="category-badge">📈 Marketing & Sales</a>
        <a href="#" class="category-badge">⚙️ Operations</a>
    </div>

    <main class="container">
        <div class="section-header">
            <h2>Latest opportunities</h2>
        </div>
        
        <div class="job-list">
            {% for job in jobs %}
            <a href="/job/{{ job.clean_url }}" class="job-card">
                <div>
                    <div class="job-title">{{ job.title }}</div>
                    <div class="job-meta">
                        <span>🏢 {{ job.company_name or 'Remote Company' }}</span>
                        <span class="job-pill">🌍 Remote</span>
                    </div>
                </div>
                <div class="apply-btn">View Details</div>
            </a>
            {% endfor %}
        </div>
    </main>

    <footer>
        <div class="ad-container" style="margin-bottom: 20px;">
            <div class="ad-wrapper">
                <div class="ad-label">Advertisement</div>
                <script>
                    atOptions = {
                        'key' : '1a3228e92dc53e303f6535c4b403ab8f',
                        'format' : 'iframe',
                        'height' : 60,
                        'width' : 468,
                        'params' : {}
                    };
                </script>
                <script src="https://www.highperformanceformat.com/1a3228e92dc53e303f6535c4b403ab8f/invoke.js"></script>
            </div>
        </div>

        <div class="footer-links">
            <a href="/about.html">About Us</a>
            <a href="/privacy.html">Privacy Policy</a>
        </div>

        <p style="font-size: 0.9rem; color: var(--text-gray); margin: 0;">&copy; 2026 JobHoga. All rights reserved.</p>
    </footer>
</body>
</html>"""

    template = Template(template_home)
    rendered_html = template.render(jobs=selected_jobs)

    os.makedirs(output_dir, exist_ok=True)
    output_path = os.path.join(output_dir, "index.html")
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(rendered_html)
    
    print(f"Homepage created successfully in {output_dir}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--json_file", default="jobs.ndjson")
    parser.add_argument("--output_dir", default=".")
    args = parser.parse_args()
    main(args.json_file, args.output_dir)