#!/usr/bin/env python3
"""Alfred Sovereign GPU Model Catalog, Background Puller & Auto-Tune Activator."""
import importlib.machinery, importlib.util, json, os, re, signal, subprocess, sys, time

MODELS_DIR = "/var/lib/alfred-gpu/models"
ACTIVE_JSON = "/var/lib/alfred-gpu/active_model.json"
DL_STATE_DIR = "/var/lib/alfred-gpu/downloads"
UNIT_PATH = "/etc/systemd/system/alfred-llama-gpu.service"

# Load autotune helper cleanly
loader = importlib.machinery.SourceFileLoader("autotune", "/usr/local/bin/alfred-gpu-autotune")
spec = importlib.util.spec_from_loader(loader.name, loader)
autotune = importlib.util.module_from_spec(spec)
loader.exec_module(autotune)

CATALOG = [
    {
        "id": "qwen3.5-35b-a3b",
        "name": "Qwen 3.5 35B-A3B Uncensored Heretic v2 (Native-MTP + Vision)",
        "family": "Sparse MoE (35B Total / 3B Active • Uncensored + Vision)",
        "tier": "Flagship Daily Driver (41.6 tok/s + 1.1s Vision)",
        "filename": "Qwen3.5-35B-A3B-uncensored-heretic-v2-Native-MTP-Preserved-Q4_K_S.gguf",
        "mmproj": "Qwen3.5-35B-A3B-uncensored-heretic-mmproj-BF16.gguf",
        "size_gb": 20.43,
        "is_moe": True,
        "is_embed": False,
        "url": "https://huggingface.co/llmfan46/Qwen3.5-35B-A3B-uncensored-heretic-v2-Native-MTP-Preserved-GGUF/resolve/main/Qwen3.5-35B-A3B-uncensored-heretic-v2-Native-MTP-Preserved-Q4_K_S.gguf",
        "desc": "Uncensored 35B MoE + Native MTP speculative decoding (41.6 tok/s, 87.8% accept) + BF16 Vision (1.1s) on RTX 4060 8GB!",
        "custom_flags": [
            "--device", "CUDA0", "-ngl", "99",
            "-ot", ".ffn_.*_exps.=CPU",
            "--load-mode", "none", "--moe-cache-mib", "2400",
            "-t", "8", "-tb", "12", "-fa", "on", "-ctk", "q8_0", "-ctv", "q8_0",
            "-c", "65536", "-np", "2",
            "--spec-type", "draft-mtp", "--spec-draft-n-max", "3",
            "--reasoning-budget", "768", "--jinja", "--no-ui"
        ],
    },
    {
        "id": "qwen3-coder-next-80b",
        "name": "Qwen 3 Coder Next 80B-A3B Uncensored Heretic (Q3_K_M)",
        "family": "Sparse MoE (80B Total / 3B Active • 512 Experts • Uncensored)",
        "tier": "Heavy Frontier Coding Specialist (16.5 tok/s)",
        "filename": "Qwen3-Coder-Next-Uncensored-Heretic-Q3_K_M.gguf",
        "size_gb": 37.95,
        "is_moe": True,
        "is_embed": False,
        "url": "https://huggingface.co/llmfan46/Qwen3-Coder-Next-Uncensored-Heretic-GGUF/resolve/main/Qwen3-Coder-Next-Uncensored-Heretic-Q3_K_M.gguf",
        "desc": "80B unrestricted frontier coder (512 experts, 3B active) tuned for RTX 4060 8GB + 62GB DDR5 (16.5 tok/s, 4.7s tools, 32K ctx).",
        "custom_flags": [
            "--device", "CUDA0", "-ngl", "99",
            "-ot", ".ffn_.*_exps.=CPU",
            "-ot", "token_embd\\.weight=CPU",
            "-ot", "ffn_.*_shexp=CPU",
            "--load-mode", "none", "--moe-cache-mib", "0",
            "-t", "8", "-tb", "12", "-fa", "on", "-ctk", "q8_0", "-ctv", "q8_0",
            "-c", "32768", "-np", "1", "--jinja", "--no-ui"
        ],
    },
    {
        "id": "qwen3.5-35b-censored-legacy",
        "name": "Qwen 3.5 35B-A3B (Unsloth Dynamic 4-bit MoE)",
        "family": "Sparse MoE (35B Total / 3B Active)",
        "tier": "Flagship All-Rounder + Agents",
        "filename": "Qwen3.5-35B-A3B-UD-IQ4_XS.gguf",
        "size_gb": 16.29,
        "is_moe": True,
        "is_embed": False,
        "url": "https://huggingface.co/unsloth/Qwen3.5-35B-A3B-GGUF/resolve/main/Qwen3.5-35B-A3B-UD-IQ4_XS.gguf",
        "desc": "Best speed-to-intelligence ratio on 8GB-32GB GPUs + 32GB+ RAM (~34 tok/s on RTX 4060 8GB!).",
    },
    {
        "id": "qwen3-coder-30b-a3b",
        "name": "Qwen 3 Coder 30B-A3B (Unsloth Q4_K_XL MoE)",
        "family": "Sparse MoE (30B Total / 3B Active)",
        "tier": "Specialist Coding & Tool Calling",
        "filename": "Qwen3-Coder-30B-A3B-Instruct-UD-Q4_K_XL.gguf",
        "size_gb": 16.50,
        "is_moe": True,
        "is_embed": False,
        "url": "https://huggingface.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF/resolve/main/Qwen3-Coder-30B-A3B-Instruct-UD-Q4_K_XL.gguf",
        "desc": "Dedicated coding & Cursor/Cline agent powerhouse with 3B active experts per token.",
    },
    {
        "id": "deepseek-r1-qwen3-8b",
        "name": "DeepSeek-R1 0528 Qwen3 8B (Q4_K_M)",
        "family": "Dense 8B Reasoning",
        "tier": "100% VRAM Ultra-Fast Reasoning",
        "filename": "DeepSeek-R1-0528-Qwen3-8B-Q4_K_M.gguf",
        "size_gb": 5.03,
        "is_moe": False,
        "is_embed": False,
        "url": "https://huggingface.co/unsloth/DeepSeek-R1-0528-Qwen3-8B-GGUF/resolve/main/DeepSeek-R1-0528-Qwen3-8B-Q4_K_M.gguf",
        "desc": "Fits 100% inside 8GB RTX 4060 VRAM for 70-110+ tok/s deep reasoning & instant chat.",
    },
    {
        "id": "qwen3-32b-q4",
        "name": "Qwen 3 32B Dense (Q4_K_M)",
        "family": "Dense 32B Flagship",
        "tier": "RTX 5090 (32GB) Full-VRAM Sweet Spot",
        "filename": "Qwen3-32B-Q4_K_M.gguf",
        "size_gb": 19.76,
        "is_moe": False,
        "is_embed": False,
        "url": "https://huggingface.co/Qwen/Qwen3-32B-GGUF/resolve/main/Qwen3-32B-Q4_K_M.gguf",
        "desc": "Dense 32B reasoning & coding flagship; runs 100% in VRAM on 24GB-32GB GPUs (RTX 4090/5090).",
    },
    {
        "id": "llama-3.3-70b-iq4",
        "name": "Llama 3.3 70B Instruct (IQ4_XS)",
        "family": "Dense 70B Enterprise",
        "tier": "RTX 5090 (32GB) + 64GB RAM",
        "filename": "Llama-3.3-70B-Instruct-IQ4_XS.gguf",
        "size_gb": 37.60,
        "is_moe": False,
        "is_embed": False,
        "url": "https://huggingface.co/bartowski/Llama-3.3-70B-Instruct-GGUF/resolve/main/Llama-3.3-70B-Instruct-IQ4_XS.gguf",
        "desc": "Meta 70B frontier model; ideal on RTX 5090 32GB + 64GB RAM or dual-GPU servers.",
    },
    {
        "id": "nomic-embed-text-v1.5",
        "name": "Nomic Embed Text v1.5 (Q8_0)",
        "family": "Embeddings (768-dim RAG)",
        "tier": "RAG & Vector Search",
        "filename": "nomic-embed-text-v1.5.Q8_0.gguf",
        "size_gb": 0.15,
        "is_moe": False,
        "is_embed": True,
        "url": "https://huggingface.co/nomic-ai/nomic-embed-text-v1.5-GGUF/resolve/main/nomic-embed-text-v1.5.Q8_0.gguf",
        "desc": "Ultra-fast local vector embeddings for RAG pipelines, knowledge bases, and semantic search.",
    },
]

def pid_alive(pid: int) -> bool:
    if pid <= 1:
        return False
    try:
        os.kill(pid, 0)
        return True
    except OSError:
        return False

def get_active_info():
    if os.path.exists(ACTIVE_JSON):
        try:
            return json.load(open(ACTIVE_JSON))
        except Exception:
            pass
    # Parse current systemd unit as fallback
    active_file = "Qwen3.5-35B-A3B-UD-IQ4_XS.gguf"
    active_id = "qwen3.5-35b-a3b"
    if os.path.exists(UNIT_PATH):
        txt = open(UNIT_PATH).read()
        m_f = re.search(r"-m\s+(\S+)", txt)
        m_a = re.search(r"--alias\s+(\S+)", txt)
        if m_f:
            active_file = os.path.basename(m_f.group(1))
        if m_a:
            active_id = m_a.group(1)
    return {"id": active_id, "filename": active_file}

def get_dl_status(model_id: str, filename: str, target_gb: float):
    st_path = os.path.join(DL_STATE_DIR, f"{model_id}.json")
    part_path = os.path.join(MODELS_DIR, filename + ".part")
    final_path = os.path.join(MODELS_DIR, filename)
    if os.path.exists(st_path):
        try:
            st = json.load(open(st_path))
            pid = int(st.get("pid", 0))
            if pid_alive(pid):
                cur_bytes = os.path.getsize(part_path) if os.path.exists(part_path) else (os.path.getsize(final_path) if os.path.exists(final_path) else 0)
                cur_gb = round(cur_bytes / 1073741824.0, 2)
                pct = min(99.5, round((cur_gb / max(target_gb, 0.05)) * 100.0, 1))
                return {"downloading": True, "pid": pid, "downloaded_gb": cur_gb, "pct": pct, "started_at": st.get("started_at", 0)}
            else:
                try: os.remove(st_path)
                except OSError: pass
        except Exception:
            pass
    return {"downloading": False, "pid": 0, "downloaded_gb": 0.0, "pct": 0.0}

def find_llama_env():
    # Detect installed llama-server binary (Ollama CUDA 13 bundle or standalone llama.cpp)
    candidates = [
        ("/opt/llama-inkling/bin/llama-server", "/opt/llama-inkling/bin",
         "/opt/llama-inkling/bin:/usr/lib/x86_64-linux-gnu/nvidia/610.57.04:/usr/lib/x86_64-linux-gnu"),
        ("/usr/local/lib/ollama/llama-server", "/usr/local/lib/ollama/cuda_v13",
         "/usr/local/lib/ollama:/usr/local/lib/ollama/cuda_v13:/usr/lib/x86_64-linux-gnu/nvidia/610.57.04:/usr/lib/x86_64-linux-gnu"),
        ("/usr/local/bin/llama-server", "/usr/local/bin", "/usr/local/lib:/usr/lib/x86_64-linux-gnu"),
    ]
    for bin_p, wd, ld in candidates:
        if os.path.isfile(bin_p) and os.access(bin_p, os.X_OK):
            # Dynamically include any /usr/lib/x86_64-linux-gnu/nvidia/* directory present
            nv_base = "/usr/lib/x86_64-linux-gnu/nvidia"
            extra = []
            if os.path.isdir(nv_base):
                for d in sorted(os.listdir(nv_base)):
                    full = os.path.join(nv_base, d)
                    if os.path.isdir(full):
                        extra.append(full)
            ld_parts = [p for p in (ld.split(":") + extra) if os.path.isdir(p)]
            seen = []
            for p in ld_parts:
                if p not in seen: seen.append(p)
            return bin_p, wd if os.path.isdir(wd) else "/var/lib/alfred-gpu", ":".join(seen)
    return "/usr/local/lib/ollama/llama-server", "/usr/local/lib/ollama/cuda_v13", "/usr/local/lib/ollama:/usr/local/lib/ollama/cuda_v13"

def cmd_list():
    os.makedirs(MODELS_DIR, exist_ok=True)
    os.makedirs(DL_STATE_DIR, exist_ok=True)
    hw = autotune.detect_hardware()
    active = get_active_info()
    known_files = set()
    items = []
    for m in CATALOG:
        known_files.add(m["filename"])
        fpath = os.path.join(MODELS_DIR, m["filename"])
        dl = get_dl_status(m["id"], m["filename"], m["size_gb"])
        installed = os.path.isfile(fpath) and (not dl["downloading"]) and os.path.getsize(fpath) > 10_000_000
        disk_gb = round(os.path.getsize(fpath) / 1073741824.0, 2) if installed else dl["downloaded_gb"]
        plan = autotune.recommend_for_model(hw, m["size_gb"], m["is_moe"], m["is_embed"])
        items.append({
            **m,
            "installed": installed,
            "disk_gb": disk_gb,
            "active": (active.get("id") == m["id"] or active.get("filename") == m["filename"]),
            "download": dl,
            "autotune": plan,
        })

    # Include any custom user-dropped .gguf files in /var/lib/alfred-gpu/models
    for fn in sorted(os.listdir(MODELS_DIR)):
        if fn.endswith(".gguf") and fn not in known_files and "mmproj" not in fn.lower():
            fp = os.path.join(MODELS_DIR, fn)
            sz_gb = round(os.path.getsize(fp) / 1073741824.0, 2)
            cid = re.sub(r"[^a-zA-Z0-9_.\-]", "-", fn[:-5].lower())[:48]
            is_moe = any(k in fn.lower() for k in ("a3b", "moe", "mixtral", "qwen3.5-35b", "qwen3-30b", "qwen3-coder-30b"))
            plan = autotune.recommend_for_model(hw, sz_gb, is_moe, "embed" in fn.lower())
            items.append({
                "id": cid,
                "name": fn[:-5],
                "family": "Custom Local GGUF",
                "tier": "User Imported Model",
                "filename": fn,
                "size_gb": sz_gb,
                "is_moe": is_moe,
                "is_embed": "embed" in fn.lower(),
                "url": "",
                "desc": "Custom GGUF model stored in /var/lib/alfred-gpu/models/.",
                "installed": True,
                "disk_gb": sz_gb,
                "active": (active.get("id") == cid or active.get("filename") == fn),
                "download": {"downloading": False, "pid": 0, "downloaded_gb": sz_gb, "pct": 100.0},
                "autotune": plan,
            })

    print(json.dumps({"ok": True, "hardware": hw, "active": active, "models": items}, indent=2))

def cmd_pull(model_id: str, custom_url: str = "", custom_moe: bool = False):
    os.makedirs(MODELS_DIR, exist_ok=True)
    os.makedirs(DL_STATE_DIR, exist_ok=True)
    entry = next((m for m in CATALOG if m["id"] == model_id), None)
    if entry:
        url = entry["url"]
        fn = entry["filename"]
    elif custom_url.startswith("https://") and ".gguf" in custom_url.lower():
        url = custom_url
        fn = re.sub(r"[^a-zA-Z0-9_.\-]", "_", os.path.basename(custom_url.split("?")[0]))
        if not fn.endswith(".gguf"):
            fn += ".gguf"
        model_id = re.sub(r"[^a-zA-Z0-9_.\-]", "-", model_id.lower()) or fn[:-5].lower()
    else:
        print(json.dumps({"ok": False, "error": f"Unknown model_id '{model_id}' or invalid HTTPS GGUF URL."}))
        sys.exit(1)

    st_path = os.path.join(DL_STATE_DIR, f"{model_id}.json")
    part_path = os.path.join(MODELS_DIR, fn + ".part")
    final_path = os.path.join(MODELS_DIR, fn)
    log_path = os.path.join(DL_STATE_DIR, f"{model_id}.log")

    if os.path.exists(st_path):
        try:
            old_pid = int(json.load(open(st_path)).get("pid", 0))
            if pid_alive(old_pid):
                print(json.dumps({"ok": True, "message": f"Download already running (PID {old_pid}).", "pid": old_pid}))
                return
        except Exception:
            pass

    wrapper = f"curl -fL --retry 5 --retry-delay 3 -C - {json.dumps(url)} -o {json.dumps(part_path)} && mv -f {json.dumps(part_path)} {json.dumps(final_path)} && rm -f {json.dumps(st_path)}"
    log_fh = open(log_path, "ab")
    proc = subprocess.Popen(
        ["bash", "-c", wrapper],
        stdout=log_fh, stderr=log_fh, stdin=subprocess.DEVNULL,
        start_new_session=True
    )
    with open(st_path, "w") as f:
        json.dump({"id": model_id, "filename": fn, "url": url, "pid": proc.pid, "started_at": int(time.time())}, f)
    print(json.dumps({"ok": True, "message": f"Started background download of {fn}", "pid": proc.pid, "id": model_id}))

def cmd_cancel(model_id: str):
    st_path = os.path.join(DL_STATE_DIR, f"{model_id}.json")
    if os.path.exists(st_path):
        st = json.load(open(st_path))
        pid = int(st.get("pid", 0))
        if pid_alive(pid):
            try:
                os.killpg(os.getpgid(pid), signal.SIGTERM)
            except Exception:
                try: os.kill(pid, signal.SIGTERM)
                except Exception: pass
        part_p = os.path.join(MODELS_DIR, st.get("filename", "") + ".part")
        if os.path.isfile(part_p):
            os.remove(part_p)
        os.remove(st_path)
    print(json.dumps({"ok": True, "message": f"Cancelled download for {model_id}."}))

def cmd_activate(model_id: str):
    entry = next((m for m in CATALOG if m["id"] == model_id), None)
    if entry:
        fn = entry["filename"]
        is_moe = entry["is_moe"]
        is_embed = entry["is_embed"]
    else:
        # Look for custom file matching id
        fn = None
        for f in os.listdir(MODELS_DIR):
            if f.endswith(".gguf") and (f[:-5].lower() == model_id.lower() or re.sub(r"[^a-zA-Z0-9_.\-]", "-", f[:-5].lower())[:48] == model_id.lower()):
                fn = f
                break
        if not fn:
            print(json.dumps({"ok": False, "error": f"Model '{model_id}' not found on disk."}))
            sys.exit(1)
        is_moe = any(k in fn.lower() for k in ("a3b", "moe", "mixtral", "35b", "30b"))
        is_embed = "embed" in fn.lower()

    fpath = os.path.join(MODELS_DIR, fn)
    if not os.path.isfile(fpath) or os.path.getsize(fpath) < 10_000_000:
        print(json.dumps({"ok": False, "error": f"Model file {fn} is not downloaded yet. Click Pull first."}))
        sys.exit(1)

    hw = autotune.detect_hardware()
    sz_gb = round(os.path.getsize(fpath) / 1073741824.0, 2)
    plan = autotune.recommend_for_model(hw, sz_gb, is_moe, is_embed)
    if plan["fit_level"] == "blocked":
        print(json.dumps({"ok": False, "error": f"Hardware Auto-Tuner blocked activation: {plan['summary']}"}))
        sys.exit(1)

    bin_p, wd, ld = find_llama_env()
    use_flags = list(entry.get("custom_flags") or plan["extra_flags"]) if entry else list(plan["extra_flags"])
    mm_part = ""
    if entry and entry.get("mmproj"):
        mm_path = os.path.join(MODELS_DIR, entry["mmproj"])
        if os.path.isfile(mm_path):
            mm_part = f" --mmproj {mm_path}"
    flags_str = " ".join(f'"{x}"' if any(c in x for c in " .*$\\") else x for x in use_flags)
    unit = f"""[Unit]
Description=Alfred Sovereign CUDA 13 Inference Engine ({model_id})
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory={wd}
Environment="LD_LIBRARY_PATH={ld}"
ExecStartPre=-/usr/local/bin/alfred-gpu-unload-ollama.sh
ExecStart={bin_p} -m {fpath}{mm_part} --alias {model_id} --host 127.0.0.1 --port 18090 {flags_str}
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
"""
    with open(UNIT_PATH, "w") as f:
        f.write(unit)
    with open(ACTIVE_JSON, "w") as f:
        json.dump({
            "id": model_id,
            "filename": fn,
            "size_gb": sz_gb,
            "is_moe": is_moe,
            "is_embed": is_embed,
            "plan": plan,
            "updated_at": int(time.time()),
        }, f, indent=2)

    subprocess.check_call(["systemctl", "daemon-reload"])
    subprocess.check_call(["systemctl", "enable", "--now", "alfred-llama-gpu.service"])
    subprocess.check_call(["systemctl", "restart", "alfred-llama-gpu.service"])
    print(json.dumps({"ok": True, "message": f"Auto-tuned & activated {model_id} ({plan['summary']})", "plan": plan}))

def cmd_delete(model_id: str):
    active = get_active_info()
    entry = next((m for m in CATALOG if m["id"] == model_id), None)
    fn = entry["filename"] if entry else None
    if not fn:
        for f in os.listdir(MODELS_DIR):
            if f.endswith(".gguf") and re.sub(r"[^a-zA-Z0-9_.\-]", "-", f[:-5].lower())[:48] == model_id.lower():
                fn = f
                break
    if not fn:
        print(json.dumps({"ok": False, "error": "Model file not found."}))
        sys.exit(1)
    if active.get("id") == model_id or active.get("filename") == fn:
        print(json.dumps({"ok": False, "error": "Cannot delete the currently active model. Activate another model first."}))
        sys.exit(1)
    fp = os.path.join(MODELS_DIR, fn)
    if os.path.isfile(fp):
        os.remove(fp)
    print(json.dumps({"ok": True, "message": f"Deleted {fn} and reclaimed disk space."}))

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: alfred-gpu-models {list|pull <id>|pull-url <id> <https_url>|cancel <id>|activate <id>|delete <id>}")
        sys.exit(1)
    op = sys.argv[1]
    if op == "list": cmd_list()
    elif op == "pull": cmd_pull(sys.argv[2])
    elif op == "pull-url": cmd_pull(sys.argv[2], sys.argv[3])
    elif op == "cancel": cmd_cancel(sys.argv[2])
    elif op == "activate": cmd_activate(sys.argv[2])
    elif op == "delete": cmd_delete(sys.argv[2])
    else:
        print(json.dumps({"ok": False, "error": f"Unknown op: {op}"}))
        sys.exit(1)
