# -*- coding: utf-8 -*-
"""
慈龙 · 一键拉取 AI 模型（跨平台脚本）
======================================
客户装完 Ollama 引擎后，双击本脚本即可自动拉取慈龙比龙7 所需的本地模型：
  - qwen2.5:1.5b  轻量版（约 1GB，日常够用，默认）
  - qwen2.5:3b    中间档（约 2GB，复杂任务自动切用）

设计原则（对齐一键安装器，吴总铁律）：
  1. 多源交替：国内镜像失败自动切官方源，绝不放弃。
  2. 边拉边显进度，失败自动换源重试。
  3. 全自动完成，客户零知识。

用法：
  双击运行，或命令行：
    python 拉取慈龙模型.py            # 拉默认 1.5b + 3b
    python 拉取慈龙模型.py 7b         # 额外拉旗舰版 7b（约 4.7GB）
"""
import os
import sys
import time
import shutil
import subprocess

MODELS = ["qwen2.5:1.5b", "qwen2.5:3b"]
UPGRADE = "qwen2.5:7b"

# 多源交替（国内镜像优先，失败切官方）
SOURCES = [
    {"name": "国内镜像源", "env": {}},
    {"name": "官方源", "env": {}},
    {"name": "国内备用镜像", "env": {"OLLAMA_REGISTRY": "docker.m.daocloud.io"}},
]


def log(msg):
    line = "[%s] %s" % (time.strftime("%H:%M:%S"), msg)
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        print(line, flush=True)
    except Exception:
        try:
            print(line, flush=True)
        except Exception:
            pass


def find_ollama():
    exe = shutil.which("ollama")
    if exe:
        return exe
    # Windows 常见安装路径
    for c in [
        os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "Ollama", "ollama.exe"),
        r"C:\Program Files\Ollama\ollama.exe",
    ]:
        if c and os.path.exists(c):
            return c
    return None


def model_present(name, exe):
    try:
        out = subprocess.run([exe, "list"], capture_output=True, timeout=30)
        txt = (out.stdout or b"").decode("utf-8", "ignore")
        return name.split(":")[0] in txt
    except Exception:
        return False


def pull_model(exe, name, max_rounds=999):
    if model_present(name, exe):
        log("模型已存在，跳过: %s" % name)
        return True
    round_no = 0
    while round_no < max_rounds:
        round_no += 1
        for src in SOURCES:
            log("第 %d 轮 · 尝试%s · %s" % (round_no, src["name"], name))
            try:
                env = dict(os.environ)
                env.update(src.get("env") or {})
                proc = subprocess.Popen([exe, "pull", name],
                                        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                        env=env, text=False)
                for raw in proc.stdout:
                    try:
                        line = raw.decode("utf-8", "ignore").strip()
                        if line:
                            log("  " + line[:80])
                    except Exception:
                        pass
                proc.wait()
                if proc.returncode == 0 and model_present(name, exe):
                    log("模型下载成功: %s" % name)
                    return True
                log("%s 返回码 %s，换源" % (src["name"], proc.returncode))
            except Exception as e:
                log("%s 失败: %s" % (src["name"], e))
            time.sleep(3)
        log("一轮源均未成功，进入下一轮重试")
        time.sleep(5)
    return False


def main():
    print("=" * 50)
    print("  慈龙 · 一键拉取 AI 模型")
    print("=" * 50)
    exe = find_ollama()
    if not exe:
        print()
        print("[错误] 未检测到 Ollama 引擎。")
        print("请先安装 Ollama：")
        print("  https://ollama.com/download/OllamaSetup.exe")
        print()
        input("按回车键退出...")
        return 1
    log("已找到 Ollama: %s" % exe)

    targets = list(MODELS)
    if len(sys.argv) > 1 and sys.argv[1].lower() in ("7b", "all", "full"):
        targets.append(UPGRADE)

    print()
    print("将拉取模型：%s" % ", ".join(targets))
    print("请保持联网，首次下载需要一段时间。")
    print("-" * 50)

    ok_all = True
    for m in targets:
        print()
        if not pull_model(exe, m):
            log("模型拉取失败: %s" % m)
            ok_all = False

    print()
    print("=" * 50)
    log("拉取完成，当前本地模型清单：")
    subprocess.run([exe, "list"])
    if ok_all:
        print()
        print("全部模型就绪，可以启动慈龙比龙7 开始使用。")
    else:
        print()
        print("部分模型未成功，请检查网络后重新运行本脚本。")
    print("=" * 50)
    input("按回车键退出...")
    return 0 if ok_all else 1


if __name__ == "__main__":
    sys.exit(main())
