#!/bin/bash
set -e

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-vacations-service ==="

# Configuration
SERVICE_NAME="tbi-rlv-vacations-service"
NAMESPACE="redtag"
ENVIRONMENT="${DEPLOY_ENV:-dev}"
AWS_REGION="${AWS_REGION:-ca-central-1}"
TBI_ENVIRONMENTS_BRANCH="${TBI_ENVIRONMENTS_BRANCH:-master}"
HELM_S3_BUCKET="${HELM_S3_BUCKET:-tbi-charts}"

CLUSTER_NAME="${CLUSTER_NAME:-${ENVIRONMENT}}"
if [ -z "${CLUSTER_NAME}" ]; then echo "ERROR: CLUSTER_NAME not set!"; exit 1; fi
if [ -z "${AWS_ACCOUNT_ID}" ]; then echo "ERROR: AWS_ACCOUNT_ID not set!"; exit 1; fi
if [ -z "${GITHUB_TOKEN}" ]; then echo "ERROR: GITHUB_TOKEN not set!"; exit 1; fi

# Clean URL - no inline token (credential helper supplies it at request time)
TBI_ENVIRONMENTS_REPO="https://github.com/redlabelvacations/tbi-environments.git"

if [ -f "IMAGE_TAG" ]; then
    CHART_VERSION=$(cat IMAGE_TAG | tr -d '[:space:]')
else
    BASE_VERSION=$(cat VERSION | tr -d '[:space:]')
    CHART_VERSION="${BASE_VERSION}-${CIRCLE_BRANCH}-${CIRCLE_BUILD_NUM}"
fi

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

package_helm_chart() {
    echo "=== Packaging Helm chart for ${SERVICE_NAME} ==="
    local chart_path="tbi-devops-environments/${ENVIRONMENT}/${SERVICE_NAME}/charts/${SERVICE_NAME}"
    if [ ! -d "${chart_path}" ]; then
        echo "ERROR: Chart directory 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
}

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

clone_tbi_environments() {
    rm -rf /tmp/tbi-environments
    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
    # Persist the helper so the later git push also authenticates
    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 "ERROR: Requirements file 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
}

update_values_file() {
    local values_file="/tmp/tbi-environments/${ENVIRONMENT}/values/${SERVICE_NAME}.yaml"
    if [ ! -f "${values_file}" ]; then echo "ERROR: Values file 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
}

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 ${ENVIRONMENT}/requirements.yaml
    if git diff --cached --quiet; then
        echo "No changes detected - skipping commit"
    else
        git commit -m "Update ${SERVICE_NAME} to ${CHART_VERSION}

Deployed by CircleCI build #${CIRCLE_BUILD_NUM}
Branch: ${CIRCLE_BRANCH}"
        git_push_with_retry "${TBI_ENVIRONMENTS_BRANCH}"
    fi
}

deploy_service() {
    cd /tmp/tbi-environments
    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 successfully"
}

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

echo "=== Deployment Complete: ${SERVICE_NAME} v${CHART_VERSION} ==="

# ============================================================================
# Blue Rewards variant deploy (shared image, separate release/namespace).
# Reuses the SAME image (${CHART_VERSION}) built in this run — no rebuild.
# Deploys tbi-rlv-vacations-bluerewards-service to the redtagbluerewards namespace.
# ============================================================================
deploy_bluerewards_variant() {
    local variant="tbi-rlv-vacations-bluerewards-service"
    local primary_image_name="tbi-rlv-vacations-service"
    local variant_ns="redtagbluerewards"
    local ecr_registry="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
    local image_url="${ecr_registry}/${primary_image_name}:${CHART_VERSION}"

    # Resolve absolute path to the tbi-devops-environments checkout (CWD is
    # /tmp/tbi-environments after the primary deploy step).
    local devops_root
    if [ -d "${CIRCLE_WORKING_DIRECTORY:-}/tbi-devops-environments" ]; then
        devops_root="${CIRCLE_WORKING_DIRECTORY}/tbi-devops-environments"
    elif [ -d "${HOME}/project/tbi-devops-environments" ]; then
        devops_root="${HOME}/project/tbi-devops-environments"
    elif [ -d "./tbi-devops-environments" ]; then
        devops_root="$(pwd)/tbi-devops-environments"
    else
        echo "ERROR: could not locate tbi-devops-environments checkout for Blue Rewards deploy"
        return 1
    fi

    echo ""
    echo "=== Blue Rewards: deploying ${variant} (image: ${image_url}) ==="

    local chart_path="${devops_root}/${ENVIRONMENT}/${variant}/charts/${variant}"
    if [ ! -d "${chart_path}" ]; then
        echo "ERROR: Blue Rewards chart directory 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
    helm package ${chart_path} -d /tmp/helm-charts
    helm_s3_push_with_retry "/tmp/helm-charts/${variant}-${CHART_VERSION}.tgz" tbi-charts

    local values_file="/tmp/tbi-environments/${ENVIRONMENT}/values/${variant}.yaml"
    if [ ! -f "${values_file}" ]; then echo "ERROR: Blue Rewards values file not found: ${values_file}"; return 1; fi
    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

    local req_file="/tmp/tbi-environments/${ENVIRONMENT}/requirements.yaml"
    if [ -f "${req_file}" ]; then
        sed -i.bak "/name: ${variant}/,/version:/ s|version:.*|version: ${CHART_VERSION}|" ${req_file}
        rm -f ${req_file}.bak
    fi

    ( cd /tmp/tbi-environments
      git config user.name "CircleCI Bot"
      git config user.email "circleci@tbidevelopment.ca"
      git add "${ENVIRONMENT}/values/${variant}.yaml" "${ENVIRONMENT}/requirements.yaml"
      if git diff --cached --quiet; then
          echo "No Blue Rewards values changes to commit"
      else
          git commit -m "Update ${variant} to ${CHART_VERSION}

Shared image with ${primary_image_name}
Branch: ${CIRCLE_BRANCH} Build: ${CIRCLE_BUILD_NUM}"
          git_push_with_retry "${TBI_ENVIRONMENTS_BRANCH}"
      fi )

    ( cd /tmp/tbi-environments
      helm secrets upgrade --install \
          --namespace ${variant_ns} ${variant} \
          tbi-charts/${variant} \
          --set cluster="${CLUSTER_NAME}" \
          --version ${CHART_VERSION} \
          --reset-values \
          -f ./${ENVIRONMENT}/common.yaml \
          -f ./${ENVIRONMENT}/secrets.common.yaml \
          -f ./${ENVIRONMENT}/values/${variant}.yaml \
          -f ./${ENVIRONMENT}/secrets/secrets.${variant}.yaml
      kubectl rollout status deployment/${variant} -n ${variant_ns} --timeout=5m )

    echo "✅ ${variant}: ${CHART_VERSION} (Blue Rewards)"
}

deploy_bluerewards_variant
