#!/bin/bash
set -e

# Retry helm s3 push with backoff to handle S3 PreconditionFailed 412 race conditions
helm_s3_push_with_retry() {
    local chart_file="$1"
    local repo_name="$2"
    local max_retries=5
    local attempt=1
    local wait_time=5
    while [ $attempt -le $max_retries ]; do
        if helm s3 push "${chart_file}" "${repo_name}" --force 2>&1; then
            return 0
        fi
        echo "helm s3 push failed (attempt ${attempt}/${max_retries}), retrying in ${wait_time}s..."
        sleep $wait_time
        wait_time=$((wait_time * 2))
        attempt=$((attempt + 1))
    done
    echo "ERROR: helm s3 push failed after ${max_retries} attempts"
    return 1
}

git_push_with_retry() {
    local branch="${1:-master}"
    local max_retries=5
    local attempt=1
    while [ $attempt -le $max_retries ]; do
        if git push origin "$branch" 2>&1; then
            return 0
        fi
        echo "Push failed (attempt ${attempt}/${max_retries}), rebasing and retrying..."
        git pull --rebase origin "$branch"
        attempt=$((attempt + 1))
    done
    echo "ERROR: Failed to push after ${max_retries} attempts"
    return 1
}

echo "=== Starting deployment of tbi-rlv-profile-backend-service to PRODUCTION ==="

SERVICE_NAME="tbi-rlv-profile-backend-service"
NAMESPACE="redtag"
ENVIRONMENT="${DEPLOY_ENV:-prod}"
AWS_REGION="${AWS_REGION:-ca-central-1}"
TBI_ENVIRONMENTS_BRANCH="${TBI_ENVIRONMENTS_BRANCH:-master}"
HELM_S3_BUCKET="${HELM_S3_BUCKET:-tbi-charts-prod}"

echo ""
echo "🔒 PRODUCTION DEPLOYMENT SAFETY CHECKS"

if [ -z "${DEPLOY_ENV}" ]; then echo "❌ DEPLOY_ENV not set!"; exit 1; fi
if [ "${DEPLOY_ENV}" != "prod" ]; then echo "❌ DEPLOY_ENV=${DEPLOY_ENV}, expected prod"; exit 1; fi
echo "✅ DEPLOY_ENV verified: ${DEPLOY_ENV}"

if [ -z "${CLUSTER_NAME}" ]; then echo "❌ CLUSTER_NAME not set!"; exit 1; fi
if [[ ! "${CLUSTER_NAME}" =~ prod ]]; then echo "❌ CLUSTER_NAME doesn't contain 'prod': ${CLUSTER_NAME}"; exit 1; fi
echo "✅ Cluster verified: ${CLUSTER_NAME}"

if [ -z "${AWS_ACCOUNT_ID}" ]; then echo "❌ AWS_ACCOUNT_ID not set!"; exit 1; fi
if [ -z "${GITHUB_TOKEN}" ]; then echo "❌ GITHUB_TOKEN not set!"; exit 1; fi

TBI_ENVIRONMENTS_REPO="https://github.com/redlabelvacations/tbi-environments.git"

if [ -f "IMAGE_TAG" ]; then
    CHART_VERSION=$(cat IMAGE_TAG | tr -d '[:space:]')
else
    if [ ! -f "VERSION" ]; then echo "❌ VERSION file not found!"; exit 1; fi
    BASE_VERSION=$(cat VERSION | tr -d '[:space:]')
    CHART_VERSION="${BASE_VERSION}-${CIRCLE_BRANCH}-${CIRCLE_BUILD_NUM}"
fi

if [[ "${CHART_VERSION}" =~ (develop|qa|uat) ]]; then echo "❌ Cannot deploy dev/qa/uat tags to production: ${CHART_VERSION}"; exit 1; fi
if [[ "${CHART_VERSION}" == "latest" ]]; then echo "❌ 'latest' tag not allowed in production!"; exit 1; fi
echo "✅ Image tag validated: ${CHART_VERSION}"

echo ""
echo "🔒 Service: ${SERVICE_NAME} | Version: ${CHART_VERSION}"
echo "   Environment: ${ENVIRONMENT} | Cluster: ${CLUSTER_NAME} | Namespace: ${NAMESPACE}"

package_helm_chart() {
    local chart_path="tbi-devops-environments/${ENVIRONMENT}/${SERVICE_NAME}/charts/${SERVICE_NAME}"
    if [ ! -d "${chart_path}" ]; then echo "❌ Chart not found: ${chart_path}"; return 1; fi
    sed -i.bak "s|version:.*|version: ${CHART_VERSION}|g" ${chart_path}/Chart.yaml
    sed -i.bak "s|appVersion:.*|appVersion: \"${CHART_VERSION}\"|g" ${chart_path}/Chart.yaml
    rm -f ${chart_path}/Chart.yaml.bak
    mkdir -p /tmp/helm-charts
    helm package ${chart_path} -d /tmp/helm-charts
    echo "✅ Chart packaged"
}

push_chart_to_s3_repo() {
    local chart_file="/tmp/helm-charts/${SERVICE_NAME}-${CHART_VERSION}.tgz"
    if [ ! -f "${chart_file}" ]; then echo "❌ Chart file not found: ${chart_file}"; return 1; fi
    helm_s3_push_with_retry ${chart_file} tbi-charts
    echo "✅ Chart pushed to S3"
}

clone_tbi_environments() {
    rm -rf /tmp/tbi-environments
    # Authenticate via a credential helper (survives GitHub's redirect, unlike an
    # inline token in the URL), and persist it on the clone so the later push works.
    git -c credential.helper= \
        -c credential.helper='!f() { echo "username=x-access-token"; echo "password=${GITHUB_TOKEN}"; }; f' \
        clone "${TBI_ENVIRONMENTS_REPO}" /tmp/tbi-environments
    git -C /tmp/tbi-environments config credential.helper '!f() { echo "username=x-access-token"; echo "password=${GITHUB_TOKEN}"; }; f'
    cd /tmp/tbi-environments && git checkout ${TBI_ENVIRONMENTS_BRANCH}
}

update_requirements() {
    local req_file="/tmp/tbi-environments/${ENVIRONMENT}/requirements.yaml"
    if [ ! -f "${req_file}" ]; then echo "❌ Requirements not found: ${req_file}"; return 1; fi
    sed -i.bak "/name: ${SERVICE_NAME}/,/version:/ s|version:.*|version: ${CHART_VERSION}|" ${req_file}
    rm -f ${req_file}.bak
    echo "✅ requirements.yaml updated"
}

update_values_file() {
    local values_file="/tmp/tbi-environments/${ENVIRONMENT}/values/${SERVICE_NAME}.yaml"
    if [ ! -f "${values_file}" ]; then echo "❌ Values not found: ${values_file}"; return 1; fi
    local image_url="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${SERVICE_NAME}:${CHART_VERSION}"
    if grep -q "^image:" "${values_file}"; then
        sed -i.bak "s|^image:.*|image: ${image_url}|" ${values_file}
    else
        sed -i.bak "1 a\\
image: ${image_url}" ${values_file}
    fi
    rm -f ${values_file}.bak
    echo "✅ Values updated: ${image_url}"
}

push_values_update() {
    cd /tmp/tbi-environments
    git config user.name "CircleCI Bot"
    git config user.email "circleci@tbidevelopment.ca"
    git add ${ENVIRONMENT}/values/${SERVICE_NAME}.yaml
    git add ${ENVIRONMENT}/requirements.yaml
    if git diff --cached --quiet; then
        echo "ℹ️  No changes - already up to date"
    else
        git commit -m "🔒 PRODUCTION: Update ${SERVICE_NAME} to ${CHART_VERSION}

Deployed by CircleCI build #${CIRCLE_BUILD_NUM}
Branch: ${CIRCLE_BRANCH}
Environment: prod"
        git_push_with_retry "${TBI_ENVIRONMENTS_BRANCH}"
        echo "✅ Pushed to tbi-environments"
    fi
}

deploy_service() {
    cd /tmp/tbi-environments

    if [ -z "${AWS_ACCESS_KEY_ID}" ] || [ -z "${AWS_SECRET_ACCESS_KEY}" ]; then
        echo "❌ AWS credentials not set!"; exit 1
    fi

    mkdir -p ~/.aws
    cat > ~/.aws/credentials << EOF
[default]
aws_access_key_id = ${AWS_ACCESS_KEY_ID}
aws_secret_access_key = ${AWS_SECRET_ACCESS_KEY}
EOF
    cat > ~/.aws/config << EOF
[default]
region = ${AWS_REGION}
EOF

    # Override .sops.yaml to remove aws_profile
    cat > /tmp/tbi-environments/.sops.yaml << 'SOPSEOF'
creation_rules:
  - kms: arn:aws:kms:ca-central-1:495680544243:key/99547b03-9580-403f-8579-ea1595335830
SOPSEOF

    PROD_ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
    if [ "$PROD_ACCOUNT" != "489176460030" ]; then
        echo "❌ Not using production account! Got: $PROD_ACCOUNT"; exit 1
    fi
    echo "✅ Production credentials verified"

    helm secrets upgrade --install \
        --namespace ${NAMESPACE} ${SERVICE_NAME} \
        tbi-charts/${SERVICE_NAME} \
        --set cluster="${CLUSTER_NAME}" \
        --version ${CHART_VERSION} \
        --reset-values \
        -f ./${ENVIRONMENT}/common.yaml \
        -f ./${ENVIRONMENT}/secrets.common.yaml \
        -f ./${ENVIRONMENT}/values/${SERVICE_NAME}.yaml \
        -f ./${ENVIRONMENT}/secrets/secrets.${SERVICE_NAME}.yaml

    kubectl rollout status deployment/${SERVICE_NAME} -n ${NAMESPACE} --timeout=5m
    echo "✅ ${SERVICE_NAME} deployed to PRODUCTION"
}

package_helm_chart
helm repo add tbi-charts s3://${HELM_S3_BUCKET}/
push_chart_to_s3_repo
helm repo update
clone_tbi_environments
update_values_file
update_requirements
push_values_update
helm repo update
deploy_service

echo ""
echo "=== 🔒 PRODUCTION DEPLOYMENT COMPLETE ==="
echo "Service: ${SERVICE_NAME} | Version: ${CHART_VERSION} | Cluster: ${CLUSTER_NAME} | Namespace: ${NAMESPACE}"
