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

# This file intentionally contains the gateway token in plaintext.
GATEWAY_URL="https://pro5000.cdxyl.online"
AUTH_TOKEN="sk-llm-local-change-me"
MODEL_ID="Qwen3.8-27B-FP8"
CONTEXT_TOKENS="131072"
MAX_OUTPUT_TOKENS="8192"

CODE_CLI="${CODE_CLI:-code}"
if ! command -v "$CODE_CLI" >/dev/null 2>&1; then
  echo "VS Code command 'code' was not found." >&2
  echo "Run this script from the VS Code Remote SSH integrated terminal, or install Claude Code from the Extensions view." >&2
  exit 1
fi

"$CODE_CLI" --install-extension Anthropic.claude-code --force

SERVER_DATA="${VSCODE_SERVER_DATA:-$HOME/.vscode-server/data}"
MACHINE_SETTINGS="$SERVER_DATA/Machine/settings.json"
USER_SETTINGS="$SERVER_DATA/User/settings.json"
mkdir -p "$(dirname "$MACHINE_SETTINGS")" "$(dirname "$USER_SETTINGS")"

ANTHROPIC_AUTH_TOKEN="$AUTH_TOKEN" node - "$MACHINE_SETTINGS" "$USER_SETTINGS" "$GATEWAY_URL" "$MODEL_ID" "$CONTEXT_TOKENS" "$MAX_OUTPUT_TOKENS" <<'NODE'
const fs = require("node:fs");
const path = require("node:path");

const [, , machinePath, userPath, baseUrl, model, contextTokens, maxOutputTokens] = process.argv;
const authToken = process.env.ANTHROPIC_AUTH_TOKEN;
if (!authToken) throw new Error("Missing gateway token.");

function readJson(filePath) {
  try {
    return JSON.parse(fs.readFileSync(filePath, "utf8"));
  } catch (error) {
    if (error.code === "ENOENT") return {};
    throw new Error(`Cannot read valid JSON from ${filePath}: ${error.message}`);
  }
}

function writeJson(filePath, value) {
  const tempPath = `${filePath}.tmp-${process.pid}`;
  fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
  fs.chmodSync(tempPath, 0o600);
  fs.renameSync(tempPath, filePath);
}

const machineSettings = readJson(machinePath);
const environmentVariables = Array.isArray(machineSettings["claudeCode.environmentVariables"])
  ? machineSettings["claudeCode.environmentVariables"].filter(
      (item) => item && ![
        "ANTHROPIC_BASE_URL",
        "ANTHROPIC_AUTH_TOKEN",
        "ANTHROPIC_MODEL",
        "ANTHROPIC_SMALL_FAST_MODEL",
        "CLAUDE_CODE_MAX_CONTEXT_TOKENS",
        "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
      ].includes(item.name),
    )
  : [];

environmentVariables.push(
  { name: "ANTHROPIC_BASE_URL", value: baseUrl },
  { name: "ANTHROPIC_AUTH_TOKEN", value: authToken },
  { name: "ANTHROPIC_MODEL", value: model },
  { name: "ANTHROPIC_SMALL_FAST_MODEL", value: model },
  { name: "CLAUDE_CODE_MAX_CONTEXT_TOKENS", value: contextTokens },
  { name: "CLAUDE_CODE_MAX_OUTPUT_TOKENS", value: maxOutputTokens },
);
machineSettings["claudeCode.environmentVariables"] = environmentVariables;
writeJson(machinePath, machineSettings);

const userSettings = readJson(userPath);
userSettings["claudeCode.disableLoginPrompt"] = true;
writeJson(userPath, userSettings);

console.log("Gateway settings written to VS Code Server machine settings.");
console.log(`Model: ${model}; gateway: ${baseUrl}`);
NODE

chmod 600 "$MACHINE_SETTINGS" "$USER_SETTINGS"
echo "Claude Code for VS Code is installed and configured. Run 'Developer: Reload Window' and start a new Claude conversation."
