import os
import json
import argparse
import datetime
from jinja2 import Template

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
    
    # Reverse to show the newest jobs at the top
    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
    
    template_home = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rowjobs | 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;
        }
        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: 100px 5% 60px;
            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: 40px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto 100px;
            padding: 0 20px;
        }
        .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;
        }
        .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;
        }

        @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">Row<span>Jobs</span></a>
    </header>

    <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>

    <main class="container">
        <div class="section-header">
            <h2>Latest opportunities</h2>
        </div>
        
        <div class="job-list">
            {% for job in jobs %}
            <a href="/job/{{ job.slug }}" class="job-card">
                <div>
                    <div class="job-title">{{ job.title }}</div>
                    <div class="job-meta">
                        <span>🏢 {{ job.company_name }}</span>
                        <span>📍 Remote</span>
                    </div>
                </div>
                <div class="apply-btn">View Details</div>
            </a>
            {% endfor %}
        </div>
    </main>
</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)