#!/bin/bash
#
# MPC-System Native Deployment Script (No Docker)
# For environments where Docker is not available (e.g., China)
#
# Usage:
#   ./scripts/deploy.sh install    # Install dependencies and build services
#   ./scripts/deploy.sh start      # Start all services
#   ./scripts/deploy.sh stop       # Stop all services
#   ./scripts/deploy.sh restart    # Restart all services
#   ./scripts/deploy.sh status     # Check service status
#   ./scripts/deploy.sh logs       # View logs
#   ./scripts/deploy.sh uninstall  # Remove all services
#

set -e

# ============================================
# Configuration
# ============================================
MPC_HOME="${MPC_HOME:-/opt/mpc-system}"
MPC_USER="${MPC_USER:-mpc}"
MPC_GROUP="${MPC_GROUP:-mpc}"
LOG_DIR="${MPC_HOME}/logs"
PID_DIR="${MPC_HOME}/pids"
BIN_DIR="${MPC_HOME}/bin"
CONFIG_DIR="${MPC_HOME}/config"
DATA_DIR="${MPC_HOME}/data"

# Service names
SERVICES=("account-service" "session-coordinator" "message-router" "server-party-1" "server-party-2" "server-party-3")

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# ============================================
# Helper Functions
# ============================================
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "This script must be run as root"
        exit 1
    fi
}

# ============================================
# Install Dependencies
# ============================================
install_dependencies() {
    log_info "Installing system dependencies..."

    # Update package list
    apt-get update

    # Install basic tools
    apt-get install -y curl wget git build-essential

    # Install Go 1.21
    log_info "Installing Go 1.21..."
    if ! command -v go &> /dev/null || [[ $(go version) != *"go1.21"* ]]; then
        wget -q https://go.dev/dl/go1.21.13.linux-amd64.tar.gz -O /tmp/go.tar.gz
        rm -rf /usr/local/go
        tar -C /usr/local -xzf /tmp/go.tar.gz
        rm /tmp/go.tar.gz

        # Add Go to PATH for all users
        echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh
        source /etc/profile.d/go.sh
    fi
    log_info "Go version: $(go version)"

    # Install PostgreSQL 15
    log_info "Installing PostgreSQL 15..."
    if ! command -v psql &> /dev/null; then
        apt-get install -y postgresql postgresql-contrib
        systemctl enable postgresql
        systemctl start postgresql
    fi

    # Install Redis
    log_info "Installing Redis..."
    if ! command -v redis-server &> /dev/null; then
        apt-get install -y redis-server
        systemctl enable redis-server
        systemctl start redis-server
    fi

    # Install RabbitMQ
    log_info "Installing RabbitMQ..."
    if ! command -v rabbitmqctl &> /dev/null; then
        # Install Erlang first
        apt-get install -y erlang-base erlang-nox erlang-dev erlang-src

        # Install RabbitMQ
        apt-get install -y rabbitmq-server
        systemctl enable rabbitmq-server
        systemctl start rabbitmq-server

        # Enable management plugin
        rabbitmq-plugins enable rabbitmq_management
    fi

    log_info "All dependencies installed successfully"
}

# ============================================
# Create User and Directories
# ============================================
setup_directories() {
    log_info "Setting up directories..."

    # Create mpc user if not exists
    if ! id "$MPC_USER" &>/dev/null; then
        useradd -r -s /bin/false -d "$MPC_HOME" "$MPC_USER"
    fi

    # Create directories
    mkdir -p "$MPC_HOME" "$LOG_DIR" "$PID_DIR" "$BIN_DIR" "$CONFIG_DIR" "$DATA_DIR"

    # Set permissions
    chown -R "$MPC_USER:$MPC_GROUP" "$MPC_HOME"
    chmod 755 "$MPC_HOME"

    log_info "Directories created at $MPC_HOME"
}

# ============================================
# Configure Infrastructure
# ============================================
configure_postgres() {
    log_info "Configuring PostgreSQL..."

    # Load environment variables - use MPC_ prefix variables (same as Go code uses)
    source "$CONFIG_DIR/mpc.env" 2>/dev/null || true

    local DB_USER="${MPC_DATABASE_USER:-mpc_user}"
    local DB_PASS="${MPC_DATABASE_PASSWORD:-your_secure_postgres_password_here}"
    local DB_NAME="${MPC_DATABASE_DBNAME:-mpc_system}"

    # Configure pg_hba.conf to allow password authentication for local connections
    local PG_HBA="/etc/postgresql/*/main/pg_hba.conf"
    for hba_file in $PG_HBA; do
        if [ -f "$hba_file" ]; then
            # Backup original
            cp "$hba_file" "${hba_file}.bak" 2>/dev/null || true
            # Change 'peer' to 'md5' for local connections to allow password auth
            sed -i 's/local   all             all                                     peer/local   all             all                                     md5/' "$hba_file"
            sed -i 's/host    all             all             127.0.0.1\/32            scram-sha-256/host    all             all             127.0.0.1\/32            md5/' "$hba_file"
            sed -i 's/host    all             all             ::1\/128                 scram-sha-256/host    all             all             ::1\/128                 md5/' "$hba_file"
            log_info "Updated pg_hba.conf at $hba_file"
        fi
    done

    # Reload PostgreSQL to apply pg_hba.conf changes
    systemctl reload postgresql 2>/dev/null || systemctl restart postgresql

    # Create database and user
    sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';" 2>/dev/null || \
        sudo -u postgres psql -c "ALTER USER $DB_USER WITH PASSWORD '$DB_PASS';"
    sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;" 2>/dev/null || true
    sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;" 2>/dev/null || true
    sudo -u postgres psql -d "$DB_NAME" -c "GRANT ALL ON SCHEMA public TO $DB_USER;" 2>/dev/null || true

    # Run migrations
    log_info "Running database migrations..."
    PGPASSWORD="$DB_PASS" psql -h 127.0.0.1 -U "$DB_USER" -d "$DB_NAME" -f "$MPC_HOME/migrations/001_init_schema.up.sql" 2>/dev/null || log_warn "Migration may have already been applied"

    log_info "PostgreSQL configured with user '$DB_USER' and database '$DB_NAME'"
}

configure_redis() {
    log_info "Configuring Redis..."

    source "$CONFIG_DIR/mpc.env" 2>/dev/null || true

    local REDIS_PASS="${REDIS_PASSWORD:-}"

    if [ -n "$REDIS_PASS" ]; then
        # Set Redis password
        sed -i "s/^# requirepass.*/requirepass $REDIS_PASS/" /etc/redis/redis.conf
        systemctl restart redis-server
    fi

    log_info "Redis configured"
}

configure_rabbitmq() {
    log_info "Configuring RabbitMQ..."

    source "$CONFIG_DIR/mpc.env" 2>/dev/null || true

    local RABBIT_USER="${RABBITMQ_USER:-mpc_user}"
    local RABBIT_PASS="${RABBITMQ_PASSWORD:-mpc_rabbit_password}"

    # Create user
    rabbitmqctl add_user "$RABBIT_USER" "$RABBIT_PASS" 2>/dev/null || rabbitmqctl change_password "$RABBIT_USER" "$RABBIT_PASS"
    rabbitmqctl set_permissions -p / "$RABBIT_USER" ".*" ".*" ".*"
    rabbitmqctl set_user_tags "$RABBIT_USER" administrator

    log_info "RabbitMQ configured"
}

# ============================================
# Build Services
# ============================================
build_services() {
    log_info "Building MPC services..."

    # Get the script's directory (where the source code is)
    local SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

    export PATH=$PATH:/usr/local/go/bin
    export GOPATH="$MPC_HOME/go"
    export GOPROXY="https://goproxy.cn,direct"  # Use Chinese proxy

    cd "$SOURCE_DIR"

    # Download dependencies
    log_info "Downloading Go dependencies..."
    go mod download

    # Build account service
    log_info "Building account-service..."
    go build -o "$BIN_DIR/account-service" ./services/account/cmd/server/

    # Build session coordinator
    log_info "Building session-coordinator..."
    go build -o "$BIN_DIR/session-coordinator" ./services/session-coordinator/cmd/server/

    # Build message router
    log_info "Building message-router..."
    go build -o "$BIN_DIR/message-router" ./services/message-router/cmd/server/

    # Build server party (single binary, different config for each party)
    log_info "Building server-party..."
    go build -o "$BIN_DIR/server-party" ./services/server-party/cmd/server/

    # Copy migrations
    cp -r "$SOURCE_DIR/migrations" "$MPC_HOME/"

    # Set permissions
    chmod +x "$BIN_DIR"/*
    chown -R "$MPC_USER:$MPC_GROUP" "$BIN_DIR"

    log_info "All services built successfully"
}

# ============================================
# Create Systemd Service Files
# ============================================
create_systemd_services() {
    log_info "Creating systemd service files..."

    # Common service template
    # Args: SERVICE_NAME, DESCRIPTION, EXEC_START, EXTRA_ENV (optional)
    create_service_file() {
        local SERVICE_NAME=$1
        local DESCRIPTION=$2
        local EXEC_START=$3
        local EXTRA_ENV=$4

        cat > "/etc/systemd/system/$SERVICE_NAME.service" << EOF
[Unit]
Description=MPC System - $DESCRIPTION
After=network.target postgresql.service redis-server.service rabbitmq-server.service
Wants=postgresql.service redis-server.service rabbitmq-server.service

[Service]
Type=simple
User=$MPC_USER
Group=$MPC_GROUP
WorkingDirectory=$MPC_HOME
EnvironmentFile=$CONFIG_DIR/mpc.env
${EXTRA_ENV:+$EXTRA_ENV}
ExecStart=$EXEC_START
Restart=always
RestartSec=5
StandardOutput=append:$LOG_DIR/$SERVICE_NAME.log
StandardError=append:$LOG_DIR/$SERVICE_NAME.error.log

# Security settings
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=$MPC_HOME

[Install]
WantedBy=multi-user.target
EOF
    }

    # Create service files with different gRPC ports to avoid conflicts
    # session-coordinator: gRPC 50051, HTTP 8081
    # message-router: gRPC 50052, HTTP 8082
    # server-party-1/2/3: HTTP 8083/8084/8085
    # account-service: HTTP 8080

    create_service_file "mpc-account" "Account Service" "$BIN_DIR/account-service" \
        "Environment=MPC_SERVER_HTTP_PORT=8080"

    create_service_file "mpc-session-coordinator" "Session Coordinator" "$BIN_DIR/session-coordinator" \
        "Environment=MPC_SERVER_GRPC_PORT=50051
Environment=MPC_SERVER_HTTP_PORT=8081"

    create_service_file "mpc-message-router" "Message Router" "$BIN_DIR/message-router" \
        "Environment=MPC_SERVER_GRPC_PORT=50052
Environment=MPC_SERVER_HTTP_PORT=8082"

    create_service_file "mpc-server-party-1" "Server Party 1" "$BIN_DIR/server-party" \
        "Environment=PARTY_ID=server-party-1
Environment=MPC_SERVER_HTTP_PORT=8083"

    create_service_file "mpc-server-party-2" "Server Party 2" "$BIN_DIR/server-party" \
        "Environment=PARTY_ID=server-party-2
Environment=MPC_SERVER_HTTP_PORT=8084"

    create_service_file "mpc-server-party-3" "Server Party 3" "$BIN_DIR/server-party" \
        "Environment=PARTY_ID=server-party-3
Environment=MPC_SERVER_HTTP_PORT=8085"

    # Reload systemd
    systemctl daemon-reload

    log_info "Systemd services created"
}

# ============================================
# Generate Secure Random Keys
# ============================================
generate_random_password() {
    # Generate a random 32-character alphanumeric password
    openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 32
}

generate_random_hex_key() {
    # Generate a random 64-character hex key (256-bit)
    openssl rand -hex 32
}

# ============================================
# Create Environment Configuration
# ============================================
create_env_config() {
    log_info "Creating environment configuration..."

    if [ ! -f "$CONFIG_DIR/mpc.env" ]; then
        # Generate secure random keys
        local POSTGRES_PASS=$(generate_random_password)
        local RABBITMQ_PASS=$(generate_random_password)
        local JWT_SECRET=$(generate_random_password)
        local API_KEY=$(generate_random_password)
        local MASTER_KEY=$(generate_random_hex_key)

        log_info "Generating secure random keys..."

        cat > "$CONFIG_DIR/mpc.env" << EOF
# MPC-System Environment Configuration
# Auto-generated secure keys - modify if needed

# Environment
ENVIRONMENT=production

# PostgreSQL Database
POSTGRES_USER=mpc_user
POSTGRES_PASSWORD=${POSTGRES_PASS}
MPC_DATABASE_HOST=localhost
MPC_DATABASE_PORT=5432
MPC_DATABASE_USER=mpc_user
MPC_DATABASE_PASSWORD=${POSTGRES_PASS}
MPC_DATABASE_DBNAME=mpc_system
MPC_DATABASE_SSLMODE=disable

# Redis Cache (empty = no password)
REDIS_PASSWORD=
MPC_REDIS_HOST=localhost
MPC_REDIS_PORT=6379
MPC_REDIS_PASSWORD=

# RabbitMQ Message Queue
RABBITMQ_USER=mpc_user
RABBITMQ_PASSWORD=${RABBITMQ_PASS}
MPC_RABBITMQ_HOST=localhost
MPC_RABBITMQ_PORT=5672
MPC_RABBITMQ_USER=mpc_user
MPC_RABBITMQ_PASSWORD=${RABBITMQ_PASS}

# JWT Configuration
JWT_SECRET_KEY=${JWT_SECRET}
MPC_JWT_SECRET_KEY=${JWT_SECRET}
MPC_JWT_ISSUER=mpc-system

# Crypto Master Key (64 hex characters = 256-bit key for encrypting key shares)
CRYPTO_MASTER_KEY=${MASTER_KEY}
MPC_CRYPTO_MASTER_KEY=${MASTER_KEY}

# API Security
MPC_API_KEY=${API_KEY}
ALLOWED_IPS=192.168.1.111

# Server Configuration
MPC_SERVER_ENVIRONMENT=production
# NOTE: MPC_SERVER_HTTP_PORT and MPC_SERVER_GRPC_PORT are set per-service in systemd unit files
# Do NOT set them here as they are service-specific:
#   session-coordinator: gRPC 50051, HTTP 8081
#   message-router: gRPC 50052, HTTP 8082
#   server-party-1/2/3: HTTP 8083/8084/8085
#   account-service: HTTP 8080

# Internal Service Addresses
SESSION_COORDINATOR_ADDR=localhost:50051
MESSAGE_ROUTER_ADDR=localhost:50052
EOF

        chmod 600 "$CONFIG_DIR/mpc.env"
        chown "$MPC_USER:$MPC_GROUP" "$CONFIG_DIR/mpc.env"

        log_info "Environment file created with auto-generated secure keys"
        log_info "Keys saved to: $CONFIG_DIR/mpc.env"
    else
        log_info "Environment file already exists"
    fi
}

# ============================================
# Regenerate Keys (for existing installation)
# ============================================
regenerate_keys() {
    check_root

    log_info "Regenerating secure keys..."

    local MASTER_KEY=$(generate_random_hex_key)
    local JWT_SECRET=$(generate_random_password)
    local API_KEY=$(generate_random_password)

    if [ -f "$CONFIG_DIR/mpc.env" ]; then
        # Replace CRYPTO_MASTER_KEY and MPC_CRYPTO_MASTER_KEY lines entirely
        # This handles any existing value, not just specific placeholders
        sed -i "s/^CRYPTO_MASTER_KEY=.*/CRYPTO_MASTER_KEY=${MASTER_KEY}/" "$CONFIG_DIR/mpc.env"
        sed -i "s/^MPC_CRYPTO_MASTER_KEY=.*/MPC_CRYPTO_MASTER_KEY=${MASTER_KEY}/" "$CONFIG_DIR/mpc.env"

        # Replace JWT keys
        sed -i "s/^JWT_SECRET_KEY=.*/JWT_SECRET_KEY=${JWT_SECRET}/" "$CONFIG_DIR/mpc.env"
        sed -i "s/^MPC_JWT_SECRET_KEY=.*/MPC_JWT_SECRET_KEY=${JWT_SECRET}/" "$CONFIG_DIR/mpc.env"

        # Replace API key
        sed -i "s/^MPC_API_KEY=.*/MPC_API_KEY=${API_KEY}/" "$CONFIG_DIR/mpc.env"

        log_info "Keys regenerated successfully"
        log_info "New MASTER_KEY: ${MASTER_KEY:0:16}..."
        log_info "New JWT_SECRET: ${JWT_SECRET:0:8}..."
        log_info "New API_KEY: ${API_KEY:0:8}..."
        log_info ""
        log_info "Now reconfigure PostgreSQL with new password and restart services:"
        log_info "  $0 reconfigure"
        log_info "  $0 restart"
    else
        log_error "Environment file not found: $CONFIG_DIR/mpc.env"
        exit 1
    fi
}

# ============================================
# Service Control Functions
# ============================================
start_services() {
    log_info "Starting MPC services..."

    # Start infrastructure first
    systemctl start postgresql
    systemctl start redis-server
    systemctl start rabbitmq-server

    sleep 3

    # Start MPC services in order
    systemctl start mpc-session-coordinator
    sleep 2
    systemctl start mpc-message-router
    sleep 2
    systemctl start mpc-server-party-1
    systemctl start mpc-server-party-2
    systemctl start mpc-server-party-3
    sleep 2
    systemctl start mpc-account

    log_info "All services started"
}

stop_services() {
    log_info "Stopping MPC services..."

    systemctl stop mpc-account 2>/dev/null || true
    systemctl stop mpc-server-party-1 2>/dev/null || true
    systemctl stop mpc-server-party-2 2>/dev/null || true
    systemctl stop mpc-server-party-3 2>/dev/null || true
    systemctl stop mpc-message-router 2>/dev/null || true
    systemctl stop mpc-session-coordinator 2>/dev/null || true

    log_info "All MPC services stopped"
}

restart_services() {
    stop_services
    sleep 2
    start_services
}

enable_services() {
    log_info "Enabling MPC services to start on boot..."

    systemctl enable mpc-session-coordinator
    systemctl enable mpc-message-router
    systemctl enable mpc-server-party-1
    systemctl enable mpc-server-party-2
    systemctl enable mpc-server-party-3
    systemctl enable mpc-account

    log_info "Services enabled"
}

status_services() {
    echo ""
    echo "============================================"
    echo "MPC System Service Status"
    echo "============================================"
    echo ""

    # Infrastructure
    echo "Infrastructure:"
    echo "  PostgreSQL:    $(systemctl is-active postgresql)"
    echo "  Redis:         $(systemctl is-active redis-server)"
    echo "  RabbitMQ:      $(systemctl is-active rabbitmq-server)"
    echo ""

    # MPC Services
    echo "MPC Services:"
    echo "  Session Coordinator: $(systemctl is-active mpc-session-coordinator)"
    echo "  Message Router:      $(systemctl is-active mpc-message-router)"
    echo "  Server Party 1:      $(systemctl is-active mpc-server-party-1)"
    echo "  Server Party 2:      $(systemctl is-active mpc-server-party-2)"
    echo "  Server Party 3:      $(systemctl is-active mpc-server-party-3)"
    echo "  Account Service:     $(systemctl is-active mpc-account)"
    echo ""

    # Health check
    echo "Health Check:"
    if curl -s http://localhost:8080/health > /dev/null 2>&1; then
        echo "  Account Service API: ${GREEN}OK${NC}"
    else
        echo "  Account Service API: ${RED}FAIL${NC}"
    fi
    echo ""
}

view_logs() {
    local SERVICE="${2:-mpc-account}"
    echo "Viewing logs for $SERVICE..."
    echo "Press Ctrl+C to exit"
    echo ""

    if [ -f "$LOG_DIR/$SERVICE.log" ]; then
        tail -f "$LOG_DIR/$SERVICE.log"
    else
        journalctl -u "$SERVICE" -f
    fi
}

# ============================================
# Install Command
# ============================================
install() {
    check_root

    log_info "Starting MPC-System installation..."

    install_dependencies
    setup_directories
    create_env_config

    log_warn "Please edit the configuration file: $CONFIG_DIR/mpc.env"
    log_warn "Then run: $0 build"
}

build() {
    check_root

    log_info "Building MPC-System..."

    build_services
    create_systemd_services
    configure_postgres
    configure_redis
    configure_rabbitmq
    enable_services

    log_info "Build complete!"
    log_info "Start services with: $0 start"
}

# ============================================
# Reconfigure Command (fix existing installation)
# ============================================
reconfigure() {
    check_root

    log_info "Reconfiguring MPC-System infrastructure..."

    configure_postgres
    configure_redis
    configure_rabbitmq

    log_info "Reconfiguration complete!"
    log_info "Restart services with: $0 restart"
}

# ============================================
# Fix Port Conflicts (remove global port settings from mpc.env)
# ============================================
fix_ports() {
    check_root

    log_info "Fixing port configuration..."

    if [ ! -f "$CONFIG_DIR/mpc.env" ]; then
        log_error "Environment file not found: $CONFIG_DIR/mpc.env"
        exit 1
    fi

    # Remove MPC_SERVER_HTTP_PORT and MPC_SERVER_GRPC_PORT from mpc.env
    # These should be set per-service in systemd unit files, not globally
    if grep -q "^MPC_SERVER_HTTP_PORT=" "$CONFIG_DIR/mpc.env"; then
        sed -i '/^MPC_SERVER_HTTP_PORT=/d' "$CONFIG_DIR/mpc.env"
        log_info "Removed MPC_SERVER_HTTP_PORT from mpc.env"
    fi

    if grep -q "^MPC_SERVER_GRPC_PORT=" "$CONFIG_DIR/mpc.env"; then
        sed -i '/^MPC_SERVER_GRPC_PORT=/d' "$CONFIG_DIR/mpc.env"
        log_info "Removed MPC_SERVER_GRPC_PORT from mpc.env"
    fi

    # Add explanatory comment if not already present
    if ! grep -q "# Port configuration is per-service" "$CONFIG_DIR/mpc.env"; then
        cat >> "$CONFIG_DIR/mpc.env" << 'EOF'

# Port configuration is per-service (set in systemd unit files):
#   session-coordinator: gRPC 50051, HTTP 8081
#   message-router: gRPC 50052, HTTP 8082
#   server-party-1/2/3: HTTP 8083/8084/8085
#   account-service: HTTP 8080
EOF
        log_info "Added port documentation to mpc.env"
    fi

    # Reload systemd and restart services
    systemctl daemon-reload

    log_info "Port configuration fixed!"
    log_info "Restart services with: $0 restart"
}

# ============================================
# Debug Command (troubleshooting)
# ============================================
debug() {
    echo ""
    echo "============================================"
    echo "MPC-System Debug Information"
    echo "============================================"
    echo ""

    # Load environment variables
    if [ -f "$CONFIG_DIR/mpc.env" ]; then
        source "$CONFIG_DIR/mpc.env"
        log_info "Loaded environment from $CONFIG_DIR/mpc.env"
    else
        log_error "Environment file not found: $CONFIG_DIR/mpc.env"
        return 1
    fi

    echo ""
    echo "=== Environment Variables ==="
    echo "MPC_DATABASE_HOST: ${MPC_DATABASE_HOST:-NOT SET}"
    echo "MPC_DATABASE_PORT: ${MPC_DATABASE_PORT:-NOT SET}"
    echo "MPC_DATABASE_USER: ${MPC_DATABASE_USER:-NOT SET}"
    echo "MPC_DATABASE_PASSWORD: ${MPC_DATABASE_PASSWORD:+SET (hidden)}"
    echo "MPC_DATABASE_DBNAME: ${MPC_DATABASE_DBNAME:-NOT SET}"
    echo "SESSION_COORDINATOR_ADDR: ${SESSION_COORDINATOR_ADDR:-NOT SET}"
    echo "MESSAGE_ROUTER_ADDR: ${MESSAGE_ROUTER_ADDR:-NOT SET}"
    echo ""

    echo "=== PostgreSQL Connection Test ==="
    local DB_USER="${MPC_DATABASE_USER:-mpc_user}"
    local DB_PASS="${MPC_DATABASE_PASSWORD:-}"
    local DB_NAME="${MPC_DATABASE_DBNAME:-mpc_system}"
    local DB_HOST="${MPC_DATABASE_HOST:-localhost}"

    # Test PostgreSQL connection with password
    echo "Testing connection to PostgreSQL..."
    if PGPASSWORD="$DB_PASS" psql -h 127.0.0.1 -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" > /dev/null 2>&1; then
        echo "  PostgreSQL connection: ${GREEN}OK${NC}"
    else
        echo "  PostgreSQL connection: ${RED}FAILED${NC}"
        echo ""
        echo "  Trying with verbose output:"
        PGPASSWORD="$DB_PASS" psql -h 127.0.0.1 -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" 2>&1 || true
        echo ""
        echo "  Check pg_hba.conf authentication method:"
        cat /etc/postgresql/*/main/pg_hba.conf 2>/dev/null | grep -v "^#" | grep -v "^$" | head -10
    fi
    echo ""

    echo "=== Redis Connection Test ==="
    if redis-cli ping > /dev/null 2>&1; then
        echo "  Redis connection: ${GREEN}OK${NC}"
    else
        echo "  Redis connection: ${RED}FAILED${NC}"
    fi
    echo ""

    echo "=== RabbitMQ Connection Test ==="
    if rabbitmqctl status > /dev/null 2>&1; then
        echo "  RabbitMQ status: ${GREEN}OK${NC}"
    else
        echo "  RabbitMQ status: ${RED}FAILED${NC}"
    fi
    echo ""

    echo "=== Port Listening Status ==="
    echo "  PostgreSQL (5432): $(ss -tlnp | grep ':5432' > /dev/null && echo 'LISTENING' || echo 'NOT LISTENING')"
    echo "  Redis (6379): $(ss -tlnp | grep ':6379' > /dev/null && echo 'LISTENING' || echo 'NOT LISTENING')"
    echo "  RabbitMQ (5672): $(ss -tlnp | grep ':5672' > /dev/null && echo 'LISTENING' || echo 'NOT LISTENING')"
    echo "  Session Coordinator gRPC (50051): $(ss -tlnp | grep ':50051' > /dev/null && echo 'LISTENING' || echo 'NOT LISTENING')"
    echo "  Message Router gRPC (50052): $(ss -tlnp | grep ':50052' > /dev/null && echo 'LISTENING' || echo 'NOT LISTENING')"
    echo "  Account Service HTTP (8080): $(ss -tlnp | grep ':8080' > /dev/null && echo 'LISTENING' || echo 'NOT LISTENING')"
    echo ""

    echo "=== Service Error Logs (last 10 lines) ==="
    for service in mpc-session-coordinator mpc-message-router mpc-server-party-1 mpc-account; do
        echo ""
        echo "--- $service ---"
        journalctl -u "$service" --no-pager -n 10 2>/dev/null || echo "No logs available"
    done
    echo ""

    echo "=== Manual Test Command ==="
    echo "Run this command to manually test a service:"
    echo ""
    echo "  sudo -u $MPC_USER bash -c 'source $CONFIG_DIR/mpc.env && $BIN_DIR/session-coordinator'"
    echo ""
}

# ============================================
# Uninstall Command
# ============================================
uninstall() {
    check_root

    log_warn "This will remove all MPC services and data!"
    read -p "Are you sure? (yes/no): " confirm

    if [ "$confirm" != "yes" ]; then
        log_info "Uninstall cancelled"
        exit 0
    fi

    stop_services

    # Disable and remove services
    for service in mpc-account mpc-session-coordinator mpc-message-router mpc-server-party-1 mpc-server-party-2 mpc-server-party-3; do
        systemctl disable "$service" 2>/dev/null || true
        rm -f "/etc/systemd/system/$service.service"
    done

    systemctl daemon-reload

    # Remove directories (keep data by default)
    rm -rf "$BIN_DIR" "$PID_DIR"

    log_info "MPC services removed"
    log_warn "Data directory preserved at: $DATA_DIR"
    log_warn "Config directory preserved at: $CONFIG_DIR"
    log_warn "To completely remove, run: rm -rf $MPC_HOME"
}

# ============================================
# Main
# ============================================
case "${1:-}" in
    install)
        install
        ;;
    build)
        build
        ;;
    reconfigure)
        reconfigure
        ;;
    regenerate-keys)
        regenerate_keys
        ;;
    fix-ports)
        fix_ports
        ;;
    debug)
        debug
        ;;
    start)
        start_services
        ;;
    stop)
        stop_services
        ;;
    restart)
        restart_services
        ;;
    status)
        status_services
        ;;
    logs)
        view_logs "$@"
        ;;
    uninstall)
        uninstall
        ;;
    *)
        echo "MPC-System Deployment Script"
        echo ""
        echo "Usage: $0 {install|build|reconfigure|regenerate-keys|fix-ports|debug|start|stop|restart|status|logs|uninstall}"
        echo ""
        echo "Commands:"
        echo "  install         - Install system dependencies (Go, PostgreSQL, Redis, RabbitMQ)"
        echo "  build           - Build services and configure infrastructure"
        echo "  reconfigure     - Reconfigure PostgreSQL/Redis/RabbitMQ (fix auth issues)"
        echo "  regenerate-keys - Regenerate secure keys (fix placeholder key issues)"
        echo "  fix-ports       - Fix port conflicts (remove global port settings from mpc.env)"
        echo "  debug           - Show debug information and test connections"
        echo "  start           - Start all MPC services"
        echo "  stop            - Stop all MPC services"
        echo "  restart         - Restart all MPC services"
        echo "  status          - Show service status"
        echo "  logs            - View service logs (use: $0 logs [service-name])"
        echo "  uninstall       - Remove MPC services"
        echo ""
        echo "Example:"
        echo "  $0 install       # First time setup (auto-generates secure keys)"
        echo "  $0 build         # Build and configure"
        echo "  $0 start         # Start services"
        echo "  $0 status        # Check status"
        echo ""
        echo "Troubleshooting:"
        echo "  $0 debug           # Show debug info and test DB connection"
        echo "  $0 reconfigure     # Fix database authentication issues"
        echo "  $0 regenerate-keys # Fix 'Invalid master key format' errors"
        echo "  $0 restart         # Then restart services"
        echo ""
        exit 1
        ;;
esac
