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

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

CONFIG_DIR="${KIMI_CODE_HOME:-$HOME/.kimi-code}"
CONFIG_FILE="$CONFIG_DIR/config.toml"
provider_list=""
if [[ -f "$CONFIG_FILE" ]]; then
  if ! provider_list="$(kimi provider list --json 2>&1)"; then
    echo "Kimi Code could not read its existing provider config. No config changes were made. Details: $provider_list" >&2
    exit 1
  fi
fi
HAS_CUSTOM_PROVIDER=false
if [[ "$provider_list" == *'human01'* ]]; then HAS_CUSTOM_PROVIDER=true; fi
if [[ -f "$CONFIG_FILE" ]] && grep -Eq '^\[providers\.human01\]|^\[models\."human01/' "$CONFIG_FILE"; then HAS_CUSTOM_PROVIDER=true; fi
if [[ "$HAS_CUSTOM_PROVIDER" == true ]] && { [[ ! -f "$CONFIG_FILE" ]] || ! grep -q '^# BEGIN HUMAN01 INTEGRATION$' "$CONFIG_FILE"; }; then
  echo "A provider named human01 already exists and is not managed by this installer. No config changes were made." >&2
  exit 1
fi
HAD_CONFIG=false
if [[ -f "$CONFIG_FILE" ]]; then HAD_CONFIG=true; fi
BACKUP_FILE=""
if [[ "$HAD_CONFIG" == true ]]; then
  BACKUP_FILE="$CONFIG_FILE.backup-$(date -u +%Y%m%dT%H%M%SZ)-$$-$RANDOM"
fi

python3 - "$CONFIG_FILE" "$BACKUP_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)

path = sys.argv[1]
backup = sys.argv[2]
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",
}
try:
    catalog = fetch_json("https://llm.human01.xyz/v1/models").get("data", [])
    # 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)
begin = "# BEGIN HUMAN01 INTEGRATION"
end = "# END HUMAN01 INTEGRATION"
ids = tuple(m["id"] for m in catalog)
catalog_by_id = {m["id"]: m for m in catalog}

# 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_ids = [mid for mid in ids if not _is_free_entry(catalog_by_id[mid])]
free_ids = [mid for mid in ids if _is_free_entry(catalog_by_id[mid])]

def _build_provider_block(provider_id, display_name, model_ids):
    """Build the TOML lines for one provider + its model aliases."""
    lines = [f"[providers.{provider_id}]", 'type = "openai"', 'base_url = "https://llm.human01.xyz/v1"', 'api_key_env = "HUMAN01_API_KEY"', ""]
    for model in model_ids:
        details = catalog_by_id[model]
        context = details.get("context_window") or 200000
        output = details.get("max_output_tokens") or 8192
        lines += [f'[models."{provider_id}/{model}"]', f'provider = "{provider_id}"', f'model = "{model}"', f'max_context_size = {context}', f'max_output_size = {output}', 'capabilities = ["thinking", "tool_use"]', ""]
    return lines

block = [begin]
block += _build_provider_block("human01", "Human01", paid_ids)
block += _build_provider_block("human01free", "Human01 Free", free_ids)
block += [end]
replacement = "\n".join(block)
old = ""
if os.path.exists(path):
    with open(path, encoding="utf-8") as f:
        old = f.read()
if (begin in old) != (end in old):
    print("The Human01 marker block is incomplete; no changes were made.", file=sys.stderr)
    sys.exit(1)
if begin in old:
    start = old.index(begin)
    stop = old.index(end, start) + len(end)
    updated = old[:start] + replacement + old[stop:]
else:
    updated = old.rstrip() + ("\n\n" if old.strip() else "") + replacement + "\n"

os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path):
    shutil.copy2(path, backup)
    print(f"Backup: {backup}")
tmp = path + ".human01-tmp"
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
    f.write(updated)
os.replace(tmp, path)
print(f"Human01 provider ({len(paid_ids)} paid models) and Human01 Free provider ({len(free_ids)} free models) added to {path}")
print("Your API key was not included or saved. Set HUMAN01_API_KEY in the terminal before starting Kimi Code, then choose a human01 (paid) or human01free (free) model with /model.")
PY

if ! kimi provider list --json >/dev/null 2>&1; then
  echo "Kimi Code rejected the updated config; restoring the previous file." >&2
  if [[ "$HAD_CONFIG" == true ]]; then cp -p "$BACKUP_FILE" "$CONFIG_FILE"; else rm -f "$CONFIG_FILE"; fi
  exit 1
fi
