#!/bin/bash
set -e

# ==============================================
# LLMHosts.com Dev Container Entrypoint
# God-Mode provisioned | Auto-authenticates GitHub
# ==============================================

# ---- GitHub CLI authentication ----
if [ -n "$GH_TOKEN" ]; then
  echo "[god-mode] Authenticating GitHub CLI..."
  
  # Attempt gh auth login (may fail if account is flagged -- that's OK)
  if echo "$GH_TOKEN" | gh auth login --with-token 2>/dev/null; then
    echo "[god-mode] GitHub CLI authenticated as $(gh api user --jq '.login' 2>/dev/null || echo 'unknown')"
  else
    echo "[god-mode] gh auth login failed (account may be flagged). Token still usable for HTTPS git ops."
  fi
  
  # Configure git identity and safe directory -- ALWAYS runs regardless of login status
  git config --global user.name "${GITHUB_USER:-LookNoHandsMom}"
  git config --global user.email "${GITHUB_EMAIL:-brendonurban+LookNoHandsMOM@gmail.com}"
  git config --global --add safe.directory /workspace
  
  # CRITICAL: setup-git configures credential helper for git push/pull via gh
  # This works even when gh auth login fails -- GH_TOKEN env var is used directly
  gh config set git_protocol https 2>/dev/null || true
  gh auth setup-git 2>/dev/null || true
  
  # Fallback: ensure git can always push via HTTPS using GH_TOKEN directly
  # This is the safety net when gh auth setup-git doesn't stick
  git config --global credential.helper '!f() { echo username=x-access-token; echo "password=${GH_TOKEN}"; }; f'
  
  # Useful git defaults
  git config --global init.defaultBranch main
  git config --global push.autoSetupRemote true
  git config --global pull.rebase true
  git config --global core.autocrlf input
else
  echo "[god-mode] WARNING: GH_TOKEN not set. GitHub CLI will not be authenticated."
  echo "[god-mode] Set GH_TOKEN in .env file. See .env.example for reference."
fi

# ---- SSH key generation (if not already present) ----
if [ ! -f /root/.ssh/id_ed25519 ]; then
  echo "[god-mode] Generating SSH key..."
  ssh-keygen -t ed25519 -C "ai-agent-docker-llmhost" -f /root/.ssh/id_ed25519 -N "" 2>/dev/null
  echo "[god-mode] SSH key generated. Public key:"
  cat /root/.ssh/id_ed25519.pub
  
  # Register with GitHub if gh is authenticated
  if gh auth status >/dev/null 2>&1; then
    echo "[god-mode] Registering SSH key with GitHub..."
    gh ssh-key add /root/.ssh/id_ed25519.pub --title "ai-agent-docker-llmhost-$(date +%Y%m%d)" 2>/dev/null && \
      echo "[god-mode] SSH key registered with GitHub." || \
      echo "[god-mode] SSH key registration failed (may already exist). Register manually: gh ssh-key add /root/.ssh/id_ed25519.pub"
  fi
else
  echo "[god-mode] SSH key already exists."
fi

# ---- SSH config for GitHub ----
if [ ! -f /root/.ssh/config ] || ! grep -q "github.com" /root/.ssh/config 2>/dev/null; then
  cat >> /root/.ssh/config << 'SSHCFG'
Host github.com
  HostName github.com
  User git
  IdentityFile /root/.ssh/id_ed25519
  IdentitiesOnly yes
  StrictHostKeyChecking accept-new
SSHCFG
  chmod 600 /root/.ssh/config
fi

# ---- Install project dependencies if present ----
if [ -f /workspace/pyproject.toml ]; then
  echo "[god-mode] Installing Python project dependencies..."
  pip install -e ".[dev]" 2>/dev/null || pip install -e . 2>/dev/null || true
fi

if [ -f /workspace/frontend/package.json ]; then
  echo "[god-mode] Installing Node.js frontend dependencies..."
  cd /workspace/frontend && npm ci 2>/dev/null || npm install 2>/dev/null || true
  cd /workspace
fi

# ---- Print status summary ----
echo ""
echo "======================================"
echo " LLMHosts.com Dev Container Ready"
echo "======================================"
echo " GitHub CLI:  $(gh auth status 2>&1 | head -1 || echo 'not authenticated')"
echo " Git user:    $(git config --global user.name 2>/dev/null || echo 'not set')"
echo " Git email:   $(git config --global user.email 2>/dev/null || echo 'not set')"
echo " SSH key:     $(test -f /root/.ssh/id_ed25519 && echo 'present' || echo 'missing')"
echo " Python:      $(python --version 2>/dev/null || echo 'not found')"
echo " Node.js:     $(node --version 2>/dev/null || echo 'not found')"
echo " gh CLI:      $(gh --version 2>/dev/null | head -1 || echo 'not found')"
echo "======================================"
echo ""

exec "$@"
