#!/usr/bin/env python3
"""Pure PEP-3333 WSGI web application for Reel Rebrand studio.

Compatible with:
- Local development: `python3 app.py`
- Shared hosting (cPanel Setup Python App / Phusion Passenger): `passenger_wsgi.py`
- Production WSGI servers: `gunicorn -w 2 -b 0.0.0.0:8080 app:application`
"""

from __future__ import annotations

import json
import mimetypes
import os
import re
import shutil
import subprocess
import sys
import time
import uuid
from http import HTTPStatus
from pathlib import Path
from socketserver import ThreadingMixIn
from typing import Any, Callable, Iterable
from wsgiref.simple_server import WSGIServer, make_server

APP_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(APP_DIR))

from processor import find_binary  # noqa: E402

ASSETS_DIR = APP_DIR / "assets"
STATIC_DIR = APP_DIR / "static"
JOBS_DIR = APP_DIR / "jobs"
DEFAULT_BG = ASSETS_DIR / "default_background.png"
DEFAULT_COVER = ASSETS_DIR / "default_cover.png"

MAX_BODY_BYTES = 180 * 1024 * 1024  # 180 MB max request
JOB_TTL_SECONDS = 7200  # Clean up old jobs after 2 hours
SAFE_JOB_RE = re.compile(r"^[a-f0-9]{12,32}$")


def _cleanup_old_jobs() -> None:
    if not JOBS_DIR.exists():
        return
    now = time.time()
    for d in JOBS_DIR.iterdir():
        if d.is_dir() and (now - d.stat().st_mtime) > JOB_TTL_SECONDS:
            shutil.rmtree(d, ignore_errors=True)


def _parse_multipart(content_type: str, body: bytes) -> tuple[dict[str, str], dict[str, tuple[str, bytes]]]:
    """Parse multipart/form-data without deprecated stdlib cgi module (Python 3.10-3.14+)."""
    m = re.search(r'boundary=(?:"([^"]+)"|([^;\s]+))', content_type, re.IGNORECASE)
    if not m:
        raise ValueError("Invalid multipart Content-Type header (missing boundary)")
    boundary_str = m.group(1) or m.group(2)
    boundary = b"--" + boundary_str.encode("latin-1")

    fields: dict[str, str] = {}
    files: dict[str, tuple[str, bytes]] = {}
    parts = body.split(boundary)
    for part in parts[1:]:
        if part.startswith(b"--"):
            break
        part = part.lstrip(b"\r\n")
        sep_idx = part.find(b"\r\n\r\n")
        if sep_idx < 0:
            continue
        raw_headers = part[:sep_idx].decode("utf-8", "replace")
        payload = part[sep_idx + 4 :]
        if payload.endswith(b"\r\n"):
            payload = payload[:-2]

        disp_match = re.search(r'Content-Disposition:[^\r\n]*\bname="([^"]+)"', raw_headers, re.IGNORECASE)
        if not disp_match:
            continue
        name = disp_match.group(1)
        fn_match = re.search(r'\bfilename="([^"]*)"', raw_headers, re.IGNORECASE)
        if fn_match:
            filename = Path(fn_match.group(1)).name
            if filename and len(payload) > 0:
                files[name] = (filename, payload)
        else:
            fields[name] = payload.decode("utf-8", "replace")
    return fields, files


def _json_response(
    start_response: Callable[..., Any],
    data: dict[str, Any],
    status: HTTPStatus = HTTPStatus.OK,
) -> list[bytes]:
    body = json.dumps(data).encode("utf-8")
    start_response(
        f"{status.value} {status.phrase}",
        [
            ("Content-Type", "application/json; charset=utf-8"),
            ("Content-Length", str(len(body))),
            ("Cache-Control", "no-store"),
        ],
    )
    return [body]


def _file_response(
    environ: dict[str, Any],
    start_response: Callable[..., Any],
    path: Path,
    content_type: str | None = None,
    download_name: str | None = None,
) -> Iterable[bytes]:
    if not path.exists():
        return _json_response(start_response, {"error": "File not found"}, HTTPStatus.NOT_FOUND)

    size = path.stat().st_size
    ctype = content_type or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
    headers: list[tuple[str, str]] = [
        ("Content-Type", ctype),
        ("Accept-Ranges", "bytes"),
    ]
    if download_name:
        safe_name = re.sub(r"[^A-Za-z0-9._-]", "_", download_name)
        headers.append(("Content-Disposition", f'attachment; filename="{safe_name}"'))
    else:
        headers.append(("Cache-Control", "no-cache"))

    range_header = environ.get("HTTP_RANGE", "")
    start = 0
    end = size - 1
    status = HTTPStatus.OK

    if range_header.startswith("bytes="):
        spec = range_header[6:].split(",", 1)[0].strip()
        if "-" in spec:
            s_str, e_str = spec.split("-", 1)
            if s_str:
                start = int(s_str)
                end = int(e_str) if e_str else size - 1
            elif e_str:
                start = max(0, size - int(e_str))
            end = min(end, size - 1)
            if start > end or start >= size:
                start_response("416 Range Not Satisfiable", [("Content-Range", f"bytes */{size}")])
                return [b""]
            status = HTTPStatus.PARTIAL_CONTENT
            headers.append(("Content-Range", f"bytes {start}-{end}/{size}"))

    length = max(0, end - start + 1)
    headers.append(("Content-Length", str(length)))
    start_response(f"{status.value} {status.phrase}", headers)

    def _stream() -> Iterable[bytes]:
        with path.open("rb") as fh:
            fh.seek(start)
            remaining = length
            while remaining > 0:
                chunk = fh.read(min(65536, remaining))
                if not chunk:
                    break
                remaining -= len(chunk)
                yield chunk

    return _stream()


def _handle_health(start_response: Callable[..., Any]) -> list[bytes]:
    checks: dict[str, Any] = {
        "default_background": DEFAULT_BG.exists(),
        "default_cover": DEFAULT_COVER.exists(),
    }
    for tool in ("ffmpeg", "yt-dlp"):
        try:
            checks[tool] = find_binary(tool)
        except Exception as exc:
            if tool == "yt-dlp":
                import importlib.util

                if importlib.util.find_spec("yt_dlp") is not None:
                    checks[tool] = f"{sys.executable} -m yt_dlp"
                    continue
            checks[tool] = f"missing: {exc}"
    ok = DEFAULT_BG.exists() and not str(checks.get("ffmpeg", "")).startswith("missing") and not str(checks.get("yt-dlp", "")).startswith("missing")
    return _json_response(start_response, {"ok": ok, "checks": checks})


def _handle_process(environ: dict[str, Any], start_response: Callable[..., Any]) -> list[bytes]:
    _cleanup_old_jobs()
    try:
        content_len = int(environ.get("CONTENT_LENGTH") or 0)
    except ValueError:
        content_len = 0
    if content_len <= 0:
        return _json_response(start_response, {"error": "Empty request body"}, HTTPStatus.BAD_REQUEST)
    if content_len > MAX_BODY_BYTES:
        return _json_response(start_response, {"error": "Request exceeds 180 MB limit"}, HTTPStatus.REQUEST_ENTITY_TOO_LARGE)

    raw_body = environ["wsgi.input"].read(content_len)
    ctype = environ.get("CONTENT_TYPE", "")
    fields: dict[str, str] = {}
    files: dict[str, tuple[str, bytes]] = {}

    if "multipart/form-data" in ctype:
        fields, files = _parse_multipart(ctype, raw_body)
    elif "application/json" in ctype:
        data = json.loads(raw_body.decode("utf-8"))
        fields = {str(k): str(v) for k, v in data.items() if v is not None}
    else:
        return _json_response(start_response, {"error": "Unsupported Content-Type"}, HTTPStatus.BAD_REQUEST)

    url = (fields.get("url") or "").strip()
    has_video_upload = "video_file" in files
    if not url and not has_video_upload:
        return _json_response(start_response, {"error": "Provide a video link or upload an MP4 file."}, HTTPStatus.BAD_REQUEST)

    job_id = uuid.uuid4().hex[:16]
    job_dir = JOBS_DIR / job_id
    job_dir.mkdir(parents=True, exist_ok=True)

    uploaded_video_path: str | None = None
    source_name: str | None = None
    if has_video_upload:
        vname, vbytes = files["video_file"]
        ext = Path(vname).suffix.lower()
        if ext not in (".mp4", ".mov", ".m4v", ".webm"):
            shutil.rmtree(job_dir, ignore_errors=True)
            return _json_response(start_response, {"error": "Unsupported video extension. Use MP4/MOV/WEBM."}, HTTPStatus.BAD_REQUEST)
        vdest = job_dir / f"input{ext}"
        vdest.write_bytes(vbytes)
        uploaded_video_path = str(vdest)
        source_name = re.sub(r"[^A-Za-z0-9._-]", "_", Path(vname).stem) or "uploaded_video"

    bg_path = DEFAULT_BG
    if "background_file" in files:
        bname, bbytes = files["background_file"]
        bext = Path(bname).suffix.lower() or ".png"
        bdest = job_dir / f"custom_bg{bext}"
        bdest.write_bytes(bbytes)
        bg_path = bdest

    cover_path: Path | None = DEFAULT_COVER if DEFAULT_COVER.exists() else None
    if "cover_file" in files:
        cname, cbytes = files["cover_file"]
        cext = Path(cname).suffix.lower() or ".png"
        cdest = job_dir / f"custom_cover{cext}"
        cdest.write_bytes(cbytes)
        cover_path = cdest

    include_cover = fields.get("include_cover", "true").lower() not in ("false", "0", "no")
    try:
        bg_zoom = max(1.0, min(2.5, float(fields.get("bg_zoom") or 1.45)))
        bg_y_frac = max(0.0, min(1.0, float(fields.get("bg_y_frac") or 0.425)))
    except ValueError:
        bg_zoom, bg_y_frac = 1.45, 0.425

    cfg = {
        "job_id": job_id,
        "url": url,
        "uploaded_video": uploaded_video_path,
        "source_name": source_name,
        "background_path": str(bg_path),
        "cover_path": str(cover_path) if cover_path else None,
        "include_cover": include_cover,
        "bg_zoom": bg_zoom,
        "bg_y_frac": bg_y_frac,
        "manual_crop": (fields.get("manual_crop") or "").strip() or None,
    }
    (job_dir / "config.json").write_text(json.dumps(cfg, indent=2), encoding="utf-8")
    (job_dir / "status.json").write_text(
        json.dumps({"status": "queued", "step": "queued", "progress": 5, "message": "Job queued..."}),
        encoding="utf-8",
    )

    log_fh = (job_dir / "worker.log").open("wb")
    try:
        subprocess.Popen(
            [sys.executable, str(APP_DIR / "worker.py"), str(job_dir)],
            cwd=str(APP_DIR),
            stdout=log_fh,
            stderr=subprocess.STDOUT,
            start_new_session=True,
        )
    finally:
        log_fh.close()
    return _json_response(start_response, {"job_id": job_id}, HTTPStatus.ACCEPTED)


def _extract_job_id(path: str, prefix: str) -> str | None:
    if not path.startswith(prefix):
        return None
    jid = path[len(prefix) :].strip("/")
    return jid if SAFE_JOB_RE.match(jid) else None


def application(environ: dict[str, Any], start_response: Callable[..., Any]) -> Iterable[bytes]:
    """PEP-3333 WSGI application entrypoint."""
    method = environ.get("REQUEST_METHOD", "GET").upper()
    path = environ.get("PATH_INFO", "/") or "/"

    try:
        if method == "GET" and path == "/":
            return _file_response(environ, start_response, STATIC_DIR / "index.html", "text/html; charset=utf-8")
        if method == "GET" and path == "/api/health":
            return _handle_health(start_response)
        if method == "GET" and path == "/api/defaults/background":
            return _file_response(environ, start_response, DEFAULT_BG, "image/png")
        if method == "GET" and path == "/api/defaults/cover":
            return _file_response(environ, start_response, DEFAULT_COVER, "image/png")
        if method == "POST" and path == "/api/process":
            return _handle_process(environ, start_response)

        if method == "GET" and path.startswith("/api/status/"):
            jid = _extract_job_id(path, "/api/status/")
            if not jid:
                return _json_response(start_response, {"error": "Invalid job ID"}, HTTPStatus.BAD_REQUEST)
            status_file = JOBS_DIR / jid / "status.json"
            if not status_file.exists():
                return _json_response(start_response, {"error": "Job not found"}, HTTPStatus.NOT_FOUND)
            st_data = json.loads(status_file.read_text(encoding="utf-8"))
            if st_data.get("status") == "queued" and (time.time() - status_file.stat().st_mtime) > 12:
                log_file = JOBS_DIR / jid / "worker.log"
                if log_file.exists():
                    log_txt = log_file.read_text(encoding="utf-8", errors="replace").strip()
                    if log_txt:
                        st_data = {"status": "error", "step": "error", "progress": 100, "error": log_txt[-500:]}
            return _json_response(start_response, st_data)

        if method == "GET" and path.startswith("/api/preview/"):
            jid = _extract_job_id(path, "/api/preview/")
            if not jid:
                return _json_response(start_response, {"error": "Invalid job ID"}, HTTPStatus.BAD_REQUEST)
            return _file_response(environ, start_response, JOBS_DIR / jid / "preview.jpg", "image/jpeg")

        if method == "GET" and path.startswith("/api/video/"):
            jid = _extract_job_id(path, "/api/video/")
            if not jid:
                return _json_response(start_response, {"error": "Invalid job ID"}, HTTPStatus.BAD_REQUEST)
            return _file_response(environ, start_response, JOBS_DIR / jid / "output.mp4", "video/mp4")

        if method == "GET" and path.startswith("/api/download/"):
            jid = _extract_job_id(path, "/api/download/")
            if not jid:
                return _json_response(start_response, {"error": "Invalid job ID"}, HTTPStatus.BAD_REQUEST)
            status_file = JOBS_DIR / jid / "status.json"
            dl_name = f"{jid}_rebranded.mp4"
            if status_file.exists():
                dl_name = json.loads(status_file.read_text(encoding="utf-8")).get("download_name") or dl_name
            return _file_response(environ, start_response, JOBS_DIR / jid / "output.mp4", "video/mp4", download_name=dl_name)

        return _json_response(start_response, {"error": "Not found"}, HTTPStatus.NOT_FOUND)
    except Exception as exc:
        return _json_response(start_response, {"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR)


class ThreadingWSGIServer(ThreadingMixIn, WSGIServer):
    daemon_threads = True
    allow_reuse_address = True


def main() -> None:
    host = os.environ.get("HOST", "127.0.0.1")
    port = int(os.environ.get("PORT", "8791"))
    JOBS_DIR.mkdir(parents=True, exist_ok=True)
    with make_server(host, port, application, server_class=ThreadingWSGIServer) as httpd:
        print(f"Reel Studio running at http://127.0.0.1:{port}", flush=True)
        httpd.serve_forever()


if __name__ == "__main__":
    main()
