#!/usr/bin/env bash
# services/vscode/entrypoint.sh
#
# Generuje settings.json z wartości env var, potem uruchamia code-server.
# Dzięki temu cała konfiguracja pochodzi z .env — zero ręcznego klikania w UI.

set -euo pipefail

USER_DATA_DIR="${USER_DATA_DIR:-/home/coder/.local/share/code-server/User}"
SETTINGS_FILE="${USER_DATA_DIR}/settings.json"
KEYBINDINGS_FILE="${USER_DATA_DIR}/keybindings.json"

# Utwórz katalogi jeśli nie istnieją
mkdir -p "${USER_DATA_DIR}"

echo "→ proxym VSCode: generuję konfigurację..."
echo "  API Base:  ${PROXYM_API_BASE}"
echo "  Workspace: /home/coder/project (${WORKSPACE_NAME:-proxym})"

# ── Generuj settings.json ────────────────────────────────────
# Zastępuje istniejący tylko jeśli różni się klucz PROXYM_API_BASE,
# żeby nie nadpisywać zmian robionych ręcznie przez użytkownika.
EXISTING_BASE=""
if [ -f "${SETTINGS_FILE}" ]; then
    EXISTING_BASE=$(python3 -c "
import json, sys
try:
    d = json.load(open('${SETTINGS_FILE}'))
    print(d.get('roo-cline.openAiBaseUrl', ''))
except: pass
" 2>/dev/null || true)
fi

if [ "${EXISTING_BASE}" != "${PROXYM_API_BASE}" ]; then
    echo "  settings.json: aktualizuję (API Base się zmieniło)"
    python3 - <<'PYEOF'
import json, os

settings = {
    # ── Roo Code — główny asystent AI ──────────────────────
    "roo-cline.apiProvider": "openai",
    "roo-cline.openAiBaseUrl": os.environ["PROXYM_API_BASE"],
    "roo-cline.openAiApiKey":  os.environ["PROXYM_API_KEY"],
    "roo-cline.openAiModelId": os.environ.get("VSCODE_MODEL_CODE", "balanced"),

    # ── VS Code built-in Chat (Copilot Chat) ─────────────────
    # code-server uses Open VSX; GitHub Copilot Chat is NOT available there.
    # Disable the built-in chat UI to prevent auto-install attempts.
    "chat.enabled": False,
    "chat.commandCenter.enabled": False,

    # Sticky models per tryb (każdy tryb używa innego aliasu modelu)
    "roo-cline.modeApiConfigs": {
        "code": {
            "apiProvider":    "openai",
            "openAiBaseUrl":  os.environ["PROXYM_API_BASE"],
            "openAiApiKey":   os.environ["PROXYM_API_KEY"],
            "openAiModelId":  os.environ.get("VSCODE_MODEL_CODE", "balanced"),
        },
        "architect": {
            "apiProvider":    "openai",
            "openAiBaseUrl":  os.environ["PROXYM_API_BASE"],
            "openAiApiKey":   os.environ["PROXYM_API_KEY"],
            "openAiModelId":  os.environ.get("VSCODE_MODEL_ARCHITECT", "free"),
        },
        "debug": {
            "apiProvider":    "openai",
            "openAiBaseUrl":  os.environ["PROXYM_API_BASE"],
            "openAiApiKey":   os.environ["PROXYM_API_KEY"],
            "openAiModelId":  os.environ.get("VSCODE_MODEL_DEBUG", "cheap"),
        },
        "ask": {
            "apiProvider":    "openai",
            "openAiBaseUrl":  os.environ["PROXYM_API_BASE"],
            "openAiApiKey":   os.environ["PROXYM_API_KEY"],
            "openAiModelId":  os.environ.get("VSCODE_MODEL_ASK", "free"),
        },
        "orchestrator": {
            "apiProvider":    "openai",
            "openAiBaseUrl":  os.environ["PROXYM_API_BASE"],
            "openAiApiKey":   os.environ["PROXYM_API_KEY"],
            "openAiModelId":  os.environ.get("VSCODE_MODEL_CODE", "balanced"),
        },
    },

    # Custom mode "Opus" — do najtrudniejszych zadań
    "roo-cline.customModes": [
        {
            "slug": "opus",
            "name": "⚡ Opus — Złożone zadania",
            "roleDefinition": (
                "Expert software architect. You work on complex multi-file "
                "refactorings, architectural decisions, and deep debugging. "
                "Think step by step before writing code."
            ),
            "groups": ["read", "edit", "command", "browser"],
            "apiConfig": {
                "apiProvider":   "openai",
                "openAiBaseUrl": os.environ["PROXYM_API_BASE"],
                "openAiApiKey":  os.environ["PROXYM_API_KEY"],
                "openAiModelId": os.environ.get("VSCODE_MODEL_OPUS", "premium"),
            },
        },
    ],

    # Limity bezpieczeństwa
    "roo-cline.autoApproveMaxRequests": 15,
    "roo-cline.diffEnabled": True,
    "roo-cline.enableCheckpoints": True,

    # MCP servers — proxym self-server
    "roo-cline.mcpServers": {
        "proxym": {
            "url": os.environ["PROXYM_API_BASE"].replace("/v1", "/mcp/self"),
            "description": "proxym self-management: VMs, accounts, costs",
        },
    },

    # ── Continue.dev — alternatywny asystent ──────────────
    "continue.enableTabAutocomplete": True,

    # ── Python ────────────────────────────────────────────
    "python.defaultInterpreterPath": "/usr/bin/python3",
    "[python]": {
        "editor.defaultFormatter": "charliermarsh.ruff",
        "editor.formatOnSave": True,
        "editor.codeActionsOnSave": {
            "source.fixAll.ruff": "explicit",
            "source.organizeImports.ruff": "explicit",
        },
    },
    "ruff.lint.args": ["--select=E,F,W,I,UP"],

    # ── Editor ────────────────────────────────────────────
    "editor.fontSize": 14,
    "editor.fontFamily": "'JetBrains Mono', 'Fira Code', monospace",
    "editor.fontLigatures": True,
    "editor.tabSize": 4,
    "editor.rulers": [88, 120],
    "editor.minimap.enabled": False,
    "editor.bracketPairColorization.enabled": True,
    "editor.stickyScroll.enabled": True,
    "editor.inlineSuggest.enabled": True,
    "editor.wordWrap": "off",

    # ── Terminal ─────────────────────────────────────────
    "terminal.integrated.defaultProfile.linux": "bash",
    "terminal.integrated.fontSize": 13,

    # ── Workbench ─────────────────────────────────────────
    "workbench.colorTheme": "Dark+",
    "workbench.iconTheme": "material-icon-theme",
    "workbench.startupEditor": "none",

    # ── Security / Trust ────────────────────────────────────
    "security.workspace.trust.enabled": False,

    # ── Git ───────────────────────────────────────────────
    "git.autofetch": True,
    "git.confirmSync": False,
    "gitlens.telemetry.enabled": False,

    # ── Files ─────────────────────────────────────────────
    "files.autoSave": "afterDelay",
    "files.autoSaveDelay": 1000,
    "files.exclude": {
        "**/__pycache__": True,
        "**/*.pyc": True,
        "**/.pytest_cache": True,
        "**/htmlcov": True,
        "**/.ruff_cache": True,
    },

    # ── ErrorLens ─────────────────────────────────────────
    "errorLens.enabledDiagnosticLevels": ["error", "warning"],
}

settings_file = os.environ.get("USER_DATA_DIR", "/home/coder/.local/share/code-server/User") + "/settings.json"
with open(settings_file, "w") as f:
    json.dump(settings, f, indent=2, ensure_ascii=False)

print("  ✅ settings.json zapisany")
PYEOF
else
    echo "  settings.json: bez zmian (API Base niezmieniony)"
fi

# ── Zawsze aktualizuj trust i theme (niezależnie od zmiany API) ───
python3 - <<'PYEOF'
import json
import os

settings_file = os.environ.get("USER_DATA_DIR", "/home/coder/.local/share/code-server/User") + "/settings.json"

try:
    with open(settings_file, "r") as f:
        settings = json.load(f)
except:
    settings = {}

# Wyłącz workspace trust (folder automatycznie trusted)
settings["security.workspace.trust.enabled"] = False

# Wyłącz wbudowany Chat (Copilot Chat) — nie działa w code-server (Open VSX)
settings["chat.enabled"] = False
settings["chat.commandCenter.enabled"] = False

# Ustaw ciemniejszy theme (Dark+ zamiast Default Dark Modern)
settings["workbench.colorTheme"] = "Dark+"

with open(settings_file, "w") as f:
    json.dump(settings, f, indent=2, ensure_ascii=False)

print("  ✅ Trust wyłączony, Theme: Dark+")
PYEOF

# ── Generuj keybindings.json ─────────────────────────────────
if [ ! -f "${KEYBINDINGS_FILE}" ]; then
    cat > "${KEYBINDINGS_FILE}" << 'KEYBINDINGS'
[
  {
    "key": "ctrl+shift+a",
    "command": "roo-cline.plusButtonClicked",
    "when": "!inlineSuggestionVisible"
  },
  {
    "key": "ctrl+shift+r",
    "command": "roo-cline.popoutButtonClicked"
  },
  {
    "key": "ctrl+`",
    "command": "workbench.action.terminal.toggleTerminal"
  }
]
KEYBINDINGS
    echo "  ✅ keybindings.json utworzony"
fi

# ── Generuj continue config (alternatywny asystent) ───────────
CONTINUE_DIR="/home/coder/.continue"
CONTINUE_CONFIG="${CONTINUE_DIR}/config.json"
mkdir -p "${CONTINUE_DIR}"

if [ ! -f "${CONTINUE_CONFIG}" ]; then
    python3 - <<'PYEOF'
import json, os

config = {
    "models": [
        {
            "title": "proxym — balanced (Sonnet)",
            "provider": "openai",
            "model": os.environ.get("VSCODE_MODEL_CODE", "balanced"),
            "apiBase": os.environ["PROXYM_API_BASE"],
            "apiKey": os.environ["PROXYM_API_KEY"],
        },
        {
            "title": "proxym — free (Gemini)",
            "provider": "openai",
            "model": os.environ.get("VSCODE_MODEL_ARCHITECT", "free"),
            "apiBase": os.environ["PROXYM_API_BASE"],
            "apiKey": os.environ["PROXYM_API_KEY"],
        },
        {
            "title": "proxym — cheap (Haiku)",
            "provider": "openai",
            "model": os.environ.get("VSCODE_MODEL_DEBUG", "cheap"),
            "apiBase": os.environ["PROXYM_API_BASE"],
            "apiKey": os.environ["PROXYM_API_KEY"],
        },
    ],
    "tabAutocompleteModel": {
        "title": "proxym — local autocomplete",
        "provider": "openai",
        "model": "local",
        "apiBase": os.environ["PROXYM_API_BASE"],
        "apiKey": os.environ["PROXYM_API_KEY"],
    },
    "allowAnonymousTelemetry": False,
}

continue_config = os.environ.get("CONTINUE_DIR", "/home/coder/.continue") + "/config.json"
with open(continue_config, "w") as f:
    json.dump(config, f, indent=2)

print("  ✅ continue/config.json utworzony")
PYEOF
fi

echo "→ proxym VSCode: konfiguracja gotowa"

# ── Podmień stronę logowania na custom z widoczną ścieżką do config ───
CUSTOM_LOGIN="/usr/local/bin/login.html"
CODE_SERVER_LOGIN=""

# Znajdź plik login.html code-server
for path in \
    "/usr/lib/code-server/out/browser/pages/login.html" \
    "/usr/lib/code-server/dist/pages/login.html" \
    "/app/code-server/out/browser/pages/login.html" \
    "/usr/local/lib/code-server/out/browser/pages/login.html"
do
    if [ -f "$path" ]; then
        CODE_SERVER_LOGIN="$path"
        break
    fi
done

if [ -n "$CODE_SERVER_LOGIN" ] && [ -f "$CUSTOM_LOGIN" ]; then
    echo "  Podmieniam stronę logowania: $CODE_SERVER_LOGIN"
    cp "$CUSTOM_LOGIN" "$CODE_SERVER_LOGIN"
    echo "  ✅ Strona logowania zaktualizowana (widoczna ścieżka do config)"
else
    echo "  ℹ️ Strona logowania: nie znaleziono pliku code-server do podmiany"
fi

echo ""
echo "  ╔════════════════════════════════════════════════════════════╗"
echo "  ║  VS Code Web gotowy na http://...:8080                     ║"
echo "  ║  Workspace: /home/coder/project                            ║"
echo "  ║  proxym API: ${PROXYM_API_BASE}                            ║"
echo "  ║                                                            ║"
echo "  ║  Plik konfiguracyjny code-server:                          ║"
echo "  ║  ~/.config/code-server/config.yaml                         ║"
echo "  ╚════════════════════════════════════════════════════════════╝"
echo ""

# Uruchom code-server
exec code-server \
    --bind-addr 0.0.0.0:8080 \
    --user-data-dir "${USER_DATA_DIR}" \
    --disable-telemetry \
    /home/coder/project
