#!/usr/bin/env python3
"""
Script to update all remaining prod CircleCI configs with approval workflow and SNS notifications
"""

import re
from pathlib import Path

# Services to update (standard configs only)
STANDARD_SERVICES = [
    "tbi-acc-hotel-mapping-service",
    "tbi-acc-mybooking-service",
    "tbi-acc-notification-service",
    "tbi-acc-profile-service",
    "tbi-acc-profile-sync-service",
    "tbi-acc-quotes-service",
]

def update_config(service_name):
    """Update a single service config"""
    config_path = Path(f"prod/{service_name}/.circleci/config.yml")
    
    if not config_path.exists():
        print(f"❌ Config not found: {config_path}")
        return False
    
    content = config_path.read_text()
    
    # Check if already updated
    if "notify-await-build-approval" in content:
        print(f"✓ {service_name} already updated")
        return True
    
    print(f"→ Updating {service_name}...")
    
    # 1. Add two new jobs before deploy-to-kubernetes
    new_jobs = f'''  notify-await-build-approval:
    executor: aws-cli/default
    resource_class: small
    steps:
      - checkout
      - aws-cli/setup:
          profile_name: default
      - run:
          name: Send SNS notification - Awaiting BUILD approval
          command: |
            BASE_VERSION=$(cat VERSION | tr -d '[:space:]')

            cat > /tmp/sns-approval-needed.txt \\<< EOF
            ⏳ PRODUCTION Pipeline - Awaiting BUILD Approval

            Service: {service_name}
            Environment: PRODUCTION
            Build: #${{CIRCLE_BUILD_NUM}}
            Branch: ${{CIRCLE_BRANCH}}
            Commit: ${{CIRCLE_SHA1:0:7}}
            Image Tag: ${{BASE_VERSION}}
            Triggered by: ${{CIRCLE_USERNAME}}

            ✅ Tests have passed successfully

            ⏳ MANUAL APPROVAL REQUIRED to proceed with Docker image build

            To approve:
            1. Go to: ${{CIRCLE_BUILD_URL}}
            2. Click "Approve" on the approve-build job

            Once approved, the Docker image will be built and pushed to ECR.
            EOF

            aws sns publish \\
              --region ca-central-1 \\
              --topic-arn "arn:aws:sns:ca-central-1:489176460030:DevOps-alert" \\
              --subject "🔒 PROD Approval Needed: BUILD - {service_name} #${{CIRCLE_BUILD_NUM}}" \\
              --message file:///tmp/sns-approval-needed.txt

            echo "✓ SNS notification sent - awaiting BUILD approval"

  notify-await-deploy-approval:
    executor: aws-cli/default
    resource_class: small
    steps:
      - attach_workspace:
          at: .
      - aws-cli/setup:
          profile_name: default
      - run:
          name: Send SNS notification - Awaiting DEPLOY approval
          command: |
            IMAGE_TAG=$(cat IMAGE_TAG | tr -d '[:space:]')

            cat > /tmp/sns-deploy-approval.txt \\<< EOF
            ⏳ PRODUCTION Pipeline - Awaiting DEPLOY Approval

            Service: {service_name}
            Environment: PRODUCTION
            Namespace: access
            Build: #${{CIRCLE_BUILD_NUM}}
            Branch: ${{CIRCLE_BRANCH}}
            Commit: ${{CIRCLE_SHA1:0:7}}
            Image Tag: ${{IMAGE_TAG}}
            Triggered by: ${{CIRCLE_USERNAME}}

            ✅ Tests passed
            ✅ Docker image built and pushed to ECR

            ⏳ MANUAL APPROVAL REQUIRED to deploy to PRODUCTION cluster

            To approve:
            1. Go to: ${{CIRCLE_BUILD_URL}}
            2. Click "Approve" on the approve-deploy job

            ⚠️  WARNING: This will deploy to PRODUCTION Kubernetes cluster!
            ⚠️  Ensure the image has been tested and validated.

            Once approved, the service will be deployed to production.
            EOF

            aws sns publish \\
              --region ca-central-1 \\
              --topic-arn "arn:aws:sns:ca-central-1:489176460030:DevOps-alert" \\
              --subject "🔒 PROD Approval Needed: DEPLOY - {service_name} #${{CIRCLE_BUILD_NUM}}" \\
              --message file:///tmp/sns-deploy-approval.txt

            echo "✓ SNS notification sent - awaiting DEPLOY approval"

  deploy-to-kubernetes:
    executor: aws-cli/default
    resource_class: tbi-local-runner/prod-win'''
    
    # Replace deploy-to-kubernetes job header
    content = re.sub(
        r'  deploy-to-kubernetes:\n    executor: aws-cli/default\n    resource_class: tbi-local-runner/loadtest',
        new_jobs,
        content
    )
    
    # 2. Update image tagging logic in build-and-push-images
    old_tag_logic = '''      - run:
          name: Generate image tags
          command: |
            BASE_VERSION=$(cat VERSION | tr -d '[:space:]')
            IMAGE_TAG="${BASE_VERSION}-${CIRCLE_BRANCH}-${CIRCLE_BUILD_NUM}"
            echo "export IMAGE_TAG=${IMAGE_TAG}" >> $BASH_ENV
            echo "${IMAGE_TAG}" > IMAGE_TAG
            echo "Image tag: ${IMAGE_TAG}"'''
    
    new_tag_logic = '''      - run:
          name: Generate image tags
          command: |
            BASE_VERSION=$(cat VERSION | tr -d '[:space:]')
            # Production uses clean version tag (no branch/build suffix)
            if [ "${CIRCLE_BRANCH}" == "master" ] || [ "${CIRCLE_BRANCH}" == "main" ]; then
              IMAGE_TAG="${BASE_VERSION}"
              echo "🔒 PRODUCTION: Using clean version tag: ${IMAGE_TAG}"
            else
              IMAGE_TAG="${BASE_VERSION}-${CIRCLE_BRANCH}-${CIRCLE_BUILD_NUM}"
              echo "Image tag: ${IMAGE_TAG}"
            fi
            echo "export IMAGE_TAG=${IMAGE_TAG}" >> $BASH_ENV
            echo "${IMAGE_TAG}" > IMAGE_TAG'''
    
    content = content.replace(old_tag_logic, new_tag_logic)
    
    # 3. Update deploy job with SNS notifications
    old_deploy_step = '''      - run:
          name: Package Helm chart, update requirements, and deploy
          command: |
            chmod +x scripts/deploy-services.sh
            bash scripts/deploy-services.sh'''
    
    new_deploy_step = f'''      - run:
          name: Package Helm chart, update requirements, and deploy
          command: |
            # Verify DEPLOY_ENV is set from CircleCI context
            if [ -z "${{DEPLOY_ENV}}" ]; then
              echo "ERROR: DEPLOY_ENV not set in CircleCI context!"
              echo "Expected DEPLOY_ENV=prod from devops-mgt-prod context"
              exit 1
            fi

            echo "DEPLOY_ENV is set to: ${{DEPLOY_ENV}}"

            # Verify it matches expected value for PRODUCTION
            if [ "${{DEPLOY_ENV}}" != "prod" ]; then
              echo "WARNING: DEPLOY_ENV=${{DEPLOY_ENV}} but expected 'prod' for PRODUCTION deployment"
              echo "This will deploy to ${{DEPLOY_ENV}}/values/ instead of prod/values/"
              exit 1
            fi

            chmod +x scripts/deploy-services.sh
            bash scripts/deploy-services.sh
      - run:
          name: Send deployment success notification
          command: |
            IMAGE_TAG=$(cat IMAGE_TAG | tr -d '[:space:]')

            cat > /tmp/sns-message.txt \\<< EOF
            ✅ Deployment Successful - {service_name}

            Environment: ${{DEPLOY_ENV}}
            Namespace: access
            Image Tag: ${{IMAGE_TAG}}
            Build: #${{CIRCLE_BUILD_NUM}}
            Branch: ${{CIRCLE_BRANCH}}
            Commit: ${{CIRCLE_SHA1:0:7}}
            Triggered by: ${{CIRCLE_USERNAME}}

            View build: ${{CIRCLE_BUILD_URL}}
            EOF

            aws sns publish \\
              --region ca-central-1 \\
              --topic-arn "arn:aws:sns:ca-central-1:489176460030:DevOps-alert" \\
              --subject "DevOps CI/CD Pipeline Notification" \\
              --message file:///tmp/sns-message.txt

            echo "✓ Deployment success notification sent"
      - run:
          name: Send deployment failure notification
          when: on_fail
          command: |
            IMAGE_TAG=$(cat IMAGE_TAG 2>/dev/null | tr -d '[:space:]' || echo "unknown")

            cat > /tmp/sns-failure.txt \\<< EOF
            ❌ Deployment Failed - {service_name}

            Environment: ${{DEPLOY_ENV}}
            Namespace: access
            Image Tag: ${{IMAGE_TAG}}
            Build: #${{CIRCLE_BUILD_NUM}}
            Branch: ${{CIRCLE_BRANCH}}
            Commit: ${{CIRCLE_SHA1:0:7}}
            Triggered by: ${{CIRCLE_USERNAME}}

            View build: ${{CIRCLE_BUILD_URL}}

            Please check the build logs for error details.
            EOF

            aws sns publish \\
              --region ca-central-1 \\
              --topic-arn "arn:aws:sns:ca-central-1:489176460030:DevOps-alert" \\
              --subject "DevOps CI/CD Pipeline Notification" \\
              --message file:///tmp/sns-failure.txt

            echo "✓ Deployment failure notification sent"'''
    
    content = content.replace(old_deploy_step, new_deploy_step)
    
    # 4. Replace workflow
    # Find the workflow section and replace it
    workflow_pattern = r'# Workflows\nworkflows:.*?(?=\n\n|\Z)'
    
    new_workflow = f'''# Workflows
workflows:
  deploy-{service_name}:
    jobs:
      # Step 1: Run tests
      - lint-and-test:
          context: devops-mgt-prod
          filters:
            branches:
              only:
                - master

      # Step 2: Notify that BUILD approval is needed
      - notify-await-build-approval:
          context: devops-mgt-prod
          requires:
            - lint-and-test
          filters:
            branches:
              only:
                - master

      # Step 3: Manual approval to build (DevOps)
      - approve-build:
          type: approval
          requires:
            - notify-await-build-approval
          filters:
            branches:
              only:
                - master

      # Step 4: Build and push Docker image
      - build-and-push-images:
          context: devops-mgt-prod
          requires:
            - approve-build
          filters:
            branches:
              only:
                - master

      # Step 5: Notify that DEPLOY approval is needed
      - notify-await-deploy-approval:
          context: devops-mgt-prod
          requires:
            - build-and-push-images
          filters:
            branches:
              only:
                - master

      # Step 6: Manual approval to deploy (DevOps)
      - approve-deploy:
          type: approval
          requires:
            - notify-await-deploy-approval
          filters:
            branches:
              only:
                - master

      # Step 7: Deploy to production Kubernetes
      - deploy-to-kubernetes:
          context: devops-mgt-prod
          requires:
            - approve-deploy
          filters:
            branches:
              only:
                - master'''
    
    content = re.sub(workflow_pattern, new_workflow, content, flags=re.DOTALL)
    
    # Write back
    config_path.write_text(content)
    print(f"✓ {service_name} updated successfully")
    return True

def main():
    print(f"Updating {len(STANDARD_SERVICES)} standard prod configs...")
    print()
    
    success_count = 0
    for service in STANDARD_SERVICES:
        if update_config(service):
            success_count += 1
        print()
    
    print(f"✓ Updated {success_count}/{len(STANDARD_SERVICES)} configs")

if __name__ == "__main__":
    main()
