#!/usr/bin/env python3
"""RealBasicVSR video super-resolution service (19106-vsr-upscale).
Web + API on 0.0.0.0:8082. Async queue, one job at a time.
Contract (Jim, 2026-10-31 / 2026-11-01):
- Route: RealBasicVSR video route ONLY (not frame-by-frame Real-ESRGAN).
- First version: input MP4 480P -> 720P short side only. No 1080P promise.
- DURATION UNCHANGED: no extension, no frame interpolation, no padding,
  no truncation, no speed change. Same frame count, same fps.
- Audio: copied unchanged (-c:a copy remux). Never regenerated.
- Model itself is x4: SR frames are produced at x4, then in the SAME
  pipeline downscaled with high-quality Lanczos to short side 720,
  preserving the original aspect ratio. This is logged per job.
"""
import json
import os
import queue
import subprocess
import threading
import time
import uuid

from flask import Flask, jsonify, request, send_file, send_from_directory

ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOADS = os.path.join(ROOT, "uploads")
OUTPUTS = os.path.join(ROOT, "outputs")
DATA_DIR = os.path.join(ROOT, "data")
JOBS_FILE = os.path.join(DATA_DIR, "jobs.json")
PORT = int(os.environ.get("WEBAPP_PORT", "8082"))
VENV_PY = "/home/agent/vsr-venv/bin/python"  # local-disk venv (project bind mount is too slow for torch)

app = Flask(__name__)
JOBS = {}
LOCK = threading.Lock()
Q = queue.Queue()


def now():
    return time.time()


def load_jobs():
    try:
        with open(JOBS_FILE, encoding="utf-8") as f:
            for j in json.load(f):
                if j.get("status") in ("queued", "running"):
                    j["status"] = "interrupted"
                JOBS[j["id"]] = j
    except Exception:
        pass


def save_jobs():
    # Serialized + unique tmp name: API thread and worker thread both
    # save, and sharing one tmp file raced (one os.replace 500'd).
    with LOCK:
        os.makedirs(DATA_DIR, exist_ok=True)
        tmp = "%s.tmp.%s.%s" % (JOBS_FILE, os.getpid(), threading.get_ident())
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(list(JOBS.values()), f, ensure_ascii=False)
        os.replace(tmp, JOBS_FILE)


def public(j):
    return {k: j.get(k) for k in (
        "id", "status", "input_file", "input_width", "input_height",
        "input_duration", "input_fps", "output_file", "output_width",
        "output_height", "output_duration", "output_fps", "size_bytes",
        "elapsed_sec", "engine", "model", "error", "created_at", "finished_at")}


def probe(path):
    out = subprocess.check_output([
        "ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_entries", "stream=width,height,r_frame_rate,avg_frame_rate",
        "-show_entries", "format=duration",
        "-of", "json", path], text=True, timeout=30)
    d = json.loads(out)
    s = d["streams"][0]
    num, den = s["r_frame_rate"].split("/")
    fps = float(num) / float(den) if float(den) else 0.0
    return int(s["width"]), int(s["height"]), fps, float(d["format"]["duration"])


def run_job(job):
    jid = job["id"]
    t0 = now()
    with LOCK:
        job["status"] = "running"
    save_jobs()
    try:
        src = os.path.join(UPLOADS, job["input_file"])
        w, h, fps, dur = probe(src)
        job.update({"input_width": w, "input_height": h, "input_fps": round(fps, 3),
                    "input_duration": round(dur, 3)})
        out_path = os.path.join(OUTPUTS, jid + "_720p.mp4")
        log_path = os.path.join(DATA_DIR, jid + ".log")
        with open(log_path, "w", encoding="utf-8") as lf:
            p = subprocess.run([
                VENV_PY, os.path.join(ROOT, "vsr_infer.py"),
                "--input", src, "--output", out_path,
                "--model", os.path.join(ROOT, "weights", "RealBasicVSR_x4.pth"),
            ], stdout=lf, stderr=subprocess.STDOUT, timeout=7200)
        if p.returncode != 0:
            raise RuntimeError("vsr_infer failed, see data/%s.log" % jid)
        ow, oh, ofps, odur = probe(out_path)
        job.update({"output_file": os.path.basename(out_path),
                    "output_width": ow, "output_height": oh,
                    "output_fps": round(ofps, 3), "output_duration": round(odur, 3),
                    "size_bytes": os.path.getsize(out_path),
                    "elapsed_sec": round(now() - t0, 1),
                    "engine": "RealBasicVSR (video route, x4 then Lanczos to 720P short side)",
                    "model": "RealBasicVSR_x4.pth (official, CVPR 2022)",
                    "status": "done", "finished_at": now()})
    except Exception as e:
        job.update({"status": "error", "error": str(e)[:2000],
                    "elapsed_sec": round(now() - t0, 1), "finished_at": now()})
    finally:
        save_jobs()


def worker():
    while True:
        job = Q.get()
        try:
            run_job(job)
        finally:
            Q.task_done()


@app.route("/")
def index():
    return send_from_directory(os.path.join(ROOT, "static"), "index.html")


@app.route("/health")
def health():
    return jsonify({"ok": True, "jobs_queued": Q.qsize()})


@app.route("/api/upscale", methods=["POST"])
def api_upscale():
    if "file" in request.files and request.files["file"].filename:
        f = request.files["file"]
        ext = os.path.splitext(f.filename)[1].lower() or ".mp4"
        name = uuid.uuid4().hex[:12] + ext
        f.save(os.path.join(UPLOADS, name))
    else:
        body = request.get_json(silent=True) or {}
        url = body.get("file_url")
        if not url:
            return jsonify({"error": "need multipart file or file_url"}), 400
        name = uuid.uuid4().hex[:12] + ".mp4"
        subprocess.check_call(["curl", "-sL", "-o", os.path.join(UPLOADS, name), url], timeout=300)
    jid = uuid.uuid4().hex[:12]
    job = {"id": jid, "status": "queued", "input_file": name, "created_at": now()}
    with LOCK:
        JOBS[jid] = job
    Q.put(job)
    save_jobs()
    return jsonify(public(job)), 202


@app.route("/api/jobs/<jid>")
def api_job(jid):
    job = JOBS.get(jid)
    if not job:
        return jsonify({"error": "job not found"}), 404
    return jsonify(public(job))


@app.route("/api/download/<jid>")
def api_download(jid):
    job = JOBS.get(jid)
    if not job or not job.get("output_file"):
        return jsonify({"error": "output not ready"}), 404
    return send_file(os.path.join(OUTPUTS, job["output_file"]),
                     mimetype="video/mp4", as_attachment=True,
                     download_name=job["output_file"])


def main():
    os.makedirs(UPLOADS, exist_ok=True)
    os.makedirs(OUTPUTS, exist_ok=True)
    os.makedirs(DATA_DIR, exist_ok=True)
    load_jobs()
    threading.Thread(target=worker, daemon=True).start()
    app.run(host="0.0.0.0", port=PORT, threaded=True, debug=False)


if __name__ == "__main__":
    main()
