from pathlib import Path
import shutil
import subprocess
import uuid
import zipfile

from flask import Flask, render_template, request, send_file, abort

BASE_DIR = Path(__file__).resolve().parent
UPLOAD_DIR = BASE_DIR / "uploads"
OUTPUT_DIR = BASE_DIR / "web_output"

UPLOAD_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)

app = Flask(__name__)


@app.get("/")
def index():
    return render_template("upload.html")


@app.post("/generate")
def generate():
    job_id = uuid.uuid4().hex
    job_dir = UPLOAD_DIR / job_id
    images_dir = job_dir / "images"
    job_dir.mkdir(parents=True)
    images_dir.mkdir(parents=True)

    csv_file = request.files.get("csv_file")
    if not csv_file or not csv_file.filename:
        return "Chybí CSV soubor", 400

    csv_path = job_dir / "catalog.csv"
    csv_file.save(csv_path)

    for image in request.files.getlist("images"):
        if image and image.filename:
            image.save(images_dir / Path(image.filename).name)

    zip_file = request.files.get("images_zip")
    if zip_file and zip_file.filename:
        zip_path = job_dir / "images.zip"
        zip_file.save(zip_path)
        with zipfile.ZipFile(zip_path, "r") as z:
            z.extractall(images_dir)

    output_pdf = OUTPUT_DIR / f"catalog_{job_id}.pdf"

    cmd = [
        "python",
        str(BASE_DIR / "generate_catalog.py"),
        "-i",
        str(csv_path),
        "--output",
        str(output_pdf),
        "--images-dir",
        str(images_dir),
    ]

    result = subprocess.run(
        cmd,
        cwd=BASE_DIR,
        text=True,
        capture_output=True,
    )

    if result.returncode != 0:
        return (
            "<h2>Generování selhalo</h2>"
            "<h3>STDOUT</h3><pre>" + result.stdout + "</pre>"
            "<h3>STDERR</h3><pre>" + result.stderr + "</pre>"
        ), 500

    if not output_pdf.exists():
        return "PDF se nevytvořilo.", 500

    return f"""
    <h1>Katalog je hotový</h1>
    <p><a href="/download/{job_id}">Stáhnout PDF</a></p>
    <p><a href="/">Vygenerovat další</a></p>
    """


@app.get("/download/<job_id>")
def download(job_id):
    pdf_path = OUTPUT_DIR / f"catalog_{job_id}.pdf"
    if not pdf_path.exists():
        abort(404)
    return send_file(pdf_path, as_attachment=True, download_name="catalog.pdf")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)
