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

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

AGENT_DIR="${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}"
CONFIG_FILE="$AGENT_DIR/models.json"
AUTH_FILE="$AGENT_DIR/auth.json"
python3 - "$CONFIG_FILE" "$AUTH_FILE" <<'PY'
import getpass, 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, auth_path = sys.argv[1:3]
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 parse {path}: {exc}", file=sys.stderr)
        print("No changes were made. Pi accepts JSONC too; add this provider manually if your file uses comments.", file=sys.stderr)
        sys.exit(1)
if not isinstance(config, dict):
    print("Expected a JSON object; no changes were made.", file=sys.stderr)
    sys.exit(1)
providers = config.setdefault("providers", {})
if not isinstance(providers, dict):
    print("The existing 'providers' setting is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
existing = providers.get("human01", {})
if not isinstance(existing, dict):
    print("The existing Human01 provider is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
if existing.get("baseUrl") not in (None, "https://llm.human01.xyz/v1") or existing.get("api") not in (None, "openai-completions"):
    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)
if existing.get("apiKey") not in (None, "${HUMAN01_API_KEY}"):
    print("The existing human01 provider contains a different API-key setting; no changes were made.", file=sys.stderr)
    sys.exit(1)
auth = {}
if os.path.exists(auth_path):
    try:
        with open(auth_path, encoding="utf-8") as f:
            auth = json.load(f)
    except Exception as exc:
        print(f"Could not safely parse {auth_path}: {exc}. No changes were made.", file=sys.stderr)
        sys.exit(1)
if not isinstance(auth, dict) or ("human01" in auth and not isinstance(auth["human01"], dict)):
    print("The existing Human01 credential is invalid; no changes were made.", file=sys.stderr)
    sys.exit(1)
credential = auth.get("human01", {})
api_key = os.environ.get("HUMAN01_API_KEY") or credential.get("key")
if not api_key:
    api_key = getpass.getpass("Human01 API key (input hidden; saved in Pi auth.json): ").strip()
if not api_key:
    print("No API key provided. No changes were made.", file=sys.stderr)
    sys.exit(1)
models = existing.get("models", [])
if not isinstance(models, list) or any(not isinstance(m, dict) for m in models):
    print("The existing Human01 model list is invalid; no changes were made.", file=sys.stderr)
    sys.exit(1)
models = [m for m in models if m.get("id") not in catalog_ids or m.get("id") in installable_model_ids]
model_ids = tuple(m["id"] for m in catalog)
if any(m.get("id") in model_ids and not isinstance(m, dict) for m in models):
    print("A Human01 model entry is invalid; 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}")
merged = {m.get("id"): m for m in models}
catalog_by_id = {m["id"]: m for m in catalog}
for model in model_ids:
    details = catalog_by_id[model]
    merged[model] = {
        **merged.get(model, {}),
        "id": model,
        "name": details.get("name") or model,
        "contextWindow": details.get("context_window", 200000),
        "maxTokens": details.get("max_output_tokens", 32768),
        "reasoning": True,
        "input": ["text"],
    }
existing.update({
    "baseUrl": "https://llm.human01.xyz/v1",
    "api": "openai-completions",
    "models": [merged[mid] for mid in model_ids if not _is_free_entry(catalog_by_id[mid])],
})
existing.pop("apiKey", None)
providers["human01"] = existing

# ---- human01free (free) provider ----
free_existing = providers.get("human01free", {})
if not isinstance(free_existing, dict):
    print("The existing 'human01free' provider is not an object; no changes were made.", file=sys.stderr)
    sys.exit(1)
free_models = free_existing.get("models", [])
if not isinstance(free_models, list) or any(not isinstance(m, dict) for m in free_models):
    print("The existing human01free model list is invalid; no changes were made.", file=sys.stderr)
    sys.exit(1)
free_merged = {m.get("id"): m for m in free_models}
for entry in free_entries:
    mid = entry["id"]
    free_merged[mid] = {
        **free_merged.get(mid, {}),
        "id": mid,
        "name": entry.get("name") or mid,
        "contextWindow": entry.get("context_window", 200000),
        "maxTokens": entry.get("max_output_tokens", 32768),
        "reasoning": True,
        "input": ["text"],
    }
free_existing.update({
    "baseUrl": "https://llm.human01.xyz/v1",
    "api": "openai-completions",
    "models": list(free_merged.values()),
})
free_existing.pop("apiKey", None)
providers["human01free"] = free_existing

auth["human01"] = {"type": "api_key", "key": api_key}
auth["human01free"] = {"type": "api_key", "key": api_key}
tmp = path + ".human01-tmp"
auth_tmp = auth_path + ".human01-tmp"
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}")
if os.path.exists(auth_path):
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
    backup = auth_path + ".backup-" + stamp
    shutil.copy2(auth_path, backup)
    print(f"Backup: {backup}")
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
    json.dump(config, f, indent=2, ensure_ascii=False)
    f.write("\n")
with open(auth_tmp, "w", encoding="utf-8", newline="\n") as f:
    json.dump(auth, f, indent=2, ensure_ascii=False)
    f.write("\n")
os.chmod(auth_tmp, 0o600)
os.replace(tmp, path)
os.replace(auth_tmp, auth_path)
print(f"Human01 provider ({len(paid_entries)} paid models) and Human01 Free provider ({len(free_entries)} free models) added to {path}")
print(f"Human01 API key saved to {auth_path}. Start Pi and choose a Human01 model with /model.")
PY
