#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""MiniMax H3 Fast (19105-h3-fast) webapp + async API.

Serves on 0.0.0.0:8082.  Generation is queued to ComfyUI (127.0.0.1:8188) by a
single background worker so HTTP requests never block and the 12-16 GB GPU is
never asked to run two H3 jobs at once.
"""
import base64
import json
import os
import queue
import random
import re
import shutil
import subprocess
import threading
import time
import traceback
import urllib.parse
import urllib.request
import uuid

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

ROOT = os.path.dirname(os.path.abspath(__file__))
COMFY_DIR = os.path.join(ROOT, "ComfyUI")
COMFY_URL = os.environ.get("COMFY_URL", "http://127.0.0.1:8188")
COMFY_INPUT = os.path.join(ROOT, "comfy_input")
COMFY_OUTPUT = os.path.join(ROOT, "generated")
COMFY_TEMP = os.path.join(ROOT, "comfy_temp")
UPLOADS = os.path.join(ROOT, "uploads")
DATA_DIR = os.path.join(ROOT, "data")
JOBS_FILE = os.path.join(DATA_DIR, "jobs.json")
COMFY_LOG = os.path.join(ROOT, "logs", "comfyui.log")
WEBAPP_PORT = int(os.environ.get("WEBAPP_PORT", "8082"))
TOKEN = os.environ.get("CARD_TOKEN", "agent")

# --- model files (fast/distilled stack) -------------------------------------
MODEL_UNET = "minimax_h3_fl2va_pruned_int8_convrot.safetensors"
MODEL_UNET_REF = "minimax_h3_ref2va_pruned_int8_convrot.safetensors"  # optional, not downloaded by default
MODEL_CLIP = "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors"
MODEL_VAE_VIDEO = "minimax_h3_video_vae_fp16.safetensors"
MODEL_VAE_AUDIO = "minimax_h3_audio_vae_fp32.safetensors"
LORA_T2V_I2V = "minimax_h3_fl2v_turbo_8step_v1.0_comfyui_bf16.safetensors"
LORA_REF = "minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors"
TURBO_STEPS = 8
REF_TURBO_STEPS = 4

RESOLUTIONS = {
    # key: (width, height, label, enabled)
    "480p": (832, 480, "480p 832x480 (16:9)", True),
    "540p": (960, 544, "540p 960x544 (16:9)", True),
    "768p": (1344, 768, "768p 1344x768 (16:9)", os.environ.get("ALLOW_768P", "0") == "1"),
}
DURATIONS = {
    # seconds: frame count snapped to the 17k+5 grid at 24 fps
    "5": (124, True),
    "10": (243, os.environ.get("ALLOW_LONG", "0") == "1"),
    "15": (362, os.environ.get("ALLOW_15S", "0") == "1"),
}
# 宽高比（默认 4:3）：在分辨率档位内按短边算尺寸；16:9 沿用已验证的档位原尺寸，其余算到 16 的倍数。
ASPECTS = ("4:3", "16:9", "9:16", "1:1")
DEFAULT_ASPECT = "4:3"

def aspect_dims(resolution, aspect):
    w0, h0, _, _ = RESOLUTIONS[resolution]
    if aspect == "16:9":
        return w0, h0
    short = min(w0, h0)
    if aspect == "1:1":
        return short, short
    if aspect == "4:3":
        long = int(round(short * 4 / 3 / 16) * 16)
    else:  # 9:16
        long = int(round(short * 16 / 9 / 16) * 16)
    return (long, short) if w0 >= h0 else (short, long)

app = Flask(__name__, static_folder=None)

# --- OCS delivery (Jim 2026-11-01: generated outputs go via OCS) -------------
OCS_BASE = "https://ocs.dimond.top"


def upload_to_ocs(path, ocs_name):
    """Upload a finished output to OCS. Returns the OCS URL, or None on
    failure (never raises; the local download stays as fallback)."""
    for _ in range(3):
        try:
            subprocess.run(["curl", "-sS", "--fail", "--upload-file", path,
                            OCS_BASE + "/" + ocs_name],
                           timeout=900, check=True)
            return OCS_BASE + "/" + ocs_name
        except Exception:
            time.sleep(5)
    return None


JOBS = {}
JOBS_LOCK = threading.Lock()
JOB_QUEUE = queue.Queue()
WORKER_STARTED = False
SETTINGS_FILE = os.path.join(DATA_DIR, "settings.json")
OFFLOAD_STATE = {"enabled": True, "timeout_minutes": 10, "aspect_ratio": DEFAULT_ASPECT, "last_finish": None,
                 "models_loaded": False, "offloaded": False, "last_offload_at": None,
                 "last_offload": None, "reloaded_after_offload": False}
OFFLOAD_LOCK = threading.Lock()

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)))
        _a = str(d.get("aspect_ratio", DEFAULT_ASPECT))
        OFFLOAD_STATE["aspect_ratio"] = _a if _a in ASPECTS else DEFAULT_ASPECT
    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"],
                   "aspect_ratio": OFFLOAD_STATE.get("aspect_ratio", DEFAULT_ASPECT)}, f, ensure_ascii=False)
    except Exception:
        pass

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 _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 _comfy_vram():
    try:
        d = comfy_get("/system_stats", timeout=3)
        dev = (d.get("devices") or [{}])[0]
        return dev.get("vram_total"), dev.get("vram_free")
    except Exception:
        return None, None

def _any_job_active():
    if JOB_QUEUE.qsize() > 0:
        return True
    with JOBS_LOCK:
        if any(j.get("status") in ("queued", "running") for j in JOBS.values()):
            return True
    try:
        r, p = queue_positions()
        if r or p:
            return True
    except Exception:
        pass
    return False

def _restart_comfy():
    try:
        subprocess.run(["pkill", "-f", "ComfyUI/main.py"], timeout=10)
        time.sleep(3)
        cmd = [os.path.join(ROOT, "venv", "bin", "python"), "ComfyUI/main.py",
               "--listen", "127.0.0.1", "--port", "8188", "--cuda-device", "0",
               "--disable-pinned-memory", "--input-directory", COMFY_INPUT,
               "--output-directory", COMFY_OUTPUT]
        log = open(COMFY_LOG, "a", encoding="utf-8", errors="replace")
        subprocess.Popen(cmd, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
        return wait_comfy(300)
    except Exception as e:
        return False

def do_offload(manual=False):
    with OFFLOAD_LOCK:
        if not manual and _any_job_active():
            return {"ok": False, "error": "有任务在运行/排队，暂不卸载"}
        before_total, before_free = _comfy_vram()
        before_nv_used, before_nv_total = _nvidia_total()
        method = "comfy_free"
        try:
            # /free returns an empty/non-JSON body; post raw and judge by
            # the VRAM delta afterwards, not by response parsing.
            import requests as _rq
            _rq.post(COMFY_URL + "/free", json={"unload_models": True, "free_memory": True}, timeout=30)
        except Exception as e:
            method = "comfy_free_post_error:%s" % e
        time.sleep(5)
        after_total, after_free = _comfy_vram()
        # /free flag is only acted on by ComfyUI's queue loop; if it did not
        # move VRAM and models were loaded, restart ComfyUI to a clean state.
        if OFFLOAD_STATE.get("models_loaded") and before_free is not None and after_free is not None and (after_free - before_free) < 1024*1024*1024:
            if _restart_comfy():
                method = "comfy_free+restart"
                time.sleep(2)
                after_total, after_free = _comfy_vram()
        after_nv_used, _ = _nvidia_total()
        OFFLOAD_STATE["offloaded"] = True
        OFFLOAD_STATE["models_loaded"] = False
        OFFLOAD_STATE["last_offload_at"] = now()
        OFFLOAD_STATE["last_offload"] = {"method": method, "before_vram_free": before_free,
            "after_vram_free": after_free, "before_nvidia_used_mib": before_nv_used,
            "after_nvidia_used_mib": after_nv_used, "manual": manual}
        return {"ok": True, **OFFLOAD_STATE["last_offload"]}

def offload_status():
    vt, vf = _comfy_vram()
    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"),
            "vram_total": vt, "vram_free": vf, "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():
    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():
    t = threading.Thread(target=offload_watchdog, name="offload-watchdog", daemon=True)
    t.start()


def now():
    return time.time()


def load_jobs():
    try:
        with open(JOBS_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
        for j in data:
            # a job left running by a crash is marked interrupted on restart
            if j.get("status") in ("queued", "running"):
                j["status"] = "error"
                j["error"] = "服务重启，任务中断"
            JOBS[j["id"]] = j
    except Exception:
        pass


def save_jobs():
    # Windows bind-mount project dir: a shared .tmp name can race with a
    # concurrent replace; use a per-thread tmp name and retry makedirs/open.
    import threading as _th
    tmp = "%s.tmp.%s.%s" % (JOBS_FILE, os.getpid(), _th.get_ident())
    last = None
    for _ in range(3):
        try:
            os.makedirs(DATA_DIR, exist_ok=True)
            with JOBS_LOCK:
                vals = sorted(JOBS.values(), key=lambda x: x.get("created", 0))
                with open(tmp, "w", encoding="utf-8") as f:
                    json.dump(vals[-100:], f, ensure_ascii=False, indent=1)
            os.replace(tmp, JOBS_FILE)
            return
        except Exception as e:
            last = e
            time.sleep(0.2)
    raise last


def public_job(j):
    return {
        "job_id": j["id"],
        "status": j["status"],
        "prompt": j.get("prompt", ""),
        "mode": j.get("mode"),
        "duration": j.get("duration"),
        "resolution": j.get("resolution"),
        "aspect_ratio": j.get("aspect_ratio"),
        "width": j.get("width"),
        "height": j.get("height"),
        "frames": j.get("frames"),
        "seed": j.get("seed"),
        "created_at": j.get("created_at"),
        "started_at": j.get("started_at"),
        "finished_at": j.get("finished_at"),
        "elapsed_sec": j.get("elapsed_sec"),
        "queue_position": j.get("queue_position"),
        "size_bytes": j.get("size_bytes"),
        "error": j.get("error"),
        "ocs_url": j.get("ocs_url"),
        "download_url": ("/api/download/%s" % j["id"]) if j["status"] == "done" else None,
        "video_url": (j.get("ocs_url") or ("/api/download/%s" % j["id"])) if j["status"] == "done" else None,
        "engine": "ComfyUI + MiniMax-H3 pruned-int8-convrot + NVFP4-Qwen3VL-32B + Turbo %s steps" % j.get("steps", TURBO_STEPS),
    }


def comfy_get(path, timeout=10):
    with urllib.request.urlopen(COMFY_URL + path, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8"))


def comfy_post(path, payload, timeout=30):
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(COMFY_URL + path, data=data,
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8"))


def comfy_online():
    try:
        comfy_get("/system_stats", timeout=3)
        return True
    except Exception:
        return False


def wait_comfy(timeout=600):
    end = now() + timeout
    while now() < end:
        if comfy_online():
            return True
        time.sleep(2)
    return False


def comfy_object_info(node=None):
    path = "/object_info" if node is None else "/object_info/" + node
    return comfy_get(path, timeout=60)


def safe_name(name, default_ext=""):
    name = os.path.basename(name or "")
    name = re.sub(r"[^A-Za-z0-9._-]+", "_", name)
    if not name:
        name = uuid.uuid4().hex + default_ext
    return name


def fetch_reference(ref, prefix, target_dir):
    """Accept http(s) URL, data: URL, local ComfyUI input filename or absolute path.
    Returns a filename that exists in target_dir."""
    if not ref:
        return None
    os.makedirs(target_dir, exist_ok=True)
    if ref.startswith("data:"):
        head, _, b64 = ref.partition(",")
        ext = ".png"
        m = re.search(r"data:image/(\w+)", head)
        if m:
            ext = "." + ("jpg" if m.group(1) == "jpeg" else m.group(1))
        name = prefix + "_" + uuid.uuid4().hex[:8] + ext
        with open(os.path.join(target_dir, name), "wb") as f:
            f.write(base64.b64decode(b64))
        return name
    if ref.startswith("http://") or ref.startswith("https://"):
        parsed = urllib.parse.urlparse(ref)
        ext = os.path.splitext(parsed.path)[1] or ".bin"
        name = prefix + "_" + uuid.uuid4().hex[:8] + ext
        dst = os.path.join(target_dir, name)
        with urllib.request.urlopen(ref, timeout=120) as r, open(dst, "wb") as f:
            shutil.copyfileobj(r, f)
        return name
    # local file name / absolute path
    base = safe_name(ref)
    src = ref if os.path.isabs(ref) and os.path.exists(ref) else os.path.join(target_dir, base)
    if not os.path.exists(src) and os.path.exists(os.path.join(COMFY_INPUT, base)):
        src = os.path.join(COMFY_INPUT, base)
    if not os.path.exists(src):
        raise FileNotFoundError("reference not found: %s" % ref)
    if os.path.abspath(src) != os.path.abspath(os.path.join(target_dir, base)):
        shutil.copy2(src, os.path.join(target_dir, base))
    return base


def frame_length(duration):
    sec = float(duration)
    frames = max(5, round(sec * 24))
    while frames % 17 != 5:
        frames += 1
    return frames


def build_prompt(job):
    """Return ComfyUI API prompt dict for the requested mode."""
    mode = job["mode"]
    w, h = job["width"], job["height"]
    length = job["frames"]
    seed = job["seed"]
    prompt = job["prompt"]
    is_ref = mode == "reference"
    steps = job.get("steps", REF_TURBO_STEPS if is_ref else TURBO_STEPS)
    unet_name = MODEL_UNET_REF if is_ref else MODEL_UNET
    lora_name = LORA_REF if is_ref else LORA_T2V_I2V

    g = {
        "unet": {"class_type": "UNETLoader",
                 "inputs": {"unet_name": unet_name, "weight_dtype": "default"}},
        "lora": {"class_type": "LoraLoaderModelOnly",
                 "inputs": {"model": ["unet", 0], "lora_name": lora_name,
                            "strength_model": 1.0}},
        "clip": {"class_type": "CLIPLoader",
                 "inputs": {"clip_name": MODEL_CLIP, "type": "minimax", "device": "default"}},
        "vae": {"class_type": "VAELoader", "inputs": {"vae_name": MODEL_VAE_VIDEO}},
        "audio_vae": {"class_type": "VAELoader", "inputs": {"vae_name": MODEL_VAE_AUDIO}},
        "noise": {"class_type": "RandomNoise", "inputs": {"noise_seed": seed}},
        "sampler": {"class_type": "KSamplerSelect", "inputs": {"sampler_name": "res_multistep"}},
        "sched": {"class_type": "BasicScheduler",
                  "inputs": {"model": ["lora", 0], "scheduler": "simple",
                             "steps": steps, "denoise": 1.0}},
        "guider": {"class_type": "BasicGuider",
                   "inputs": {"model": ["lora", 0], "conditioning": ["cond", 0]}},
        "sample": {"class_type": "SamplerCustomAdvanced",
                   "inputs": {"noise": ["noise", 0], "guider": ["guider", 0],
                              "sampler": ["sampler", 0], "sigmas": ["sched", 0],
                              "latent_image": ["cond", 1]}},
        "decode_video": {"class_type": "VAEDecode",
                         "inputs": {"samples": ["sample", 0], "vae": ["vae", 0]}},
        "decode_audio": {"class_type": "VAEDecodeAudio",
                         "inputs": {"samples": ["sample", 0], "vae": ["audio_vae", 0]}},
        "video": {"class_type": "CreateVideo",
                  "inputs": {"images": ["decode_video", 0], "audio": ["decode_audio", 0],
                             "fps": 24, "bit_depth": 8, "color_space": "sRGB"}},
        "save": {"class_type": "SaveVideo",
                 "inputs": {"video": ["video", 0],
                            "filename_prefix": "h3fast/%s" % job["id"],
                            "format": "mp4"}},
    }

    if mode == "t2v":
        g["cond"] = {"class_type": "MiniMaxH3ImageToVideo",
                     "inputs": {"clip": ["clip", 0], "vae": ["vae", 0], "prompt": prompt,
                                "width": w, "height": h, "length": length}}
    elif mode == "i2v":
        if not job.get("reference_image"):
            raise ValueError("image-to-video 需要 reference_image_url")
        g["load_image"] = {"class_type": "LoadImage",
                           "inputs": {"image": job["reference_image"]}}
        g["cond"] = {"class_type": "MiniMaxH3ImageToVideo",
                     "inputs": {"clip": ["clip", 0], "vae": ["vae", 0], "prompt": prompt,
                                "width": w, "height": h, "length": length,
                                "first_frame": ["load_image", 0]}}
    elif mode == "reference":
        refs = {}
        if job.get("reference_image"):
            g["ref_load_image"] = {"class_type": "LoadImage",
                                   "inputs": {"image": job["reference_image"]}}
            refs["ref_image_0"] = ["ref_load_image", 0]
        if job.get("reference_video"):
            g["ref_load_video"] = {"class_type": "LoadVideo",
                                   "inputs": {"file": job["reference_video"]}}
            g["ref_components"] = {"class_type": "GetVideoComponents",
                                   "inputs": {"video": ["ref_load_video", 0]}}
            refs["ref_video_0"] = ["ref_components", 0]
        if not refs:
            raise ValueError("reference-to-video 需要 reference_image_url 或 reference_video_url")
        g["cond"] = {"class_type": "MiniMaxH3ReferenceToVideo",
                     "inputs": {"clip": ["clip", 0], "vae": ["vae", 0],
                                "audio_vae": ["audio_vae", 0], "prompt": prompt,
                                "width": w, "height": h, "length": length,
                                "ref_image_size": "match", **refs}}
    else:
        raise ValueError("unknown mode: %s" % mode)

    # rewire scheduler/guider to the ref LoRA-free graph when needed
    return g


def find_output(job_id, timeout=10):
    """SaveVideo writes <output>/h3fast/<prefix>_00001_.mp4"""
    sub = os.path.join(COMFY_OUTPUT, "h3fast")
    end = now() + timeout
    while now() < end:
        if os.path.isdir(sub):
            hits = [os.path.join(sub, f) for f in os.listdir(sub)
                    if f.startswith(job_id) and f.endswith((".mp4", ".mkv", ".webm"))]
            hits = [p for p in hits if os.path.getsize(p) > 0]
            if hits:
                return max(hits, key=os.path.getmtime)
        time.sleep(1)
    return None


def log_tail(n=80):
    try:
        with open(COMFY_LOG, "r", encoding="utf-8", errors="replace") as f:
            lines = f.readlines()
        return "".join(lines[-n:])
    except Exception:
        return ""


def queue_positions():
    try:
        q = comfy_get("/queue", timeout=3)
        running = len(q.get("queue_running", []))
        pending = len(q.get("queue_pending", []))
        return running, pending
    except Exception:
        return 0, 0


def run_job(job):
    jid = job["id"]
    with OFFLOAD_LOCK:
        if OFFLOAD_STATE.get("offloaded"):
            OFFLOAD_STATE["reloaded_after_offload"] = True
        OFFLOAD_STATE["models_loaded"] = True
        OFFLOAD_STATE["offloaded"] = False
    with JOBS_LOCK:
        job["status"] = "running"
        job["started_at"] = now()
    try:
        save_jobs()
    except Exception:
        # a save failure must never leave the job stuck before ComfyUI runs
        traceback.print_exc()
    t0 = now()
    try:
        if not comfy_online():
            if not wait_comfy(600):
                raise RuntimeError("ComfyUI 未就绪 (127.0.0.1:8188)")
        prompt = build_prompt(job)
        r = comfy_post("/prompt", {"prompt": prompt,
                                   "client_id": "h3fast-" + jid})
        pid = r.get("prompt_id")
        job["comfy_prompt_id"] = pid
        save_jobs()
        deadline = now() + float(os.environ.get("JOB_TIMEOUT", "7200"))
        hist = {}
        while now() < deadline:
            try:
                hist = comfy_get("/history/%s" % pid, timeout=10)
            except Exception:
                hist = {}
            if pid in hist:
                break
            time.sleep(2)
        if pid not in hist:
            raise RuntimeError("生成超时 (%ss)" % int(now() - t0))
        entry = hist[pid]
        status = entry.get("status", {})
        if status.get("status_str") == "error":
            msgs = status.get("messages", [])
            raise RuntimeError("ComfyUI 执行失败: %s" % json.dumps(msgs, ensure_ascii=False)[-3000:])
        out = find_output(jid)
        if not out:
            raise RuntimeError("未找到输出视频文件")
        job["output_file"] = out
        job["size_bytes"] = os.path.getsize(out)
        job["ocs_name"] = "h3fast_%s.mp4" % jid
        job["ocs_url"] = upload_to_ocs(out, job["ocs_name"])
        job["ocs_upload"] = "ok" if job["ocs_url"] else "failed"
        job["elapsed_sec"] = round(now() - t0, 1)
        job["finished_at"] = now()
        job["status"] = "done"
    except Exception as e:
        job["status"] = "error"
        job["error"] = str(e)
        job["elapsed_sec"] = round(now() - t0, 1)
        job["finished_at"] = now()
        job["log_tail"] = log_tail(120)
        traceback.print_exc()
    finally:
        job.pop("queue_position", None)
        with OFFLOAD_LOCK:
            OFFLOAD_STATE["last_finish"] = now()
            OFFLOAD_STATE["models_loaded"] = True
        save_jobs()


def worker_loop():
    while True:
        job = JOB_QUEUE.get()
        if job is None:
            continue
        try:
            run_job(job)
        except Exception:
            traceback.print_exc()
        finally:
            JOB_QUEUE.task_done()


def ensure_worker():
    global WORKER_STARTED
    if not WORKER_STARTED:
        t = threading.Thread(target=worker_loop, name="h3-worker", daemon=True)
        t.start()
        WORKER_STARTED = True


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


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


@app.route("/health")
def health():
    running, pending = queue_positions()
    models = {
        "diffusion": os.path.exists(os.path.join(COMFY_DIR, "models/diffusion_models", MODEL_UNET)),
        "text_encoder": os.path.exists(os.path.join(COMFY_DIR, "models/text_encoders", MODEL_CLIP)),
        "video_vae": os.path.exists(os.path.join(COMFY_DIR, "models/vae", MODEL_VAE_VIDEO)),
        "audio_vae": os.path.exists(os.path.join(COMFY_DIR, "models/vae", MODEL_VAE_AUDIO)),
        "turbo_lora": os.path.exists(os.path.join(COMFY_DIR, "models/loras", LORA_T2V_I2V)),
    }
    return jsonify({"ok": True, "comfy_online": comfy_online(),
                    "comfy_queue_running": running, "comfy_queue_pending": pending,
                    "jobs_queued": JOB_QUEUE.qsize(), "models": models})


@app.route("/api/generate", methods=["POST"])
def api_generate():
    body = request.get_json(silent=True) or {}
    prompt = (body.get("prompt") or "").strip()
    if not prompt:
        return jsonify({"error": "prompt 不能为空"}), 400
    mode = body.get("mode", "t2v")
    if mode not in ("t2v", "i2v", "reference", "text-to-video", "image-to-video", "reference-to-video"):
        return jsonify({"error": "mode 必须是 t2v/i2v/reference"}), 400
    mode = {"text-to-video": "t2v", "image-to-video": "i2v", "reference-to-video": "reference"}.get(mode, mode)
    duration = str(body.get("duration", 5)).replace("s", "")
    if duration not in DURATIONS:
        return jsonify({"error": "duration 仅支持 %s 秒" % "/".join(DURATIONS)}), 400
    if not DURATIONS[duration][1]:
        return jsonify({"error": "%s 秒尚未通过真实测试，暂不开放" % duration}), 400
    resolution = str(body.get("resolution", "480p"))
    if resolution not in RESOLUTIONS:
        return jsonify({"error": "resolution 仅支持 %s" % "/".join(RESOLUTIONS)}), 400
    if not RESOLUTIONS[resolution][3]:
        return jsonify({"error": "%s 尚未通过真实 OOM 测试，暂不开放" % resolution}), 400
    aspect = str(body.get("aspect_ratio") or OFFLOAD_STATE.get("aspect_ratio") or DEFAULT_ASPECT)
    if aspect not in ASPECTS:
        return jsonify({"error": "aspect_ratio 仅支持 %s" % "/".join(ASPECTS)}), 400
    w, h = aspect_dims(resolution, aspect)
    frames = DURATIONS[duration][0]
    jid = uuid.uuid4().hex[:12]
    job = {
        "id": jid, "status": "queued", "prompt": prompt, "mode": mode,
        "duration": duration, "resolution": resolution, "aspect_ratio": aspect, "width": w, "height": h,
        "frames": frames, "steps": REF_TURBO_STEPS if mode == "reference" else TURBO_STEPS,
        "seed": int(body.get("seed") or random.randint(0, 2**31 - 1)),
        "created_at": now(), "reference_image": None, "reference_video": None,
    }
    try:
        job["reference_image"] = fetch_reference(body.get("reference_image_url"), "refimg", COMFY_INPUT)
        job["reference_video"] = fetch_reference(body.get("reference_video_url"), "refvid", COMFY_INPUT)
    except Exception as e:
        return jsonify({"error": "参考素材处理失败: %s" % e}), 400
    if mode == "i2v" and not job["reference_image"]:
        return jsonify({"error": "i2v 模式需要 reference_image_url"}), 400
    if mode == "reference" and not (job["reference_image"] or job["reference_video"]):
        return jsonify({"error": "reference 模式需要参考图或参考视频"}), 400

    with JOBS_LOCK:
        JOBS[jid] = job
        job["queue_position"] = JOB_QUEUE.qsize() + 1
    ensure_worker()
    JOB_QUEUE.put(job)
    save_jobs()
    return jsonify(public_job(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
    j = public_job(job)
    if job["status"] == "queued":
        j["queue_position"] = JOB_QUEUE.qsize()
    if job["status"] == "running":
        running, pending = queue_positions()
        j["comfy_queue_running"] = running
        j["comfy_queue_pending"] = pending
    if job["status"] == "error" and job.get("log_tail"):
        j["log_tail"] = job["log_tail"]
    return jsonify(j)


@app.route("/api/jobs")
def api_jobs():
    with JOBS_LOCK:
        vals = sorted(JOBS.values(), key=lambda x: x.get("created", 0), reverse=True)[:30]
    return jsonify({"jobs": [public_job(j) for j in vals], "queue_size": JOB_QUEUE.qsize()})


@app.route("/api/download/<jid>")
def api_download(jid):
    job = JOBS.get(jid)
    if not job or job["status"] != "done" or not job.get("output_file"):
        return jsonify({"error": "video not ready"}), 404
    path = job["output_file"]
    if not os.path.exists(path):
        return jsonify({"error": "file missing"}), 404
    return send_file(path, mimetype="video/mp4", as_attachment=True,
                     download_name="%s.mp4" % jid)


@app.route("/api/upload", methods=["POST"])
def api_upload():
    f = request.files.get("file")
    if not f:
        return jsonify({"error": "file field required"}), 400
    os.makedirs(COMFY_INPUT, exist_ok=True)
    name = "upload_" + uuid.uuid4().hex[:10] + "_" + safe_name(f.filename, ".png")
    dst = os.path.join(COMFY_INPUT, name)
    f.save(dst)
    return jsonify({"ok": True, "filename": name, "size": os.path.getsize(dst),
                    "comfy_input": dst}), 200


@app.route("/api/object_info")
def api_object_info():
    node = request.args.get("node")
    try:
        return jsonify(comfy_object_info(node))
    except Exception as e:
        return jsonify({"error": str(e)}), 502


def run_claude(q):
    msg = q
    env = dict(os.environ)
    env.update({
        "ANTHROPIC_DISABLE_PREFLIGHT": "1",
        "CLAUDE_CAPTURE_STDIO": "1",
        "CLAUDE_MSG": base64.b64encode(msg.encode("utf-8")).decode("ascii"),
    })
    p = subprocess.run(["node", os.path.join(ROOT, "run_claude.js")],
                       cwd=ROOT, env=env, capture_output=True, timeout=900)
    out = (p.stdout or b"").decode("utf-8", "replace").strip()
    err = (p.stderr or b"").decode("utf-8", "replace").strip()
    return out if out else (err or "no output")


@app.route("/ask/claude", methods=["GET", "POST"])
def ask_claude():
    q = request.values.get("q") or (request.get_json(silent=True) or {}).get("q", "")
    if not q:
        return "missing q", 400
    if " " not in q and len(q) >= 50:
        try:
            q = base64.b64decode(q).decode("utf-8")
        except Exception:
            pass
    try:
        return run_claude(q), 200
    except Exception as e:
        return "error: %s" % e, 500


@app.route("/api/file/<name>")
def api_file(name):
    return send_from_directory(COMFY_INPUT, safe_name(name))



@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"], "aspect_ratio": OFFLOAD_STATE.get("aspect_ratio", DEFAULT_ASPECT)})
    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
    if "aspect_ratio" in body:
        _a = str(body["aspect_ratio"])
        if _a not in ASPECTS:
            return jsonify({"error": "aspect_ratio 仅支持 %s" % "/".join(ASPECTS)}), 400
        OFFLOAD_STATE["aspect_ratio"] = _a
    save_settings()
    return jsonify({"enabled": OFFLOAD_STATE["enabled"], "timeout_minutes": OFFLOAD_STATE["timeout_minutes"], "aspect_ratio": OFFLOAD_STATE.get("aspect_ratio", DEFAULT_ASPECT)})


@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(COMFY_OUTPUT, exist_ok=True)
    os.makedirs(COMFY_INPUT, exist_ok=True)
    os.makedirs(DATA_DIR, exist_ok=True)
    os.makedirs(UPLOADS, exist_ok=True)
    load_jobs()
    load_settings()
    ensure_worker()
    ensure_offload_watchdog()
    app.run(host="0.0.0.0", port=WEBAPP_PORT, threaded=True, debug=False)


if __name__ == "__main__":
    main()
