#!/usr/bin/env bash
# Deploy cube-cloud to AWS.
#
# Usage:
#   ./scripts/deploy.sh              # Full deploy (infra + build + push)
#   ./scripts/deploy.sh infra        # Terraform only
#   ./scripts/deploy.sh build        # Docker build + push only
#   ./scripts/deploy.sh seed-creds   # Seed admin Apollo credentials into Secrets Manager
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
REGION="us-west-2"
ACCOUNT_ID="992382448282"
ECR_REPO="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/cube-mcp/cube-cloud"
ECR_TBOT="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/cube-mcp/tbot"
TF_DIR="${REPO_ROOT}/infra/terraform"
STATE_BUCKET="cube-mcp-terraform-state"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
info()  { echo "==> $*"; }
error() { echo "ERROR: $*" >&2; exit 1; }

check_deps() {
    for cmd in aws docker terraform; do
        command -v "$cmd" &>/dev/null || error "$cmd is required but not found"
    done
}

# ---------------------------------------------------------------------------
# S3 backend bootstrap
# ---------------------------------------------------------------------------
ensure_state_bucket() {
    if aws s3api head-bucket --bucket "$STATE_BUCKET" --region "$REGION" 2>/dev/null; then
        info "State bucket '$STATE_BUCKET' exists"
        return
    fi
    info "Creating Terraform state bucket: $STATE_BUCKET"
    aws s3api create-bucket \
        --bucket "$STATE_BUCKET" \
        --region "$REGION" \
        --create-bucket-configuration LocationConstraint="$REGION"
    aws s3api put-bucket-versioning \
        --bucket "$STATE_BUCKET" \
        --versioning-configuration Status=Enabled
}

# ---------------------------------------------------------------------------
# Terraform
# ---------------------------------------------------------------------------
deploy_infra() {
    ensure_state_bucket
    info "Running terraform init + apply"
    cd "$TF_DIR"
    terraform init
    terraform apply -auto-approve
    cd "$REPO_ROOT"
}

# ---------------------------------------------------------------------------
# Docker build + ECR push
# ---------------------------------------------------------------------------
build_and_push() {
    info "Logging into ECR"
    aws ecr get-login-password --region "$REGION" \
        | docker login --username AWS --password-stdin "${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"

    info "Building cube-cloud image (linux/amd64)"
    docker build --platform linux/amd64 \
        -f packages/cube-cloud/Dockerfile \
        -t cube-cloud:latest \
        -t "${ECR_REPO}:latest" \
        "$REPO_ROOT"

    info "Pushing cube-cloud to ECR"
    docker push "${ECR_REPO}:latest"

    info "Building tbot sidecar image (linux/amd64)"
    docker build --platform linux/amd64 \
        -f infra/tbot/Dockerfile \
        -t tbot:latest \
        -t "${ECR_TBOT}:latest" \
        "${REPO_ROOT}/infra/tbot"

    info "Pushing tbot to ECR"
    docker push "${ECR_TBOT}:latest"

    info "Forcing ECS redeployment"
    aws ecs update-service \
        --cluster cube-mcp-prod-cluster \
        --service cube-mcp-prod-service \
        --force-new-deployment \
        --region "$REGION" \
        --no-cli-pager
}

# ---------------------------------------------------------------------------
# Seed admin credentials into Secrets Manager
# ---------------------------------------------------------------------------
seed_credentials() {
    APOLLO_CONFIG="$HOME/.palantir/apollo-cli.config"
    if [[ ! -f "$APOLLO_CONFIG" ]]; then
        error "Apollo config not found at $APOLLO_CONFIG"
    fi

    # Extract credentials from apollo-cli config (JSON format)
    CLIENT_ID=$(python3 -c "import json; print(json.load(open('$APOLLO_CONFIG'))['apollo-client-id'])")
    CLIENT_SECRET=$(python3 -c "import json; print(json.load(open('$APOLLO_CONFIG'))['apollo-client-secret'])")

    info "Seeding admin profile credentials into Secrets Manager"
    aws secretsmanager put-secret-value \
        --secret-id "cube-mcp/profiles/admin" \
        --secret-string "{\"client_id\":\"${CLIENT_ID}\",\"client_secret\":\"${CLIENT_SECRET}\"}" \
        --region "$REGION" 2>/dev/null \
    || aws secretsmanager create-secret \
        --name "cube-mcp/profiles/admin" \
        --secret-string "{\"client_id\":\"${CLIENT_ID}\",\"client_secret\":\"${CLIENT_SECRET}\"}" \
        --region "$REGION"

    info "Admin credentials seeded (client_id: ${CLIENT_ID:0:8}...)"
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
case "${1:-all}" in
    infra)
        check_deps
        deploy_infra
        ;;
    build)
        build_and_push
        ;;
    seed-creds)
        seed_credentials
        ;;
    all)
        check_deps
        deploy_infra
        build_and_push
        info "Done! MCP endpoint: https://cube.edgescaleai-cube.com/mcp"
        ;;
    *)
        echo "Usage: $0 {all|infra|build|seed-creds}"
        exit 1
        ;;
esac
