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

if ! command -v opencode >/dev/null 2>&1; then
  echo "OpenCode CLI was not found on PATH. Install OpenCode, open a new terminal, and run this installer again." >&2
  exit 127
fi
# Launchers can read stdin, which still carries the script in curl | bash.
if ! opencode_version="$(opencode --version </dev/null 2>/dev/null)"; then
  echo "OpenCode CLI was found at $(command -v opencode), but it could not start. Run 'opencode --version' in this terminal for details. If you are using WSL, install OpenCode inside your Linux distribution. No config changes were made." >&2
  exit 1
fi
opencode_version="${opencode_version%%$'\n'*}"
opencode_version="${opencode_version:-(installed)}"
printf 'Detected OpenCode: %s\n' "${opencode_version}"
if ! command -v python3 >/dev/null 2>&1; then
  echo "Python 3 is required to safely merge the OpenCode 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}/opencode"
CONFIG_FILE="$CONFIG_DIR/opencode.json"
MODEL_CATALOG_URL="https://llm.human01.xyz/v1/models"

python3 - "$CONFIG_FILE" "$MODEL_CATALOG_URL" <<'PY'
import json, os, re, 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]
catalog_url = 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(catalog_url)
    models_to_add = [
        item for item in catalog.get("data", [])
        if isinstance(item, dict)
        # The live catalog is the published source of model availability.
        and isinstance(item.get("id"), str)
        and isinstance(item.get("id"), str)
        and re.fullmatch(r"[A-Za-z0-9._:/-]+", item["id"])
        and isinstance(item.get("display_name"), str)
        and item["display_name"].strip()
    ]
    if not models_to_add:
        raise ValueError("model list was empty or invalid")
except Exception as exc:
    print(f"Could not download the current Human01 model list: {exc}", file=sys.stderr)
    print("No config changes were made. Check your internet connection and try again.", 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)

# 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. A model
# is "free" when the gateway marks it with capabilities:['free'] /
# customer_price_per_token_usd:0 (the free upstreams + Workers AI models).
def _is_free(item):
    caps = item.get("capabilities")
    if isinstance(caps, list) and "free" in caps:
        return True
    return item.get("customer_price_per_token_usd") == 0

paid_items = [it for it in models_to_add if not _is_free(it)]
free_items = [it for it in models_to_add if _is_free(it)]

# ---- human01 (paid) provider ----
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)
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)
for item in paid_items:
    model_id = item["id"]
    if model_id in models and not isinstance(models[model_id], dict):
        print(f"Human01 model entry '{model_id}' is not an object; no changes were made.", file=sys.stderr)
        sys.exit(1)
catalog_ids = {item.get("id") for item in catalog.get("data", []) if isinstance(item, dict)}
models = {model_id: value for model_id, value in models.items() if model_id not in catalog_ids or model_id in installable_model_ids}

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,
        **{item["id"]: {**models.get(item["id"], {}), "name": item["display_name"]} for item in paid_items},
    },
})
provider["human01"] = current

# ---- human01free (free) provider ----
# Registered alongside human01 so free-tier models are isolated on their own
# provider entry (own rate management, no contention with paid traffic).
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)
for item in free_items:
    model_id = item["id"]
    if model_id in free_models and not isinstance(free_models[model_id], dict):
        print(f"human01free model entry '{model_id}' is not an object; no changes were made.", 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,
        **{item["id"]: {**free_models.get(item["id"], {}), "name": item["display_name"]} for item in free_items},
    },
})
provider["human01free"] = free_current

config.setdefault("$schema", "https://opencode.ai/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)
summary = f"Human01 provider ({len(paid_items)} paid models)"
if free_items:
    summary += f" and Human01 Free provider ({len(free_items)} free models)"
print(f"{summary} added to {path}")
if free_items:
    print("To use Human01 Free, connect it separately in OpenCode with /connect.")
PY

# Keep the credential prompt on the terminal, away from Bash's script input.
if ! { exec 3<>/dev/tty; } 2>/dev/null; then
  echo "No interactive terminal is available. In OpenCode, run /connect and choose Human01 to enter your API key."
  exit 0
fi

if [[ "$opencode_version" =~ (^|[[:space:]])v?([0-9]+)\. ]] && (( BASH_REMATCH[2] >= 2 )); then
  login=(opencode --standalone auth login human01 --method key)
else
  login=(opencode auth login --provider human01)
fi
if ! "${login[@]}" <&3 >&3 2>&3; then
  echo "Human01 credentials were not confirmed. In OpenCode, run /connect and choose Human01 to finish setup." >&2
  exit 1
fi
exec 3>&-
echo "Open OpenCode and use /models to choose a Human01 model."
