#!/bin/bash

# team-employee - Manage OpenClaw Docker containers for team members

set -e

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Default values
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_BASE="$HOME/openclaw-config"
TEAM_DIR="$HOME/openclaw-team"
SHARED_DIR="$TEAM_DIR/shared-dir"
WORKSPACE_DIR="$HOME/.openclaw/workspace"

# Detect container home directory
detect_container_home() {
    local image="${1:-openclaw-agent:latest}"

    # Try to get HOME directory from image
    local container_home
    container_home=$(docker run --rm --entrypoint sh "$image" -c 'echo $HOME' 2>/dev/null)

    if [ -n "$container_home" ] && [ "$container_home" != "/" ]; then
        echo "$container_home"
    else
        # Fallback: try to get default user from image
        local user
        user=$(docker image inspect "$image" --format '{{.Config.User}}' 2>/dev/null)

        if [ -n "$user" ] && [ "$user" != "0" ] && [ "$user" != "root" ]; then
            # If numeric UID, use common path
            if [[ "$user" =~ ^[0-9]+$ ]]; then
                echo "/home/ubuntu"  # Default
            else
                echo "/home/$user"
            fi
        else
            # root user or not specified
            if [ "$user" = "0" ] || [ "$user" = "root" ]; then
                echo "/root"
            else
                echo "/home/ubuntu"  # Final default
            fi
        fi
    fi
}

# Detect container UID
detect_container_uid() {
    local image="${1:-openclaw-agent:latest}"

    # Try to get UID from image config
    local user
    user=$(docker image inspect "$image" --format '{{.Config.User}}' 2>/dev/null)

    if [ -n "$user" ]; then
        # If it's already numeric UID
        if [[ "$user" =~ ^[0-9]+$ ]]; then
            echo "$user"
            return
        elif [[ "$user" =~ ^[0-9]+:[0-9]+$ ]]; then
            # Extract UID from UID:GID format
            echo "${user%%:*}"
            return
        fi
    fi

    # Fallback: run container and check actual UID
    local uid
    uid=$(docker run --rm --entrypoint sh "$image" -c 'id -u' 2>/dev/null)

    if [ -n "$uid" ] && [[ "$uid" =~ ^[0-9]+$ ]]; then
        echo "$uid"
    else
        # Final fallback
        echo "1000"
    fi
}

# Show usage
usage() {
    echo -e "${BLUE}team-employee - OpenClaw Container Management${NC}"
    echo ""
    echo "Usage: $0 <command> [arguments]"
    echo ""
    echo "Commands:"
    echo "  add <name> [app_id] [app_secret]   Add employee and deploy container"
    echo "  rebuild <name>                      Rebuild container (preserve image, delegate to upgrade)"
    echo "  upgrade <name> [version]            Upgrade container to specific version (default: latest)"
    echo "  restart <name>                      Restart container and gateway"
    echo "  remove <name>                       Remove container (keep config)"
    echo "  delete <name>                       Remove container and config"
    echo "  list                                List all containers with config paths"
    echo "  fix-permissions                     Fix read permissions for config files"
    echo ""
    echo "Examples:"
    echo "  $0 add zhangsan"
    echo "  $0 add lisi cli_xxx cli_xxx"
    echo "  $0 restart zhangsan"
    echo "  $0 remove zhangsan"
    echo "  $0 delete lisi"
    echo "  $0 list"
    echo "  $0 fix-permissions"
}

# Check Docker
check_docker() {
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}❌ Docker not installed${NC}"
        exit 1
    fi

    if ! docker info &> /dev/null; then
        echo -e "${RED}❌ Docker not running${NC}"
        exit 1
    fi
    echo -e "${GREEN}✅ Docker check passed${NC}"
}

# Check if container exists
container_exists() {
    docker ps -a --format "{{.Names}}" 2>/dev/null | grep -q "^$1$"
}

# Check if container is running
is_container_running() {
    docker ps --format "{{.Names}}" 2>/dev/null | grep -q "^$1$"
}

# Find available port
find_port() {
    local port=18790
    # macOS and Linux compatible port check
    while lsof -Pi :${port} -sTCP:LISTEN -t >/dev/null 2>&1 || netstat -an 2>/dev/null | grep -q "[.:]${port} "; do
        port=$((port + 1))
    done
    echo $port
}

# Get container port (macOS and Linux compatible)
get_container_port() {
    local container="$1"
    local config_dir="${CONFIG_BASE}/${container}"

    if [ ! -f "${config_dir}/openclaw.json" ]; then
        echo "-"
        return
    fi

    # Use python to parse JSON, avoid grep -P incompatibility
    local port
    port=$(python3 -c "
import json
try:
    with open('${config_dir}/openclaw.json', 'r') as f:
        data = json.load(f)
        port = data.get('gateway', {}).get('port', '-')
        print(port)
except Exception:
    print('-')
" 2>/dev/null) || port="-"

    echo "$port"
}

# Add employee
do_add() {
    local NAME="$1"
    local FEISHU_APP_ID="${2:-}"
    local FEISHU_APP_SECRET="${3:-}"

    if [ -z "$NAME" ]; then
        echo -e "${RED}❌ Please specify employee name${NC}"
        echo "Usage: $0 add <name> [feishu_app_id] [feishu_app_secret]"
        exit 1
    fi

    local CONTAINER_NAME="openclaw-${NAME}"
    local CONFIG_DIR="${CONFIG_BASE}/${CONTAINER_NAME}"

    echo -e "${GREEN}🚀 Starting OpenClaw container deployment: ${CONTAINER_NAME}${NC}"
    echo "=========================================="

    check_docker

    # Detect container home directory and UID
    echo -e "${GREEN}🔍 Detecting container configuration...${NC}"
    local CONTAINER_HOME=$(detect_container_home "openclaw-agent:latest")
    local CONTAINER_UID=$(detect_container_uid "openclaw-agent:latest")
    local CONTAINER_OPENCLAW_DIR="${CONTAINER_HOME}/.openclaw"
    local CONTAINER_SHARED_DIR="${CONTAINER_HOME}/openclaw-team/shared-dir"
    echo -e "${GREEN}✅ Container home: ${CONTAINER_HOME}, UID: ${CONTAINER_UID}${NC}"

    # Check MINIMAX_API_KEY (support multiple sources)
    if [ -z "$MINIMAX_API_KEY" ]; then
        echo -e "${YELLOW}⚠️ Environment variable MINIMAX_API_KEY not set${NC}"
        echo "Trying to read from auth-profiles..."

        # Try to read from auth-profiles.json (most reliable source)
        local auth_files=(
            "$HOME/.openclaw/agents/main/agent/auth-profiles.json"
            "$HOME/.openclaw/agents/defaults/agent/auth-profiles.json"
        )

        for auth_file in "${auth_files[@]}"; do
            if [ -f "$auth_file" ]; then
                echo "  Checking: $auth_file"
                MINIMAX_API_KEY=$(python3 - "$auth_file" <<'PYEOF' 2>/dev/null
import json, sys
try:
    with open(sys.argv[1], 'r') as f:
        data = json.load(f)
        profiles = data.get('profiles', {})
        for name, profile in profiles.items():
            if profile.get('provider') == 'minimax' and profile.get('key'):
                print(profile['key'])
                sys.exit(0)
except Exception:
    pass
PYEOF
)
                if [ -n "$MINIMAX_API_KEY" ]; then
                    echo -e "${GREEN}✅ Read API key from: $auth_file${NC}"
                    break
                fi
            fi
        done

        # If still not found
        if [ -z "$MINIMAX_API_KEY" ]; then
            echo -e "${RED}❌ Cannot get MINIMAX_API_KEY${NC}"
            echo ""
            echo "Please provide API Key through one of the following ways:"
            echo "  1. Set environment variable: export MINIMAX_API_KEY=your_api_key"
            echo "  2. Ensure auth-profiles.json exists in ~/.openclaw/agents/main/agent/"
            echo ""
            exit 1
        fi
    else
        echo -e "${GREEN}✅ Using MINIMAX_API_KEY from environment variable${NC}"
    fi

    # Create config directory
    echo -e "${GREEN}📁 Creating config directory: ${CONFIG_DIR}${NC}"
    mkdir -p "${CONFIG_DIR}"/{workspace,identity,cron,canvas}
    mkdir -p "${CONFIG_DIR}/agents/defaults/agent"
    mkdir -p "${CONFIG_DIR}/agents/main/agent"
    # Fix permissions (directories must be 755, not 644)
    find "${CONFIG_DIR}" -type d -exec chmod 755 {} \;

    # Get available port
    PORT=$(find_port)
    echo -e "${GREEN}🔌 Assigning port: ${PORT}${NC}"

    # Generate openclaw.json (new format)
    echo -e "${GREEN}⚙️ Generating config file${NC}"

    # Generate different config based on whether Feishu is provided
    local HAS_FEISHU="false"
    local FEISHU_CONFIG=""
    local BINDINGS_CONFIG=""

    if [ -n "$FEISHU_APP_ID" ] && [ -n "$FEISHU_APP_SECRET" ]; then
        HAS_FEISHU="true"
        FEISHU_CONFIG=$(cat <<-FEISHU_JSON
      "enabled": true,
      "accounts": {
        "${NAME}": {
          "appId": "${FEISHU_APP_ID}",
          "appSecret": "${FEISHU_APP_SECRET}"
        },
        "default": {}
      },
      "default": {
        "groupPolicy": "allowlist",
        "dmPolicy": "open",
        "allowFrom": [],
        "requireMention": false
      }
FEISHU_JSON
)
        BINDINGS_CONFIG=$(cat <<-BINDINGS_JSON
  "bindings": [
    {
      "agentId": "defaults",
      "match": {
        "channel": "feishu",
        "accountId": "${NAME}"
      }
    }
  ],
BINDINGS_JSON
)
    else
        FEISHU_CONFIG=$(cat <<-FEISHU_JSON
      "enabled": false,
      "accounts": {},
      "default": {
        "groupPolicy": "denylist",
        "dmPolicy": "denylist"
      }
FEISHU_JSON
)
        BINDINGS_CONFIG=""
    fi

    cat > "${CONFIG_DIR}/openclaw.json" << EOF
{
  "meta": {
    "lastTouchedVersion": "2026.3.1",
    "lastTouchedAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  },
  "auth": {
    "profiles": {
      "minimax:default": {
        "provider": "minimax",
        "mode": "api_key"
      }
    }
  },
  "models": {
    "providers": {
      "minimax": {
        "baseUrl": "https://api.minimax.io/anthropic",
        "api": "anthropic-messages",
        "models": [
          {
            "id": "MiniMax-M2.5",
            "name": "MiniMax M2.5"
          }
        ]
      }
    }
  },
  "agents": {
    "defaults": {
      "model": {
        "primary": "minimax/MiniMax-M2.5"
      },
      "workspace": "${CONTAINER_OPENCLAW_DIR}/workspace"
    }
  },
${BINDINGS_CONFIG}
  "channels": {
    "feishu": {
${FEISHU_CONFIG}
    }
  },
  "gateway": {
    "mode": "local",
    "bind": "loopback",
    "port": ${PORT},
    "auth": {
      "mode": "token",
      "token": "$(openssl rand -hex 16)"
    }
  },
  "plugins": {
    "entries": {
      "feishu": {
        "enabled": ${HAS_FEISHU}
      }
    }
  }
}
EOF

    # Stop and remove old container (if exists)
    if container_exists "${CONTAINER_NAME}"; then
        echo -e "${YELLOW}🛑 Stopping old container${NC}"
        docker stop "${CONTAINER_NAME}" 2>/dev/null || true
        docker rm "${CONTAINER_NAME}" 2>/dev/null || true
    fi

    # Copy auth-profiles from main agent (contains API key config)
    echo -e "${GREEN}🔑 Copying auth configuration${NC}"
    cp -f "$HOME/.openclaw/agents/main/agent/auth-profiles.json" "${CONFIG_DIR}/agents/defaults/agent/" 2>/dev/null || true
    cp -f "$HOME/.openclaw/agents/main/agent/auth-profiles.json" "${CONFIG_DIR}/agents/main/agent/" 2>/dev/null || true
    # Also copy models.json to ensure agent has proper configuration
    cp -f "$HOME/.openclaw/agents/main/agent/models.json" "${CONFIG_DIR}/agents/defaults/agent/" 2>/dev/null || true
    cp -f "$HOME/.openclaw/agents/main/agent/models.json" "${CONFIG_DIR}/agents/main/agent/" 2>/dev/null || true

    # Fix permissions (use detected container UID)
    echo -e "${GREEN}🔒 Fixing config directory permissions (UID: ${CONTAINER_UID})${NC}"
    sudo chown -R ${CONTAINER_UID}:${CONTAINER_UID} "${CONFIG_DIR}"
    sudo chmod -R 644 "${CONFIG_DIR}/agents" 2>/dev/null || true
    sudo chmod -R 755 "${CONFIG_DIR}" 2>/dev/null || true

    # Build volume arguments as array (avoids eval+quoted string issues)
    local -a VOLUME_ARGS=(
        "-v" "${CONFIG_DIR}:${CONTAINER_OPENCLAW_DIR}"
    )
    if [ -d "$SHARED_DIR" ]; then
        VOLUME_ARGS+=("-v" "${SHARED_DIR}:${CONTAINER_HOME}/shared")
        echo -e "${GREEN}✅ Mounting shared directory: ${SHARED_DIR} -> ${CONTAINER_HOME}/shared${NC}"
    fi

    # Mount credentials directory for GitHub PEM file
    if [ -d "${CONFIG_DIR}/credentials" ]; then
        VOLUME_ARGS+=("-v" "${CONFIG_DIR}/credentials:${CONTAINER_HOME}/.github")
        echo -e "${GREEN}✅ Mounting credentials: ${CONFIG_DIR}/credentials -> ${CONTAINER_HOME}/.github${NC}"
    fi
    if [ -d "${TEAM_DIR}/team-config" ]; then
        VOLUME_ARGS+=("-v" "${TEAM_DIR}/team-config:/openclaw/team-config:ro")
        echo -e "${GREEN}✅ Mounting team config: ${TEAM_DIR}/team-config -> /openclaw/team-config${NC}"
    fi

    echo -e "${GREEN}📦 Container path mapping:${NC}"
    echo "  Config: ${CONFIG_DIR} -> ${CONTAINER_OPENCLAW_DIR}"
    [ -d "$SHARED_DIR" ] && echo "  Shared: ${SHARED_DIR} -> ${CONTAINER_HOME}/shared"
    [ -d "${TEAM_DIR}/team-config" ] && echo "  Team config: ${TEAM_DIR}/team-config -> /openclaw/team-config (read-only)"

    # Start new container
    # IMPORTANT: Must use bridge network mode (Docker default). Do NOT change to host network.
    # Reason: Host mode conflicts when multiple containers need same port (18789).
    #         Bridge mode isolates container networks and allows fixed port mapping.
    # Feishu connects via WebSocket (outbound connection from container to Feishu servers)
    # Use fixed port 18789 since bridge mode doesn't conflict with host
    echo -e "${GREEN}🐳 Starting container (UID: ${CONTAINER_UID})${NC}"
    docker run -d \
        --name "${CONTAINER_NAME}" \
        --restart unless-stopped \
        --memory 1.2G \
        --memory-swap 1.2G \
        --user ${CONTAINER_UID}:${CONTAINER_UID} \
        "${VOLUME_ARGS[@]}" \
        -e HOME=${CONTAINER_HOME} \
        -e NODE_ENV=production \
        -e AGENT_ROLE=member \
        -e MEMBER_NAME="${NAME}" \
        -e OPENCLAW_ALLOW_UNCONFIGURED=true \
        -e GATEWAY_PORT=18789 \
        -e MINIMAX_API_KEY="${MINIMAX_API_KEY}" \
        -e GITHUB_APP_ID="${GITHUB_APP_ID}" \
        -e GITHUB_APP_INSTALLATION_ID="${GITHUB_APP_INSTALLATION_ID}" \
        -e GITHUB_APP_PRIVATE_KEY_PATH="${GITHUB_APP_PRIVATE_KEY_PATH}" \
        -e JIRA_API_TOKEN="${JIRA_API_TOKEN}" \
        -e GRAFANA_API_TOKEN="${GRAFANA_API_TOKEN}" \
        openclaw-agent:latest \
        /bin/sh -c "openclaw gateway run --allow-unconfigured --port 18789 > /tmp/gateway.log 2>&1 & tail -f /dev/null"

    # Wait for container to start
    echo -e "${GREEN}⏳ Waiting for container to start...${NC}"
    sleep 8

    # Check container status
    if is_container_running "${CONTAINER_NAME}"; then
        echo -e "${GREEN}✅ Container started successfully!${NC}"

        # Note: Gateway is now started automatically via the command in docker run
        # Wait a bit more for gateway to initialize
        sleep 5

        # Check gateway log
        echo -e "${GREEN}📝 Checking gateway status...${NC}"
        docker exec "${CONTAINER_NAME}" cat /tmp/gateway.log 2>/dev/null | tail -10 || true

        # Note: Feishu SDK is now pre-installed in the Docker image
        # If needed, you can still install it manually:
        # docker exec -u 0 "${CONTAINER_NAME}" npm install -g @larksuiteoapi/node-sdk --silent 2>/dev/null || true

        # Ensure .bashrc exists before adding env vars (avoid syntax errors from broken .bashrc)
        echo -e "${GREEN}📝 Setting up .bashrc...${NC}"
        docker exec "${CONTAINER_NAME}" bash -c 'if [ ! -f "${HOME}/.bashrc" ] || ! grep -q "case \$- in" "${HOME}/.bashrc" 2>/dev/null; then cp /etc/skel/.bashrc "${HOME}/.bashrc"; fi'

        # Setup environment variables and GitHub key
        echo -e "${GREEN}🔧 Setting up environment variables and GitHub key...${NC}"
        
        # Read env vars from current environment (only if set)
        local ENV_VARS_CONTENT=""
        
        # Only add if environment variable is set
        [ -n "$JIRA_API_TOKEN" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport JIRA_API_TOKEN=\"${JIRA_API_TOKEN}\""
        [ -n "$GRAFANA_API_TOKEN" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport GRAFANA_API_TOKEN=\"${GRAFANA_API_TOKEN}\""
        [ -n "$CLINIC_API_KEY" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport CLINIC_API_KEY=\"${CLINIC_API_KEY}\""
        [ -n "$AWS_BEARER_TOKEN_BEDROCK" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport AWS_BEARER_TOKEN_BEDROCK=\"${AWS_BEARER_TOKEN_BEDROCK}\""
        [ -n "$AWS_REGION" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport AWS_REGION=\"${AWS_REGION}\""
        [ -n "$ANTHROPIC_MODEL" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport ANTHROPIC_MODEL=\"${ANTHROPIC_MODEL}\""
        [ -n "$CLAUDE_CODE_USE_BEDROCK" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport CLAUDE_CODE_USE_BEDROCK=${CLAUDE_CODE_USE_BEDROCK}"
        [ -n "$MINIMAX_API_KEY" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport MINIMAX_API_KEY=\"${MINIMAX_API_KEY}\""
        
        # Feishu related env vars
        [ -n "$FEISHU_ALERT_CHAT_ID" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport FEISHU_ALERT_CHAT_ID=\"${FEISHU_ALERT_CHAT_ID}\""
        
        # GitHub related - only if PEM file exists locally
        if [ -f "$HOME/.github/data-service-code-assist.pem" ]; then
            ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport GITHUB_REPO_LOC=\"~/github\""
            ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport GITHUB_APP_PRIVATE_KEY_PATH=\"~/.github/data-service-code-assist.pem\""
            # Also read GitHub env vars from host bashrc if not set
            [ -z "$GITHUB_APP_ID" ] && GITHUB_APP_ID=$(grep -m1 '^export GITHUB_APP_ID=' "$HOME/.bashrc" | cut -d'"' -f2)
            [ -z "$GITHUB_APP_INSTALLATION_ID" ] && GITHUB_APP_INSTALLATION_ID=$(grep -m1 '^export GITHUB_APP_INSTALLATION_ID=' "$HOME/.bashrc" | cut -d'"' -f2)
            [ -n "$GITHUB_APP_ID" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport GITHUB_APP_ID=\"${GITHUB_APP_ID}\""
            [ -n "$GITHUB_APP_INSTALLATION_ID" ] && ENV_VARS_CONTENT="${ENV_VARS_CONTENT}\nexport GITHUB_APP_INSTALLATION_ID=\"${GITHUB_APP_INSTALLATION_ID}\""
        fi
        
        # Write env vars to temp file and copy to container (only if there are vars to add)
        if [ -n "$ENV_VARS_CONTENT" ]; then
            echo "$ENV_VARS_CONTENT" > /tmp/env_vars_${NAME}.sh
            docker cp /tmp/env_vars_${NAME}.sh "${CONTAINER_NAME}:${CONTAINER_HOME}/env_vars.sh"
            docker exec "${CONTAINER_NAME}" bash -c "cat ${CONTAINER_HOME}/env_vars.sh >> ${CONTAINER_HOME}/.bashrc && rm ${CONTAINER_HOME}/env_vars.sh"
            rm /tmp/env_vars_${NAME}.sh
            echo -e "${GREEN}✅ Environment variables added to ~/.bashrc${NC}"
        else
            echo -e "${YELLOW}⚠️ No environment variables set, skipping${NC}"
        fi

        # Copy GitHub private key to container (only if exists locally)
        if [ -f "$HOME/.github/data-service-code-assist.pem" ]; then
            docker exec "${CONTAINER_NAME}" mkdir -p "${CONTAINER_HOME}/.github"
            docker cp "$HOME/.github/data-service-code-assist.pem" "${CONTAINER_NAME}:${CONTAINER_HOME}/.github/"
            echo -e "${GREEN}✅ GitHub private key copied to ~/.github/${NC}"
        else
            echo -e "${YELLOW}⚠️ GitHub private key not found locally, skipping${NC}"
        fi

        echo ""
        echo "=========================================="
        echo -e "${GREEN}🎉 Deployment complete!${NC}"
        echo "=========================================="
        echo "Config directory: ${CONFIG_DIR}"
        echo "Gateway port: ${PORT}"
        echo "Container name: ${CONTAINER_NAME}"
        echo ""
        echo "Next steps:"
        echo "  1. Have employee add the bot as friend in Feishu"
        echo "  2. Check logs: docker exec ${CONTAINER_NAME} openclaw logs"
    else
        echo -e "${RED}❌ Container failed to start${NC}"
        echo "View logs: docker logs ${CONTAINER_NAME}"
        exit 1
    fi
}

# Remove employee (keep config)
do_remove() {
    local NAME="$1"
    local FORCE="$2"

    if [ -z "$NAME" ]; then
        echo -e "${RED}❌ Please specify employee name${NC}"
        echo "Usage: $0 remove <name>"
        exit 1
    fi

    local CONTAINER_NAME="openclaw-${NAME}"
    local CONFIG_DIR="${CONFIG_BASE}/${CONTAINER_NAME}"

    echo -e "${YELLOW}🗑️ Removing employee container: ${CONTAINER_NAME}${NC}"
    echo "=========================================="

    check_docker

    # Check if container exists
    if ! container_exists "${CONTAINER_NAME}"; then
        echo -e "${RED}❌ Container does not exist: ${CONTAINER_NAME}${NC}"
        exit 1
    fi

    # Confirmation prompt
    if [ "$FORCE" != "-f" ] && [ "$FORCE" != "--force" ]; then
        echo -e "${YELLOW}⚠️ This operation will remove the container but keep the config directory${NC}"
        echo "Config directory: ${CONFIG_DIR}"
        echo ""

        # Check if interactive terminal
        if [ -t 0 ]; then
            read -p "Confirm deletion? [y/N] " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                echo "Cancelled"
                exit 0
            fi
        else
            echo -e "${RED}❌ Non-interactive environment, please use -f or --force parameter${NC}"
            exit 1
        fi
    fi

    # Stop container
    if is_container_running "${CONTAINER_NAME}"; then
        echo -e "${YELLOW}🛑 Stopping container${NC}"
        docker stop "${CONTAINER_NAME}" 2>/dev/null || true
    fi

    # Remove container
    echo -e "${YELLOW}🗑️ Removing container${NC}"
    docker rm "${CONTAINER_NAME}" 2>/dev/null || true

    echo ""
    echo -e "${GREEN}✅ Employee container removed (config preserved)${NC}"
    echo "Config directory: ${CONFIG_DIR}"
    echo ""
    echo "To redeploy: $0 add ${NAME}"
}

# Delete employee (remove config)
do_delete() {
    local NAME="$1"
    local FORCE="$2"

    if [ -z "$NAME" ]; then
        echo -e "${RED}❌ Please specify employee name${NC}"
        echo "Usage: $0 delete <name>"
        exit 1
    fi

    local CONTAINER_NAME="openclaw-${NAME}"
    local CONFIG_DIR="${CONFIG_BASE}/${CONTAINER_NAME}"

    echo -e "${RED}🗑️ Completely deleting employee: ${CONTAINER_NAME}${NC}"
    echo "=========================================="

    check_docker

    # Check existence
    local has_container=false
    local has_config=false

    if container_exists "${CONTAINER_NAME}"; then
        has_container=true
    fi

    if [ -d "$CONFIG_DIR" ]; then
        has_config=true
    fi

    if [ "$has_container" = "false" ] && [ "$has_config" = "false" ]; then
        echo -e "${RED}❌ Container or config not found: ${CONTAINER_NAME}${NC}"
        exit 1
    fi

    # Confirmation prompt
    if [ "$FORCE" != "-f" ] && [ "$FORCE" != "--force" ]; then
        echo -e "${RED}⚠️ Dangerous operation: will delete the following:${NC}"
        [ "$has_container" = "true" ] && echo "  - Docker container: ${CONTAINER_NAME}"
        [ "$has_config" = "true" ] && echo "  - Config directory: ${CONFIG_DIR}"
        echo ""
        echo -e "${RED}This operation is irreversible!${NC}"
        echo ""

        # Check if interactive terminal
        if [ -t 0 ]; then
            read -p "Confirm deletion? [y/N] " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                echo "Cancelled"
                exit 0
            fi
        else
            echo -e "${RED}❌ Non-interactive environment, please use -f or --force parameter${NC}"
            exit 1
        fi
    fi

    # Delete container
    if [ "$has_container" = "true" ]; then
        echo -e "${YELLOW}🛑 Stopping container${NC}"
        docker stop "${CONTAINER_NAME}" 2>/dev/null || true

        echo -e "${YELLOW}🗑️ Removing container${NC}"
        docker rm "${CONTAINER_NAME}" 2>/dev/null || true
    fi

    # Delete config directory
    if [ "$has_config" = "true" ]; then
        echo -e "${YELLOW}🗑️ Removing config directory${NC}"
        sudo rm -rf "$CONFIG_DIR"
    fi

    echo ""
    echo -e "${GREEN}✅ Employee completely deleted${NC}"
}

# Get Feishu App ID
get_feishu_appid() {
    local config_file="$1"

    if [ ! -f "$config_file" ]; then
        echo "-"
        return
    fi

    # Use python to parse JSON, get first account's appId
    # Pass config_file as argument to avoid shell variable interpolation issues
    local app_id
    app_id=$(python3 - "$config_file" << 'PYEOF' 2>/dev/null
import json
import sys

config_file = sys.argv[1]

try:
    with open(config_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

        # Try new format: channels.feishu.accounts.<account>.appId
        channels = data.get('channels', {})
        feishu = channels.get('feishu', {})
        accounts = feishu.get('accounts', {})

        if accounts:
            # Get first account's appId
            for account_name, account_data in accounts.items():
                app_id = account_data.get('appId', '')
                if app_id:
                    print(app_id)
                    sys.exit(0)

        # Try old format: channels.feishu.app-id
        app_id = feishu.get('app-id', '')
        if app_id:
            print(app_id)
            sys.exit(0)

        # Not found
        print('-')
except Exception as e:
    print('-')
    sys.exit(1)
PYEOF
) || app_id="-"

    echo "$app_id"
}

# Check if container is alive (Gateway running)
check_container_alive() {
    local container="$1"

    if ! is_container_running "$container"; then
        echo "-"
        return
    fi

    # Check if node process is running (OpenClaw gateway)
    if docker exec "$container" sh -c 'pgrep -f "openclaw.*gateway" >/dev/null 2>&1 || pgrep node >/dev/null 2>&1' &>/dev/null; then
        echo "✓"
    else
        echo "✗"
    fi
}

# List all containers (with config info)
do_list() {
    check_docker

    local containers=$(docker ps -a --filter "name=openclaw-" --format "{{.Names}}" 2>/dev/null | sort)

    if [ -z "$containers" ]; then
        echo "No team containers found"
        return
    fi

    # Header
    echo ""
    printf "%-25s | %-8s | %-6s | %-20s | %-6s | %s\n" "CONTAINER" "STATUS" "PORT" "FEISHU_APP_ID" "ALIVE" "CONFIG_PATH"
    echo "----------------------------------------------------------------------------------------------------------------------------"

    local running_count=0
    local stopped_count=0

    for container in $containers; do
        # Check status once and reuse
        local status
        if is_container_running "$container"; then
            status="running"
            running_count=$((running_count + 1))
        else
            status="stopped"
            stopped_count=$((stopped_count + 1))
        fi

        # Port
        local port=$(get_container_port "$container")

        # Config directory
        local config_dir
        if [ -d "${CONFIG_BASE}/${container}" ]; then
            config_dir="${CONFIG_BASE}/${container}"
        else
            config_dir="N/A"
        fi

        # Feishu App ID
        local feishu_appid="-"
        if [ -f "${CONFIG_BASE}/${container}/openclaw.json" ]; then
            feishu_appid=$(get_feishu_appid "${CONFIG_BASE}/${container}/openclaw.json")
        fi

        # Alive check
        local alive=$(check_container_alive "$container")

        printf "%-25s | %-8s | %-6s | %-20s | %-6s | %s\n" "$container" "$status" "$port" "$feishu_appid" "$alive" "$config_dir"
    done

    echo ""
    echo "Summary: Running: $running_count | Stopped: $stopped_count"
}

# Restart employee container
do_restart() {
    local NAME="$1"

    if [ -z "$NAME" ]; then
        echo -e "${RED}❌ Please specify employee name${NC}"
        echo "Usage: $0 restart <name>"
        exit 1
    fi

    local CONTAINER_NAME="openclaw-${NAME}"
    local CONFIG_DIR="${CONFIG_BASE}/${CONTAINER_NAME}"

    echo -e "${GREEN}🔄 Restarting employee container: ${CONTAINER_NAME}${NC}"
    echo "=========================================="

    check_docker

    # Check if container exists
    if ! container_exists "${CONTAINER_NAME}"; then
        echo -e "${RED}❌ Container does not exist: ${CONTAINER_NAME}${NC}"
        exit 1
    fi

    # Restart container
    echo -e "${YELLOW}🔄 Restarting container...${NC}"
    docker restart "${CONTAINER_NAME}"

    # Wait for container to start
    echo -e "${GREEN}⏳ Waiting for container to start...${NC}"
    sleep 5

    # Check if container is running
    if ! is_container_running "${CONTAINER_NAME}"; then
        echo -e "${RED}❌ Container failed to start${NC}"
        echo "View logs: docker logs ${CONTAINER_NAME}"
        exit 1
    fi

    echo -e "${GREEN}✅ Container restarted successfully${NC}"

    # Get port from config
    local PORT=$(get_container_port "$CONTAINER_NAME")

    # Start gateway
    echo -e "${GREEN}🌐 Starting gateway...${NC}"
    docker exec -d "${CONTAINER_NAME}" openclaw gateway run
    sleep 3

    # Verify gateway is running
    if [ "$PORT" != "-" ] && docker exec "${CONTAINER_NAME}" sh -c "timeout 2 bash -c '</dev/tcp/127.0.0.1/${PORT}' 2>/dev/null"; then
        echo -e "${GREEN}✅ Gateway is running on port ${PORT}${NC}"
    else
        echo -e "${YELLOW}⚠️ Gateway may still be starting, check with: docker exec ${CONTAINER_NAME} openclaw logs${NC}"
    fi

    echo ""
    echo "=========================================="
    echo -e "${GREEN}🎉 Restart complete!${NC}"
    echo "=========================================="
    echo "Container name: ${CONTAINER_NAME}"
    echo "Gateway port: ${PORT}"
    echo ""
    echo "Check status:"
    echo "  docker exec ${CONTAINER_NAME} openclaw gateway probe"
    echo "  docker logs ${CONTAINER_NAME}"
}

# Fix permissions for all config directories
do_fix_permissions() {
    check_docker

    echo -e "${GREEN}🔧 Fixing permissions for config directories${NC}"
    echo "=========================================="
    echo ""

    # Detect container UID once
    local CONTAINER_UID=$(detect_container_uid "openclaw-agent:latest")
    echo -e "${GREEN}Detected container UID: ${CONTAINER_UID}${NC}"
    echo ""

    local fixed_count=0
    local failed_count=0

    for config_dir in "${CONFIG_BASE}"/openclaw-*; do
        if [ ! -d "$config_dir" ]; then
            continue
        fi

        local container_name=$(basename "$config_dir")

        echo -e "${BLUE}Fixing: $container_name${NC}"

        # Try to fix ownership and permissions
        # First fix all directories (must be 755), then files (644)
        if sudo find "$config_dir" -type d -exec chmod 755 {} \; 2>/dev/null && \
           sudo find "$config_dir" -type f -exec chmod 644 {} \; 2>/dev/null && \
           sudo chown -R ${CONTAINER_UID}:${CONTAINER_UID} "$config_dir" 2>/dev/null; then
            echo -e "  ${GREEN}✓ Ownership set to ${CONTAINER_UID}:${CONTAINER_UID}${NC}"
            fixed_count=$((fixed_count + 1))
        else
            echo -e "  ${RED}✗ Failed to fix permissions${NC}"
            failed_count=$((failed_count + 1))
        fi
    done

    echo ""
    echo "=========================================="
    echo -e "${GREEN}Summary:${NC}"
    echo "  Fixed: $fixed_count"
    if [ $failed_count -gt 0 ]; then
        echo -e "  ${RED}Failed: $failed_count${NC}"
    fi
}

# Upgrade container to a specific image version
do_upgrade() {
    local NAME="$1"
    local TARGET="${2:-latest}"
    local CONTAINER_NAME="openclaw-${NAME}"
    local IMAGE_TAG="openclaw-agent:${TARGET}"

    if [ -z "$NAME" ]; then
        echo -e "${RED}❌ Usage: $0 upgrade <name> [version]${NC}"
        exit 1
    fi

    echo -e "${GREEN}⬆ Upgrading: ${CONTAINER_NAME} → ${IMAGE_TAG}${NC}"
    echo "=========================================="
    check_docker

    # Get current version
    local CURRENT_IMAGE
    CURRENT_IMAGE=$(docker inspect --format '{{.Config.Image}}' "${CONTAINER_NAME}" 2>/dev/null | sed 's|.*/||')
    if [ -z "$CURRENT_IMAGE" ]; then
        echo -e "${RED}❌ Container not found: ${CONTAINER_NAME}${NC}"
        exit 1
    fi
    echo -e "${GREEN}🔍 Current: ${CURRENT_IMAGE}${NC}"

    # Pull new image
    echo -e "${GREEN}📥 Pulling ${IMAGE_TAG}...${NC}"
    docker pull "${IMAGE_TAG}" || { echo -e "${RED}❌ Pull failed${NC}"; exit 1; }

    # Stop and remove
    echo -e "${YELLOW}🛑 Stopping old container...${NC}"
    docker stop "${CONTAINER_NAME}" 2>/dev/null || true
    docker rm "${CONTAINER_NAME}" 2>/dev/null || true

    # Use existing config
    local CONFIG_DIR="${CONFIG_BASE}/${CONTAINER_NAME}"
    [ ! -d "$CONFIG_DIR" ] && { echo -e "${RED}❌ Config not found${NC}"; exit 1; }

    local CONTAINER_HOME
    CONTAINER_HOME=$(detect_container_home "$IMAGE_TAG")
    local CONTAINER_UID
    CONTAINER_UID=$(detect_container_uid "$IMAGE_TAG")
    local CONTAINER_OPENCLAW_DIR="${CONTAINER_HOME}/.openclaw"

    local PORT
    PORT=$(get_container_port "$CONTAINER_NAME")
    [ "$PORT" = "-" ] || [ -z "$PORT" ] && PORT=18789
    echo -e "${GREEN}🔌 Port: ${PORT}${NC}"

    # Permissions
    sudo chown -R ${CONTAINER_UID}:${CONTAINER_UID} "${CONFIG_DIR}" 2>/dev/null || true
    sudo chmod -R 755 "${CONFIG_DIR}" 2>/dev/null || true

    # Auth profiles
    mkdir -p "${CONFIG_DIR}/agents/defaults/agent" "${CONFIG_DIR}/agents/main/agent"
    cp -f "$HOME/.openclaw/agents/main/agent/auth-profiles.json" "${CONFIG_DIR}/agents/defaults/agent/" 2>/dev/null || true
    cp -f "$HOME/.openclaw/agents/main/agent/auth-profiles.json" "${CONFIG_DIR}/agents/main/agent/" 2>/dev/null || true
    cp -f "$HOME/.openclaw/agents/main/agent/auth.json" "${CONFIG_DIR}/agents/defaults/agent/" 2>/dev/null || true
    cp -f "$HOME/.openclaw/agents/main/agent/auth.json" "${CONFIG_DIR}/agents/main/agent/" 2>/dev/null || true
    sudo chown -R ${CONTAINER_UID}:${CONTAINER_UID} "${CONFIG_DIR}/agents" 2>/dev/null || true

    # Volumes
    local -a VOLUME_ARGS=("-v" "${CONFIG_DIR}:${CONTAINER_OPENCLAW_DIR}")
    [ -d "$SHARED_DIR" ] && VOLUME_ARGS+=("-v" "${SHARED_DIR}:${CONTAINER_HOME}/shared")
    [ -d "${CONFIG_DIR}/credentials" ] && VOLUME_ARGS+=("-v" "${CONFIG_DIR}/credentials:${CONTAINER_HOME}/.github")
    [ -d "${TEAM_DIR}/team-config" ] && VOLUME_ARGS+=("-v" "${TEAM_DIR}/team-config:/openclaw/team-config:ro")

    # MINIMAX_API_KEY
    local MINIMAX_API_KEY_VAL="${MINIMAX_API_KEY}"
    if [ -z "$MINIMAX_API_KEY_VAL" ]; then
        for auth_file in "$HOME/.openclaw/agents/main/agent/auth-profiles.json" \
                        "$HOME/.openclaw/agents/defaults/agent/auth-profiles.json"; do
            [ ! -f "$auth_file" ] && continue
            MINIMAX_API_KEY_VAL=$(python3 - "$auth_file" 2>/dev/null <<'PYEOF'
import json, sys
try:
    with open(sys.argv[1]) as f:
        for p in json.load(f).get('profiles', {}).values():
            if p.get('provider') == 'minimax' and p.get('key'):
                print(p['key']); sys.exit(0)
except:
    pass
PYEOF
)
            [ -n "$MINIMAX_API_KEY_VAL" ] && break
        done
    fi

    # Start
    echo -e "${GREEN}🐳 Starting container (bridge, port ${PORT})${NC}"
    docker run -d \
        --name "${CONTAINER_NAME}" \
        --network bridge \
        --restart unless-stopped \
        --memory 1.2G \
        --memory-swap 1.2G \
        --user ${CONTAINER_UID}:${CONTAINER_UID} \
        "${VOLUME_ARGS[@]}" \
        -e HOME=${CONTAINER_HOME} \
        -e NODE_ENV=production \
        -e AGENT_ROLE=member \
        -e MEMBER_NAME="${NAME}" \
        -e OPENCLAW_ALLOW_UNCONFIGURED=true \
        -e GATEWAY_PORT=${PORT} \
        -e MINIMAX_API_KEY="${MINIMAX_API_KEY_VAL}" \
        -e GITHUB_APP_ID="${GITHUB_APP_ID}" \
        -e GITHUB_APP_INSTALLATION_ID="${GITHUB_APP_INSTALLATION_ID}" \
        -e GITHUB_APP_PRIVATE_KEY_PATH="${GITHUB_APP_PRIVATE_KEY_PATH}" \
        -e JIRA_API_TOKEN="${JIRA_API_TOKEN}" \
        -e GRAFANA_API_TOKEN="${GRAFANA_API_TOKEN}" \
        "${IMAGE_TAG}" \
        /bin/sh -c "openclaw gateway run --allow-unconfigured --port ${PORT} > /tmp/gateway.log 2>&1 & tail -f /dev/null"

    sleep 8

    if is_container_running "${CONTAINER_NAME}"; then
        echo ""
        echo "=========================================="
        echo -e "${GREEN}✅ Upgrade complete!${NC}"
        echo "  Image: ${CURRENT_IMAGE} → ${IMAGE_TAG}"
        echo "  Port: ${PORT}"
        echo "=========================================="
    else
        echo -e "${RED}❌ Container failed to start. Run: docker logs ${CONTAINER_NAME}${NC}"
        exit 1
    fi
}

# Rebuild container (delete and recreate using existing config)
# Rebuild container - delegates to do_upgrade with current image (preserve version)
do_rebuild() {
    local NAME="$1"

    if [ -z "$NAME" ]; then
        echo -e "${RED}❌ Usage: $0 rebuild <name>${NC}"
        exit 1
    fi

    local CONTAINER_NAME="openclaw-${NAME}"

    check_docker

    # Check if container exists
    if ! container_exists "${CONTAINER_NAME}"; then
        echo -e "${RED}❌ Container not found: ${CONTAINER_NAME}${NC}"
        echo "Use '$0 add ${NAME}' to create a new container."
        exit 1
    fi

    # Get current image version from running container
    local CURRENT_IMAGE
    CURRENT_IMAGE=$(docker inspect --format '{{.Config.Image}}' "${CONTAINER_NAME}" 2>/dev/null | sed 's|.*/||')
    if [ -z "$CURRENT_IMAGE" ]; then
        echo -e "${RED}❌ Cannot read current image for ${CONTAINER_NAME}${NC}"
        exit 1
    fi

    echo -e "${GREEN}🔄 Rebuilding: ${CONTAINER_NAME} (preserving image: ${CURRENT_IMAGE})${NC}"

    # Delegate to do_upgrade with the same image tag (no version change = rebuild)
    do_upgrade "${NAME}" "${CURRENT_IMAGE#openclaw-agent:}"
}

# Main command handler
COMMAND="$1"

case "$COMMAND" in
    add)
        do_add "$2" "$3" "$4"
        ;;
    upgrade)
        do_upgrade "$2" "$3"
        ;;
    rebuild)
        do_rebuild "$2" "$3"
        ;;
    restart)
        do_restart "$2"
        ;;
    remove)
        do_remove "$2" "$3"
        ;;
    delete)
        do_delete "$2" "$3"
        ;;
    list|status)
        do_list
        ;;
    fix-permissions|fix-perms)
        do_fix_permissions
        ;;
    *)
        usage
        ;;
esac
