#!/bin/bash
# Container Environment Variables & PEM Check Script
# Checks if environment variables and PEM files are consistent across 5 containers
# Also checks GitHub App token validity and ai-configurations repo sync
# Auto-fixes missing env vars and PEM files
# Auto-refreshes expired GitHub App tokens and clones missing repos
# Usage: bash container-env-check.sh

# Load env vars from .bashrc (avoid interactive shell issues in cron)
if [ -f "$HOME/.bashrc" ]; then
  set -a
  source "$HOME/.bashrc"
  set +a
fi

OUTPUT_DIR="$HOME/openclaw-team/skill-scripts"
LOG_FILE="$OUTPUT_DIR/container-env-check.log"
mkdir -p "$OUTPUT_DIR"

# Target containers
CONTAINERS="openclaw-feichen openclaw-team-code-expert openclaw-team-assist openclaw-bingwang openclaw-qiangwu"

# Required env vars to check (just check existence, not value)
ENV_VARS="AI_CONFIG_REPO JIRA_API_TOKEN GRAFANA_API_TOKEN AWS_BEARER_TOKEN_BEDROCK AWS_REGION ANTHROPIC_MODEL CLAUDE_CODE_USE_BEDROCK MINIMAX_API_KEY GITHUB_REPO_LOC GITHUB_APP_PRIVATE_KEY_PATH GITHUB_APP_ID GITHUB_APP_INSTALLATION_ID FEISHU_CODING_CHAT_ID"

# PEM file path
PEM_FILE="data-service-code-assist.pem"
PEM_HOST="$HOME/.github/$PEM_FILE"
PEM_CONTAINER_PATH="/home/openclaw/.github/$PEM_FILE"

# AI Configurations repo
AI_CONFIG_REPO_URL="https://x-access-token:${GITHUB_APP_TOKEN}@github.com/tidbcloud/data-service-infra-ai-configurations.git"
AI_CONFIG_DIR="$HOME/github/data-service-infra-ai-configurations"
AI_CONFIG_BRANCH="main"

# Target Feishu user
USER_ID="ou_f442e20fd980363ea486b5a6cd8d2a2f"

# Feishu API settings
APP_ID="${FEISHU_APP_ID}"
APP_SECRET="${FEISHU_APP_SECRET}"

ALERTS=()
FIXED=()
GITHUB_APP_TOKEN=""

# ============================================================
# Helper: send Feishu alert
# ============================================================
send_alert() {
  local msg="$1"
  TOKEN=$(curl -s -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" \
      -H "Content-Type: application/json" \
      -d "{\"app_id\": \"$APP_ID\", \"app_secret\": \"$APP_SECRET\"}" | python3 -c "import sys,json; print(json.load(sys.stdin).get('tenant_access_token',''))")
  CONTENT=$(python3 -c "import json; print(json.dumps(json.dumps({'text': '''$msg'''})))")
  [ -n "$TOKEN" ] && curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d "{\"receive_id\": \"$USER_ID\", \"msg_type\": \"text\", \"content\": $CONTENT}" 2>/dev/null
}

# ============================================================
# Helper: generate GitHub App JWT token
# ============================================================
generate_github_app_token() {
  local pem_path="$1"
  local app_id="$2"
  local installation_id="$3"

  python3 -c "
import jwt, time, requests, sys
try:
    with open('$pem_path') as f:
        private_key = f.read()
    payload = {
        'iss': '$app_id',
        'iat': int(time.time()),
        'exp': int(time.time()) + 600
    }
    jwt_token = jwt.encode(payload, private_key, algorithm='RS256')
    resp = requests.post(
        f'https://api.github.com/app/installations/$installation_id/access_tokens',
        headers={
            'Authorization': f'Bearer {jwt_token}',
            'Accept': 'application/vnd.github+json',
            'X-GitHub-Api-Version': '2022-11-28'
        }
    )
    result = resp.json()
    token = result.get('token', '')
    print(token)
except Exception as e:
    print('ERROR:' + str(e), file=sys.stderr)
    sys.exit(1)
"
}

# ============================================================
# Helper: test GitHub App token validity
# ============================================================
test_github_token() {
  local token="$1"
  python3 -c "
import requests, sys
resp = requests.get(
    'https://api.github.com/repos/tidbcloud/data-service-infra-ai-configurations',
    headers={
        'Authorization': 'Bearer $token',
        'Accept': 'application/vnd.github+json',
        'X-GitHub-Api-Version': '2022-11-28'
    }
)
if resp.status_code == 200:
    print('OK')
else:
    print('FAIL:' + str(resp.status_code))
    sys.exit(1)
" 2>/dev/null
}

# ============================================================
# Section 1: GitHub App Token Check
# ============================================================
echo "=== GitHub App Token Check ==="

PEM_PATH="$HOME/.github/data-service-code-assist.pem"
APP_ID_VAL="${GITHUB_APP_ID:-3002333}"
INSTALLATION_ID_VAL="${GITHUB_APP_INSTALLATION_ID:-113867057}"

if [ -z "$APP_ID_VAL" ] || [ -z "$INSTALLATION_ID_VAL" ] || [ ! -f "$PEM_PATH" ]; then
  ALERTS+=("Host: Missing GITHUB_APP_* env vars or PEM file")
  echo "  ⚠️  Missing GITHUB_APP_* env vars or PEM file"
else
  echo "  Generating host token..."
  GITHUB_APP_TOKEN=$(generate_github_app_token "$PEM_PATH" "$APP_ID_VAL" "$INSTALLATION_ID_VAL")
  if echo "$GITHUB_APP_TOKEN" | grep -q "ERROR"; then
    ALERTS+=("Host: Failed to generate GitHub App token - $GITHUB_APP_TOKEN")
    echo "  ⚠️  Failed: $GITHUB_APP_TOKEN"
  else
    if RESULT=$(test_github_token "$GITHUB_APP_TOKEN") && [ "$RESULT" = "OK" ]; then
      echo "  ✅ Host GitHub App token: valid"
    else
      echo "  🔄 Host token expired, refreshing..."
      GITHUB_APP_TOKEN=$(generate_github_app_token "$PEM_PATH" "$APP_ID_VAL" "$INSTALLATION_ID_VAL")
      if RESULT=$(test_github_token "$GITHUB_APP_TOKEN") && [ "$RESULT" = "OK" ]; then
        echo "  ✅ Host token: refreshed successfully"
        FIXED+=("Host: GitHub App token refreshed")
      else
        ALERTS+=("Host: GitHub App token still failing after refresh")
        echo "  ⚠️  Token still failing"
      fi
    fi
  fi
fi

# Per-container GitHub App token check
for container in $CONTAINERS; do
  echo "=== $container: GitHub App Token ==="
  if ! docker ps --format '{{.Names}}' | grep -q "^${container}$"; then
    echo "  ⚠️  Container not running, skipping"
    continue
  fi

  C_APP_ID=$(docker exec "$container" bash -i -c 'echo $GITHUB_APP_ID' 2>/dev/null || echo "")
  C_INSTALL_ID=$(docker exec "$container" bash -i -c 'echo $GITHUB_APP_INSTALLATION_ID' 2>/dev/null || echo "")
  C_PEM="$PEM_CONTAINER_PATH"

  if [ -z "$C_APP_ID" ] || [ -z "$C_INSTALL_ID" ]; then
    echo "  ⚠️  Missing GITHUB_APP_* env vars in container"
    continue
  fi

  if ! docker exec "$container" test -f "$C_PEM" 2>/dev/null; then
    echo "  ⚠️  PEM file not found in container"
    continue
  fi

  # Generate token
  TEMP_PEM=$(mktemp)
  docker cp "$container:$C_PEM" "$TEMP_PEM" 2>/dev/null && chmod 600 "$TEMP_PEM"
  if [ -f "$TEMP_PEM" ]; then
    C_TOKEN=$(generate_github_app_token "$TEMP_PEM" "$C_APP_ID" "$C_INSTALL_ID")
    rm -f "$TEMP_PEM"
  else
    C_TOKEN="ERROR:copy_failed"
  fi

  if echo "$C_TOKEN" | grep -q "ERROR"; then
    ALERTS+=("$container: Failed to generate GitHub App token")
    echo "  ⚠️  Token generation failed"
    continue
  fi

  # Test token validity
  TOKEN_VALID=false
  if RESULT=$(test_github_token "$C_TOKEN") && [ "$RESULT" = "OK" ]; then
    echo "  ✅ Token valid"
    TOKEN_VALID=true
  else
    echo "  🔄 Token expired, refreshing..."
    TEMP_PEM=$(mktemp)
    docker cp "$container:$C_PEM" "$TEMP_PEM" 2>/dev/null && chmod 600 "$TEMP_PEM"
    if [ -f "$TEMP_PEM" ]; then
      C_TOKEN=$(generate_github_app_token "$TEMP_PEM" "$C_APP_ID" "$C_INSTALL_ID")
      rm -f "$TEMP_PEM"
    fi
    if RESULT=$(test_github_token "$C_TOKEN") && [ "$RESULT" = "OK" ]; then
      echo "  ✅ Token refreshed"
      FIXED+=("$container: GitHub App token refreshed")
      TOKEN_VALID=true
    else
      ALERTS+=("$container: GitHub App token still failing after refresh")
      echo "  ⚠️  Token still failing"
    fi
  fi

  # Check gh auth login if token is valid
  if [ "$TOKEN_VALID" = true ]; then
    GH_AUTH_STATUS=$(docker exec "$container" gh auth status 2>&1 || echo "NOT_LOGGED_IN")
    if echo "$GH_AUTH_STATUS" | grep -q "Failed to log in\|You are not logged\|NOT_LOGGED_IN"; then
      echo "  🔄 gh auth not logged in, logging in..."
      echo "$C_TOKEN" | docker exec -i "$container" gh auth login --with-token 2>/dev/null
      if docker exec "$container" gh auth status 2>/dev/null | grep -q "github.com"; then
        echo "  ✅ gh auth login successful"
        FIXED+=("$container: gh auth login completed")
      else
        ALERTS+=("$container: gh auth login failed")
      fi
    else
      echo "  ✅ gh auth already logged in"
    fi
  fi
done

# ============================================================
# Section 2: AI Configurations Repo Check
# ============================================================
echo "=== AI Configurations Repo Check ==="

if [ -z "$GITHUB_APP_TOKEN" ] || echo "$GITHUB_APP_TOKEN" | grep -q "ERROR"; then
  echo "  ⚠️  No valid GitHub token, skipping AI config repo check"
else
  HTTPS_URL="https://x-access-token:${GITHUB_APP_TOKEN}@github.com/tidbcloud/data-service-infra-ai-configurations.git"

  # 2a. Check host repo
  if [ -d "$AI_CONFIG_DIR" ]; then
    echo "  ✅ Host: $AI_CONFIG_DIR exists"
  else
    echo "  🔄 Host: repo not found, cloning..."
    if git clone -b "$AI_CONFIG_BRANCH" "$HTTPS_URL" "$AI_CONFIG_DIR" 2>/dev/null; then
      echo "  ✅ Host: cloned successfully"
      FIXED+=("Host: ai-config repo cloned (was missing)")
    else
      ALERTS+=("Host: failed to clone ai-config repo")
    fi
  fi

  # 2b. Check each container's workspace for the repo
  for container in $CONTAINERS; do
    echo "=== $container: AI Configurations Repo ==="
    if ! docker ps --format '{{.Names}}' | grep -q "^${container}$"; then
      echo "  ⚠️  Container not running, skipping"
      continue
    fi

    # Get container's app token
    C_APP_ID=$(docker exec "$container" bash -i -c 'echo $GITHUB_APP_ID' 2>/dev/null || echo "")
    C_INSTALL_ID=$(docker exec "$container" bash -i -c 'echo $GITHUB_APP_INSTALLATION_ID' 2>/dev/null || echo "")

    if [ -z "$C_APP_ID" ] || [ -z "$C_INSTALL_ID" ]; then
      echo "  ⚠️  Missing GITHUB_APP_* env vars, skipping"
      continue
    fi

    TEMP_PEM=$(mktemp)
    docker cp "$container:$PEM_CONTAINER_PATH" "$TEMP_PEM" 2>/dev/null && chmod 600 "$TEMP_PEM"
    if [ ! -f "$TEMP_PEM" ]; then
      echo "  ⚠️  Cannot copy PEM from container"
      continue
    fi

    C_TOKEN=$(generate_github_app_token "$TEMP_PEM" "$C_APP_ID" "$C_INSTALL_ID")
    rm -f "$TEMP_PEM"

    if echo "$C_TOKEN" | grep -q "ERROR"; then
      echo "  ⚠️  Cannot generate container token"
      continue
    fi

    CONTAINER_REPO="/home/openclaw/github/data-service-infra-ai-configurations"
    C_HTTPS_URL="https://x-access-token:${C_TOKEN}@github.com/tidbcloud/data-service-infra-ai-configurations.git"

    if docker exec "$container" test -d "$CONTAINER_REPO" 2>/dev/null; then
      echo "  ✅ Repo exists in container workspace"
    else
      echo "  🔄 Repo not found, cloning..."
      docker exec "$container" bash -c "mkdir -p /home/openclaw/github && git clone -b $AI_CONFIG_BRANCH $C_HTTPS_URL $CONTAINER_REPO 2>/dev/null"
      if docker exec "$container" test -d "$CONTAINER_REPO" 2>/dev/null; then
        echo "  ✅ Cloned successfully"
        FIXED+=("$container: ai-config repo cloned into workspace (was missing)")
      else
        ALERTS+=("$container: failed to clone ai-config repo into workspace")
      fi
    fi
  done
fi

# ============================================================
# Section 3: Original env vars & PEM check
# ============================================================
echo "=== Environment Variables & PEM Check ==="

sync_env_to_container() {
  local container="$1"
  local host_bashrc="$HOME/.bashrc"
  docker exec "$container" mkdir -p /home/openclaw 2>/dev/null
  for var in $ENV_VARS; do
    host_value=$(grep "^export ${var}=" "$host_bashrc" 2>/dev/null | head -1 | cut -d'"' -f2 || echo "")
    if [ -n "$host_value" ]; then
      container_value=$(docker exec "$container" grep "^export ${var}=" /home/openclaw/.bashrc 2>/dev/null | head -1 | cut -d'"' -f2 || echo "")
      if [ -z "$container_value" ]; then
        docker exec "$container" bash -c "echo 'export ${var}=\"$host_value\"' >> /home/openclaw/.bashrc" 2>/dev/null
        FIXED+=("$container: Added missing $var")
      fi
    fi
  done
}

sync_pem_to_container() {
  local container="$1"
  if [ -f "$PEM_HOST" ]; then
    if ! docker exec "$container" test -f "$PEM_CONTAINER_PATH" 2>/dev/null; then
      docker exec "$container" mkdir -p /home/openclaw/.github 2>/dev/null
      docker cp "$PEM_HOST" "$container:$PEM_CONTAINER_PATH" 2>/dev/null
      docker exec "$container" chown openclaw:openclaw "$PEM_CONTAINER_PATH" 2>/dev/null
      FIXED+=("$container: Copied PEM file from host")
    fi
  fi
}

for container in $CONTAINERS; do
  echo "--- $container ---"
  if ! docker ps --format '{{.Names}}' | grep -q "^${container}$"; then
    ALERTS+=("Container $container is not running")
    continue
  fi

  BASHRC_CONTENT=$(docker exec $container cat /home/openclaw/.bashrc 2>/dev/null || echo "")

  for var in $ENV_VARS; do
    CONTAINER_VALUE=$(echo "$BASHRC_CONTENT" | grep "^export ${var}=" | head -1 | cut -d'"' -f2 || echo "")
    if [ -z "$CONTAINER_VALUE" ]; then
      sync_env_to_container "$container"
      break
    fi
  done

  if ! docker exec "$container" test -f "$PEM_CONTAINER_PATH" 2>/dev/null; then
    sync_pem_to_container "$container"
  fi

  echo "  ✅ env vars & PEM OK"
done

# ============================================================
# Summary & Alerts
# ============================================================
if [ ${#ALERTS[@]} -gt 0 ]; then
  ALERT_MSG="⚠️ Container Environment Check Alert"
  for alert in "${ALERTS[@]}"; do
    ALERT_MSG="$ALERT_MSG
- $alert"
  done
  ALERT_MSG="$ALERT_MSG
Time: $(date '+%Y-%m-%d %H:%M:%S')"
  echo ""
  echo "=== ALERTS ==="
  echo "$ALERT_MSG"
  send_alert "$ALERT_MSG"
fi

if [ ${#FIXED[@]} -gt 0 ]; then
  echo ""
  echo "=== FIXED ==="
  for fix in "${FIXED[@]}"; do
    echo "  ✅ $fix"
  done
  FIXED_MSG="✅ **Container Environment Auto-Fixed**
"
  for fix in "${FIXED[@]}"; do
    FIXED_MSG+="- $fix
"
  done
  FIXED_MSG+="Time: $(date '+%Y-%m-%d %H:%M:%S')"
  send_alert "$FIXED_MSG"
fi

echo ""
echo "✅ Container Environment Check Complete"
