#!/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()
SETTINGS_FILE = os.path.join(DATA_DIR, "settings.json")
OFFLOAD_STATE = {"enabled": True, "timeout_minutes": 10, "last_finish": None,
                 "models_loaded": False, "offloaded": False, "last_offload_at": None,
                 "last_offload": None, "reloaded_after_offload": False}

def load_settings():
    try:
        with open(SETTINGS_FILE, encoding="utf-8") as f:
            d = json.load(f)
        OFFLOAD_STATE["enabled"] = bool(d.get("enabled", True))
        OFFLOAD_STATE["timeout_minutes"] = max(1, int(d.get("timeout_minutes", 10)))
    except Exception:
        pass

def save_settings():
    try:
        os.makedirs(DATA_DIR, exist_ok=True)
        with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
            json.dump({"enabled": OFFLOAD_STATE["enabled"],
                       "timeout_minutes": OFFLOAD_STATE["timeout_minutes"]}, f, ensure_ascii=False)
    except Exception:
        pass

def _nvidia_total():
    try:
        out = subprocess.check_output(["nvidia-smi", "--query-gpu=memory.used,memory.total",
                                       "--format=csv,noheader,nounits"], timeout=5, text=True)
        u, t = out.strip().split(",")
        return int(u.strip()), int(t.strip())
    except Exception:
        return None, None

def _cgroup_ram():
    try:
        cur = int(open("/sys/fs/cgroup/memory.current").read().strip())
    except Exception:
        cur = None
    try:
        mx = open("/sys/fs/cgroup/memory.max").read().strip()
        mx = None if mx == "max" else int(mx)
    except Exception:
        mx = None
    return cur, mx

def _any_job_active():
    if Q.qsize() > 0:
        return True
    with LOCK:
        return any(j.get("status") in ("queued", "running") for j in JOBS.values())

def _vsr_procs():
    try:
        out = subprocess.check_output(["ps", "aux"], timeout=5, text=True)
        return [ln for ln in out.splitlines() if "vsr_infer.py" in ln and "grep" not in ln]
    except Exception:
        return []

def do_offload(manual=False):
    if not manual and _any_job_active():
        return {"ok": False, "error": "有任务在运行/排队，暂不卸载"}
    before_used, before_total = _nvidia_total()
    before_procs = _vsr_procs()
    killed = 0
    for ln in before_procs:
        try:
            pid = int(ln.split()[1])
            subprocess.run(["kill", str(pid)], timeout=5)
            killed += 1
        except Exception:
            pass
    # vsr_infer temp SR PNG dirs are no longer needed after encoding; clean them on offload
    cleaned = 0
    try:
        import glob, shutil
        for d in glob.glob("/tmp/vsr_sr_*"):
            shutil.rmtree(d, ignore_errors=True)
            cleaned += 1
    except Exception:
        pass
    after_used, _ = _nvidia_total()
    OFFLOAD_STATE["offloaded"] = True
    OFFLOAD_STATE["models_loaded"] = False
    OFFLOAD_STATE["last_offload_at"] = now()
    # Honest note: this service loads RealBasicVSR in a per-job subprocess,
    # so there is no in-process torch model to delete; offload here means
    # verifying/killing any lingering vsr_infer process and cleaning temp SR frames.
    OFFLOAD_STATE["last_offload"] = {"method": "vsr_subprocess_check+tmp_clean",
        "model_in_process": False, "before_procs": len(before_procs), "killed": killed,
        "tmp_dirs_cleaned": cleaned, "before_nvidia_used_mib": before_used,
        "after_nvidia_used_mib": after_used, "manual": manual}
    return {"ok": True, **OFFLOAD_STATE["last_offload"]}

def offload_status():
    nv_used, nv_total = _nvidia_total()
    ram_cur, ram_max = _cgroup_ram()
    lf = OFFLOAD_STATE.get("last_finish")
    elapsed = (now() - lf) if lf else None
    timeout_s = OFFLOAD_STATE["timeout_minutes"] * 60
    countdown = None
    if lf and not OFFLOAD_STATE.get("offloaded"):
        countdown = max(0, int(timeout_s - elapsed))
    return {"enabled": OFFLOAD_STATE["enabled"], "timeout_minutes": OFFLOAD_STATE["timeout_minutes"],
            "models_loaded": OFFLOAD_STATE["models_loaded"], "offloaded": OFFLOAD_STATE["offloaded"],
            "last_finish": lf, "seconds_since_finish": (int(elapsed) if elapsed is not None else None),
            "countdown_seconds": countdown, "next_offload_at": (lf + timeout_s if lf else None),
            "last_offload_at": OFFLOAD_STATE.get("last_offload_at"), "last_offload": OFFLOAD_STATE.get("last_offload"),
            "vsr_procs": len(_vsr_procs()), "model_in_process": False,
            "nvidia_used_mib": nv_used, "nvidia_total_mib": nv_total,
            "container_ram_bytes": ram_cur, "container_ram_max_bytes": ram_max,
            "job_active": _any_job_active()}

def offload_watchdog():
    import traceback
    while True:
        time.sleep(10)
        try:
            if not OFFLOAD_STATE.get("enabled") or OFFLOAD_STATE.get("offloaded"):
                continue
            lf = OFFLOAD_STATE.get("last_finish")
            if not lf:
                continue
            if (now() - lf) >= OFFLOAD_STATE["timeout_minutes"] * 60 and not _any_job_active():
                do_offload(manual=False)
        except Exception:
            traceback.print_exc()

def ensure_offload_watchdog():
    threading.Thread(target=offload_watchdog, name="offload-watchdog", daemon=True).start()


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:
        if OFFLOAD_STATE.get("offloaded"):
            OFFLOAD_STATE["reloaded_after_offload"] = True
        OFFLOAD_STATE["models_loaded"] = True
        OFFLOAD_STATE["offloaded"] = False
        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:
        OFFLOAD_STATE["last_finish"] = now()
        OFFLOAD_STATE["models_loaded"] = True
        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)
    OFFLOAD_STATE["models_loaded"] = True
    OFFLOAD_STATE["offloaded"] = False
    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"])



@app.route("/api/settings", methods=["GET", "POST"])
def api_settings():
    if request.method == "GET":
        return jsonify({"enabled": OFFLOAD_STATE["enabled"], "timeout_minutes": OFFLOAD_STATE["timeout_minutes"]})
    body = request.get_json(silent=True) or {}
    if "enabled" in body:
        OFFLOAD_STATE["enabled"] = bool(body["enabled"])
    if "timeout_minutes" in body:
        try:
            OFFLOAD_STATE["timeout_minutes"] = max(1, int(body["timeout_minutes"]))
        except Exception:
            return jsonify({"error": "timeout_minutes 必须是分钟数"}), 400
    save_settings()
    return jsonify({"enabled": OFFLOAD_STATE["enabled"], "timeout_minutes": OFFLOAD_STATE["timeout_minutes"]})


@app.route("/api/offload-status")
def api_offload_status():
    return jsonify(offload_status())


@app.route("/api/offload", methods=["POST"])
def api_offload():
    if _any_job_active():
        return jsonify({"ok": False, "error": "有任务在运行/排队，暂不卸载"}), 409
    return jsonify(do_offload(manual=True))


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


if __name__ == "__main__":
    main()
