import os
from flask import Flask, render_template_string, request, send_from_directory
from scrape_remoteeng import run_english_scraper
from scrape_remotefr import run_french_scraper

app = Flask(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")
os.makedirs(DATA_DIR, exist_ok=True)

HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>Remote Jobs Scrapers</title>
    <style>
        body { font-family: sans-serif; max-width: 650px; margin: 40px auto; padding: 0 20px; }
        .btn-group { display: flex; gap: 10px; margin-bottom: 20px; }
        button { padding: 12px 18px; font-size: 15px; cursor: pointer; }
        .msg { margin: 15px 0; padding: 12px; border-radius: 5px; }
        .success { background: #e6f4ea; color: #137333; }
        .error { background: #fce8e6; color: #c5221f; }
    </style>
</head>
<body>
    <h2>Remote Jobs Scrapers (All Categories)</h2>
    <form method="POST" class="btn-group">
        <button type="submit" name="action" value="french">Scrape French Remote Jobs</button>
        <button type="submit" name="action" value="english">Scrape English Remote Jobs</button>
    </form>

    {% if message %}
        <div class="msg {{ status }}">{{ message }}</div>
    {% endif %}

    <h3>Saved CSV Files in /data:</h3>
    <ul>
    {% for file in files %}
        <li><a href="/download/{{ file }}">{{ file }}</a></li>
    {% else %}
        <li>No CSV files generated yet.</li>
    {% endfor %}
    </ul>
</body>
</html>
"""


@app.route("/", methods=["GET", "POST"])
def index():
    message = ""
    status = ""

    if request.method == "POST":
        action = request.form.get("action")
        if action == "french":
            ok, message = run_french_scraper()
            status = "success" if ok else "error"
        elif action == "english":
            ok, message = run_english_scraper()
            status = "success" if ok else "error"

    saved_files = sorted(
        [f for f in os.listdir(DATA_DIR) if f.endswith(".csv")], reverse=True
    )
    return render_template_string(
        HTML_TEMPLATE, message=message, status=status, files=saved_files
    )


@app.route("/download/<filename>")
def download_file(filename):
    return send_from_directory(DATA_DIR, filename, as_attachment=True)
