# -*- coding: utf-8 -*-
"""ComfyUI 后端生命周期 + 生成流程(与 UI 完全解耦)。"""
import os
import re
import time
import uuid
import random
import threading
import subprocess
from pathlib import Path

import requests

from .config import (Config, OUTPUT_DIR, available_memory_gb,
                     missing_models)
from .workflow import build_workflow


class ComfyUIError(RuntimeError):
    """ComfyUI 启动/生成过程中的可读异常。"""


def safe_filename(text, max_len=80):
    """把提示词清洗成跨平台合法文件名(去路径非法字符、控制符、限长)。"""
    text = (text or "").strip()
    text = re.sub(r"\s+", " ", text)
    text = re.sub(r'[\\/:*?"<>|\x00-\x1f]', "", text)
    text = text.strip(". ")
    return text[:max_len] if text else "SwiftCanvas"


def random_seed():
    return random.randint(0, 2 ** 53)


class ComfyUIManager:
    """管理 ComfyUI 子进程的启动、就绪探测与停止。"""

    def __init__(self, config=None):
        self.cfg = config or Config()
        self._proc = None
        self._lock = threading.Lock()
        self._log_path = self.cfg.root / "comfyui.log"
        self._log_file = None

    def log_tail(self, limit=1500):
        """读取后端日志末尾,用于把启动失败原因直接显示给用户。"""
        try:
            return self._log_path.read_text(encoding="utf-8", errors="replace")[-limit:]
        except Exception:
            return ""

    @property
    def url(self):
        return f"http://127.0.0.1:{self.cfg.comfy_port}"

    def is_running(self, timeout=5):
        try:
            r = requests.get(f"{self.url}/system_stats", timeout=timeout)
            return r.status_code == 200
        except Exception:
            return False

    def start(self):
        """若后端未运行则启动它;返回是否本次新启动。"""
        with self._lock:
            if self.is_running():
                return False
            main_py = self.cfg.comfy_dir / "main.py"
            if not main_py.is_file():
                raise ComfyUIError(
                    f"未找到 ComfyUI:{main_py}\n请先运行安装脚本(见 README 的「快速开始」)。")
            miss = missing_models()
            if miss:
                raise ComfyUIError("缺少模型文件,请先运行下载脚本:\n  " + "\n  ".join(miss))

            py = os.sys.executable  # 复用当前解释器(已含 torch/gradio 的环境)
            env = os.environ.copy()
            # 关键:本机代理会让访问 127.0.0.1 的启动自检走代理导致 502;放行本地地址即可,
            # 不清空用户代理(用户可能仍需代理下载模型)。
            no_proxy = ",".join(filter(None, [env.get("NO_PROXY", ""), "localhost,127.0.0.1"]))
            env["NO_PROXY"] = no_proxy
            env["no_proxy"] = no_proxy.lower()
            env.setdefault("HF_ENDPOINT", "https://hf-mirror.com")

            avail = available_memory_gb()
            if avail and avail < 16:
                print(f"[警告] 当前可用内存约 {avail:.1f}GB,低于建议的 16GB。"
                      "文本编码器约 9GB 会常驻内存,内存不足会严重换页。", flush=True)

            if self._log_file is not None:
                try:
                    self._log_file.close()
                except Exception:
                    pass
            logf = open(self._log_path, "w", encoding="utf-8")
            self._log_file = logf
            cmd = [py, "-s", str(main_py), "--disable-auto-launch",
                   "--listen", "127.0.0.1", "--port", str(self.cfg.comfy_port)]
            if getattr(self.cfg, "cpu_only", False):
                # 纯 CPU 模式:无 NVIDIA 显卡时强制全部计算走 CPU(ComfyUI 官方 --cpu)。
                cmd.append("--cpu")
            elif self.cfg.lowvram:
                cmd.append("--lowvram")
            creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
            self._proc = subprocess.Popen(
                cmd, cwd=str(self.cfg.comfy_dir), env=env,
                stdout=logf, stderr=subprocess.STDOUT, creationflags=creationflags)
            return True

    def wait_ready(self, timeout=420, on_tick=None):
        """轮询等待后端就绪。"""
        t0 = time.time()
        while time.time() - t0 < timeout:
            if self.is_running():
                return True
            # 进程提前退出(缺依赖、端口冲突等)时立刻报错,不再空等 7 分钟。
            if self._proc is not None and self._proc.poll() is not None:
                raise ComfyUIError(
                    f"ComfyUI 启动失败(进程已退出,代码 {self._proc.returncode})。"
                    f"请查看日志:{self._log_path}\n{self.log_tail()}")
            if on_tick:
                on_tick(int(time.time() - t0))
            time.sleep(1)
        return False

    def ensure_ready(self, timeout=420, on_tick=None):
        """确保后端可用:需要时启动并等待。"""
        self.start()
        if not self.wait_ready(timeout, on_tick):
            raise ComfyUIError(
                f"ComfyUI 在 {timeout}s 内未就绪。请查看日志:{self._log_path}\n{self.log_tail()}")

    def stop(self):
        with self._lock:
            if self._log_file is not None:
                try:
                    self._log_file.close()
                except Exception:
                    pass
                self._log_file = None
            if self._proc is not None:
                try:
                    self._proc.terminate()
                    try:
                        self._proc.wait(timeout=10)
                    except Exception:
                        self._proc.kill()
                except Exception:
                    pass
                self._proc = None
                return True
            return False


_manager = None
_manager_lock = threading.Lock()


def get_manager(config=None):
    """全局单例(Web 与 CLI 共用,避免重复启动后端)。"""
    global _manager
    if _manager is None:
        with _manager_lock:
            if _manager is None:
                _manager = ComfyUIManager(config)
    return _manager


def _submit(url, workflow):
    r = requests.post(f"{url}/prompt",
                      json={"prompt": workflow, "client_id": str(uuid.uuid4())},
                      timeout=60)
    if r.status_code != 200:
        raise ComfyUIError(f"提交工作流失败(HTTP {r.status_code}):{r.text[:600]}")
    data = r.json()
    if data.get("node_errors"):
        raise ComfyUIError(f"工作流节点校验失败:{str(data['node_errors'])[:600]}")
    pid = data.get("prompt_id")
    if not pid:
        raise ComfyUIError(f"后端未返回 prompt_id:{r.text[:600]}")
    return pid


def _wait_result(url, pid, timeout=1800, on_tick=None):
    t0 = time.time()
    while time.time() - t0 < timeout:
        try:
            history = requests.get(f"{url}/history/{pid}", timeout=10).json()
        except Exception:
            time.sleep(3)
            continue
        entry = history.get(pid)
        if entry:
            status = entry.get("status", {})
            if status.get("completed") is False and status.get("status_str") == "error":
                msgs = status.get("messages", [])
                raise ComfyUIError(f"生成失败:{str(msgs)[:800]}")
            return entry
        if on_tick:
            on_tick(int(time.time() - t0))
        time.sleep(3)
    raise ComfyUIError(f"生成超时({timeout // 60} 分钟),可尝试更小尺寸或检查后端日志。")


def _fetch_images(url, result, out_dir, base_name):
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    ts = time.strftime("%Y%m%d_%H%M%S")
    saved = []
    for node_out in result.get("outputs", {}).values():
        for image in node_out.get("images", []):
            filename = image.get("filename")
            if not filename:
                continue
            try:
                r = requests.get(f"{url}/view", params={
                    "filename": filename,
                    "subfolder": image.get("subfolder", ""),
                    "type": image.get("type", "output"),
                }, timeout=60)
                if r.status_code != 200:
                    continue
                ext = filename.rsplit(".", 1)[-1] if "." in filename else "png"
                path = out_dir / f"{base_name}_{ts}_{len(saved) + 1}.{ext}"
                path.write_bytes(r.content)
                saved.append(path)
            except Exception:
                continue
    return saved


def generate(prompt, negative="", size="1024x1024", steps=4, cfg=1.0,
             seed_rand=True, seed_value=0, manager=None, on_status=None,
             output_dir=None, timeout=None):
    """端到端生成:确保后端就绪 → 提交 → 等待 → 取图保存。

    Returns:
        (图片路径列表, 状态说明)
    """
    if not (prompt or "").strip():
        return [], "请先输入正向提示词。"

    mgr = manager or get_manager()
    cpu_only = bool(getattr(mgr.cfg, "cpu_only", False))
    if timeout is None:
        # 纯 CPU 单张 512x512 实测约 10-17 分钟,慢机器可能更久,给足 60 分钟。
        timeout = 3600 if cpu_only else 1800
    try:
        if not mgr.is_running():
            if on_status:
                on_status("正在启动 ComfyUI 后端(首次加载模型约 1-3 分钟)…")
            mgr.ensure_ready(on_tick=lambda s: on_status and on_status(
                f"正在启动后端… {s}s"))
    except ComfyUIError as e:
        return [], str(e)

    try:
        width, height = (int(x) for x in size.lower().split("x"))
    except Exception:
        width, height = 1024, 1024

    seed = random_seed() if seed_rand else (int(seed_value) if seed_value else random_seed())

    if on_status:
        on_status(f"已提交任务,正在生成({width}x{height}, {int(steps)} 步)…")
    try:
        pid = _submit(mgr.url, build_workflow(prompt, negative, steps, cfg,
                                              width, height, seed))
        result = _wait_result(mgr.url, pid, timeout=timeout,
                              on_tick=lambda s: on_status and on_status(
                                  f"生成中… {s}s({'纯 CPU 模式偏慢属正常' if cpu_only else '低显存模式偏慢属正常'})"))
        if on_status:
            on_status("解码图像…")
        dest = output_dir or OUTPUT_DIR
        images = _fetch_images(mgr.url, result, dest, safe_filename(prompt))
    except ComfyUIError as e:
        return [], str(e)
    except Exception as e:
        return [], f"生成过程出错:{e}"

    if not images:
        return [], "出图完成但未取到图像,请查看后端日志。"
    names = "、".join(p.name for p in images)
    return images, f"完成(种子={seed}),已保存:{names}"