#!/bin/bash
# BreakPilot Compliance SDK - Mac Studio Setup Script
# Hardware: Mac Studio M2 Ultra, 512GB RAM
# Enterprise/Airgapped deployment

set -e

echo "=============================================="
echo "BreakPilot Compliance SDK - Mac Studio Setup"
echo "Enterprise Edition"
echo "=============================================="

# Check prerequisites
check_prerequisites() {
    echo "Checking prerequisites..."

    # Check Docker
    if ! command -v docker &> /dev/null; then
        echo "Error: Docker is not installed"
        exit 1
    fi

    # Check memory
    TOTAL_MEM=$(sysctl -n hw.memsize)
    TOTAL_MEM_GB=$((TOTAL_MEM / 1024 / 1024 / 1024))

    if [ "$TOTAL_MEM_GB" -lt 256 ]; then
        echo "Warning: This setup is optimized for 512GB RAM"
        echo "Current memory: ${TOTAL_MEM_GB}GB"
        read -p "Continue anyway? (y/N) " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi

    # Check Ollama
    if ! command -v ollama &> /dev/null; then
        echo "Installing Ollama..."
        curl -fsSL https://ollama.com/install.sh | sh
    fi

    echo "Prerequisites OK"
}

# Configure Docker for enterprise
configure_docker() {
    echo "Configuring Docker for enterprise deployment..."

    echo ""
    echo "Please ensure Docker Desktop is configured with:"
    echo "  - Memory: 256 GB (recommended)"
    echo "  - CPUs: 20+ (recommended)"
    echo "  - Disk: 500 GB (minimum)"
    echo ""
    read -p "Press Enter when Docker is configured..."
}

# Install LLM models
install_models() {
    echo "Installing LLM models..."

    # Pull embedding model
    echo "Pulling embedding model (bge-m3)..."
    ollama pull bge-m3

    # Pull main LLM (larger model for Mac Studio)
    echo "Pulling Qwen 2.5 40B (this will take a while)..."
    ollama pull qwen2.5:40b

    echo "Models installed successfully"
}

# Create environment file
create_env_file() {
    echo "Creating environment file..."

    if [ -f .env ]; then
        echo ".env file already exists"
        read -p "Overwrite? (y/N) " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            return
        fi
    fi

    # Generate strong secrets
    JWT_SECRET=$(openssl rand -hex 64)
    DB_PASSWORD=$(openssl rand -hex 32)
    MINIO_SECRET=$(openssl rand -hex 32)
    GRAFANA_PASSWORD=$(openssl rand -base64 24)

    cat > .env << EOF
# BreakPilot Compliance SDK - Enterprise Environment Configuration
# Mac Studio M2 Ultra
# Generated on $(date)

# Database
DB_PASSWORD=${DB_PASSWORD}

# JWT (64 bytes for enterprise)
JWT_SECRET=${JWT_SECRET}

# MinIO
MINIO_ACCESS_KEY=breakpilot
MINIO_SECRET_KEY=${MINIO_SECRET}

# Grafana
GRAFANA_PASSWORD=${GRAFANA_PASSWORD}

# Maintenance
MAINTENANCE_API_KEY=
DEVICE_ID=mac-studio-$(hostname | tr '[:upper:]' '[:lower:]')
EOF

    chmod 600 .env
    echo ".env file created with secure permissions"
}

# Create supporting files
create_config_files() {
    echo "Creating configuration files..."

    # Qdrant config
    cat > qdrant-config.yaml << 'EOF'
storage:
  storage_path: /qdrant/storage
  snapshots_path: /qdrant/snapshots

service:
  host: 0.0.0.0
  http_port: 6333
  grpc_port: 6334

cluster:
  enabled: false

telemetry_disabled: true

optimizers_config:
  default_segment_number: 8
  max_segment_size_kb: 204800
  memmap_threshold_kb: 51200
  indexing_threshold_kb: 20000
EOF

    # Prometheus config
    cat > prometheus.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'api-gateway'
    static_configs:
      - targets: ['api-gateway:8080']

  - job_name: 'compliance-engine'
    static_configs:
      - targets: ['compliance-engine:8081']

  - job_name: 'rag-service'
    static_configs:
      - targets: ['rag-service:8082']

  - job_name: 'postgres'
    static_configs:
      - targets: ['postgres:5432']

  - job_name: 'redis'
    static_configs:
      - targets: ['redis:6379']
EOF

    # Backup script
    cat > backup.sh << 'EOF'
#!/bin/sh
DATE=$(date +%Y%m%d_%H%M%S)
pg_dump -Fc compliance > /backup/compliance_${DATE}.dump
find /backup -name "*.dump" -mtime +7 -delete
echo "Backup completed: compliance_${DATE}.dump"
EOF
    chmod +x backup.sh

    # Create directories
    mkdir -p pg-backup grafana-dashboards

    echo "Configuration files created"
}

# Start services
start_services() {
    echo "Starting services..."

    docker compose up -d

    echo "Waiting for services to be ready..."
    sleep 30

    # Check health
    echo "Checking service health..."
    docker compose ps
}

# Print summary
print_summary() {
    echo ""
    echo "=============================================="
    echo "Enterprise Setup Complete!"
    echo "=============================================="
    echo ""
    echo "Services:"
    echo "  API Gateway:     https://localhost"
    echo "  PostgreSQL:      localhost:5432"
    echo "  Redis:           localhost:6379"
    echo "  Qdrant:          localhost:6333"
    echo "  MinIO Console:   http://localhost:9001"
    echo "  Prometheus:      http://localhost:9090"
    echo "  Grafana:         http://localhost:3000"
    echo ""
    echo "LLM Models (via Ollama on host):"
    echo "  Embedding: bge-m3"
    echo "  Chat:      qwen2.5:40b (Enterprise)"
    echo ""
    echo "Security:"
    echo "  - All secrets stored in .env (chmod 600)"
    echo "  - Database backups: daily, 7-day retention"
    echo "  - Monitoring: Prometheus + Grafana"
    echo ""
    echo "Commands:"
    echo "  Start:    docker compose up -d"
    echo "  Stop:     docker compose down"
    echo "  Logs:     docker compose logs -f [service]"
    echo "  Backup:   docker compose exec backup /backup.sh"
    echo ""
}

# Main
main() {
    check_prerequisites
    configure_docker
    install_models
    create_env_file
    create_config_files
    start_services
    print_summary
}

main "$@"
