#!/usr/bin/env bash
set -euo pipefail

if ! command -v mimo >/dev/null 2>&1; then
  echo "MiMo Code CLI was not found on PATH. Install MiMo Code, open a new terminal, and run this installer again." >&2
  exit 127
fi
mimo_version="$(mimo --version 2>/dev/null | head -n1)" || true
mimo_version="${mimo_version:-(installed)}"
printf 'Detected MiMo Code: %s\n' "${mimo_version}"
if ! command -v python3 >/dev/null 2>&1; then
  echo "Python 3 is required to safely merge the MiMo Code config. Install Python 3 and run this installer again. No config changes were made." >&2
  exit 127
fi

CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/mimocode"
CONFIG_FILE="$CONFIG_DIR/mimocode.json"

python3 - "$CONFIG_FILE" <<'PY'
import json, os, shutil, subprocess, sys, urllib.request


def fetch_json(url):
    req = urllib.request.Request(url, method="GET")
    req.add_header("User-Agent", "curl/8.0")
    try:
        with urllib.request.urlopen(req, timeout=20) as response:
            return json.load(response)
    except Exception:
        raw = subprocess.run(["curl", "-fsSL", "--max-time", "20", url], capture_output=True, check=True).stdout
        return json.loads(raw)
from datetime import datetime, timezone

path = sys.argv[1]
installable_model_ids = {
    "gpt-6-astra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna",
    "claude-fable-5-1", "claude-fable-5", "claude-opus-5-5", "claude-opus-5", "claude-opus-4-8", "claude-opus-4-7",
    "claude-opus-4-6", "claude-opus-4-5", "claude-sonnet-5-5", "claude-sonnet-5", "claude-haiku-5-5", "claude-haiku-4-5",
    "claude-sonnet-4-6", "claude-sonnet-4-5", "ag/claude-sonnet-4-6", "ag/claude-opus-4-6-thinking",
}
catalog_ids = set()
try:
    catalog = fetch_json("https://llm.human01.xyz/v1/models").get("data", [])
    catalog_ids = {m["id"] for m in catalog if isinstance(m, dict) and isinstance(m.get("id"), str)}
    # Keep a model when it is a known paid/tested model OR the gateway marks it free
    # (capabilities:['free'] / customer_price_per_token_usd:0). Free models are split
    # into the human01free provider downstream.
    def _is_free_item(it):
        caps = it.get("capabilities")
        if isinstance(caps, list) and "free" in caps:
            return True
        return it.get("customer_price_per_token_usd") == 0
    catalog = [m for m in catalog if isinstance(m, dict) and isinstance(m.get("id"), str) and all(c.isalnum() or c in "._:/-" for c in m["id"])]
    if not catalog:
        raise ValueError("empty model catalog")
except Exception as exc:
    print(f"Could not load Human01 models: {exc}. No changes were made.", file=sys.stderr)
    sys.exit(1)
config = {}
if os.path.exists(path):
    try:
        with open(path, encoding="utf-8") as f:
            config = json.load(f)
    except Exception as exc:
        print(f"Could not safely read {path}: {exc}", file=sys.stderr)
        print("No changes were made. If this file uses JSONC comments, add the Human01 provider manually.", file=sys.stderr)
        sys.exit(1)
if not isinstance(config, dict):
    print(f"Expected a JSON object in {path}; no changes were made.", file=sys.stderr)
    sys.exit(1)

provider = config.setdefault("provider", {})
if not isinstance(provider, dict):
    print("The existing 'provider' setting is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
current = provider.get("human01", {})
if not isinstance(current, dict):
    print("The existing 'human01' provider is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
models = current.get("models", {})
if not isinstance(models, dict):
    print("The existing Human01 model list is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
models = {model: value for model, value in models.items() if model not in catalog_ids or model in installable_model_ids}
options = current.get("options", {})
if not isinstance(options, dict):
    print("The existing Human01 provider options are not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
if options.get("baseURL") not in (None, "https://llm.human01.xyz/v1") or current.get("npm") not in (None, "@ai-sdk/openai-compatible"):
    print("A different provider already uses the human01 ID; no changes were made. Rename that provider before installing Human01.", file=sys.stderr)
    sys.exit(1)
managed_models = [m["id"] for m in catalog]
if any(model in models and not isinstance(models[model], dict) for model in managed_models):
    print("A Human01 model entry is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)

# Split the catalog into PAID (human01) and FREE (human01free) providers so free-tier
# traffic does not contend with paid traffic on a single provider entry.
def _is_free_entry(it):
    caps = it.get("capabilities")
    if isinstance(caps, list) and "free" in caps:
        return True
    return it.get("customer_price_per_token_usd") == 0

paid_entries = [m for m in catalog if not _is_free_entry(m)]
free_entries = [m for m in catalog if _is_free_entry(m)]

os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path):
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
    backup = path + ".backup-" + stamp
    shutil.copy2(path, backup)
    print(f"Backup: {backup}")

current.update({
    "npm": "@ai-sdk/openai-compatible",
    "name": "Human01",
    "options": {**options, "baseURL": "https://llm.human01.xyz/v1"},
    "models": {
        **models,
        **{m["id"]: {**models.get(m["id"], {}), "name": m.get("name") or m["id"]} for m in paid_entries},
    },
})

# ---- human01free (free) provider ----
free_current = provider.get("human01free", {})
if not isinstance(free_current, dict):
    print("The existing 'human01free' provider is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
free_models = free_current.get("models", {})
if not isinstance(free_models, dict):
    print("The existing human01free model list is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
free_options = free_current.get("options", {})
if not isinstance(free_options, dict):
    print("The existing human01free provider options are not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
if free_options.get("baseURL") not in (None, "https://llm.human01.xyz/v1") or free_current.get("npm") not in (None, "@ai-sdk/openai-compatible"):
    print("A different provider already uses the human01free ID; no changes were made. Rename that provider before installing Human01 Free.", file=sys.stderr)
    sys.exit(1)
free_current.update({
    "npm": "@ai-sdk/openai-compatible",
    "name": "Human01 Free",
    "options": {**free_options, "baseURL": "https://llm.human01.xyz/v1"},
    "models": {
        **free_models,
        **{m["id"]: {**free_models.get(m["id"], {}), "name": m.get("name") or m["id"]} for m in free_entries},
    },
})
provider["human01free"] = free_current

config.setdefault("$schema", "https://mimo.xiaomi.com/mimocode/config.json")
tmp = path + ".human01-tmp"
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
    json.dump(config, f, indent=2, ensure_ascii=False)
    f.write("\n")
os.replace(tmp, path)
print(f"Human01 provider ({len(paid_entries)} paid models) and Human01 Free provider ({len(free_entries)} free models) added to {path}")
print("Your API key was not included or saved.")
print("Next: open MiMo Code, run /connect, choose Other, enter provider ID human01 (paid) or human01free (free), then enter your Human01 API key.")
print("Then run /models and select one of the available models.")
PY
