name: OpenTofu Apply
on:
  push:
    branches: [main]
    paths:
      - 'infrastructure/**'
  workflow_dispatch:
    inputs:
      environment:
        description: '部署环境'
        required: true
        default: 'dev'
        type: choice
        options:
          - dev
          - staging
          - production
      provider:
        description: '云服务商'
        required: true
        default: 'oracle-cloud'
        type: choice
        options:
          - oracle-cloud
          - huawei-cloud
          - google-cloud
          - digitalocean
          - aws

env:
  TOFU_VERSION: "1.10.6"

jobs:
  apply:
    runs-on: ubuntu-latest
    environment: ${{ github.event.inputs.environment || 'dev' }}
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        
      - name: Setup OpenTofu
        uses: opentofu/setup-opentofu@v1
        with:
          tofu_version: ${{ env.TOFU_VERSION }}
          
      - name: Configure credentials
        run: |
          PROVIDER="${{ github.event.inputs.provider || 'oracle-cloud' }}"
          echo "Setting up credentials for $PROVIDER"
          
          case "$PROVIDER" in
            "oracle-cloud")
              mkdir -p ~/.oci
              echo "${{ secrets.OCI_PRIVATE_KEY }}" > ~/.oci/oci_api_key.pem
              chmod 600 ~/.oci/oci_api_key.pem
              ;;
            "huawei-cloud")
              export HW_ACCESS_KEY="${{ secrets.HW_ACCESS_KEY }}"
              export HW_SECRET_KEY="${{ secrets.HW_SECRET_KEY }}"
              ;;
            "google-cloud")
              echo "${{ secrets.GCP_SERVICE_ACCOUNT_KEY }}" > /tmp/gcp-key.json
              export GOOGLE_APPLICATION_CREDENTIALS="/tmp/gcp-key.json"
              ;;
            "digitalocean")
              export DIGITALOCEAN_TOKEN="${{ secrets.DO_TOKEN }}"
              ;;
            "aws")
              export AWS_ACCESS_KEY_ID="${{ secrets.AWS_ACCESS_KEY_ID }}"
              export AWS_SECRET_ACCESS_KEY="${{ secrets.AWS_SECRET_ACCESS_KEY }}"
              ;;
          esac
          
      - name: Create terraform.tfvars
        run: |
          ENV="${{ github.event.inputs.environment || 'dev' }}"
          cd infrastructure/environments/$ENV
          cat > terraform.tfvars << EOF
          environment = "$ENV"
          project_name = "mgmt"
          owner = "ben"
          
          # Oracle Cloud 配置
          oci_config = {
            tenancy_ocid     = "${{ secrets.OCI_TENANCY_OCID }}"
            user_ocid        = "${{ secrets.OCI_USER_OCID }}"
            fingerprint      = "${{ secrets.OCI_FINGERPRINT }}"
            private_key_path = "~/.oci/oci_api_key.pem"
            region           = "ap-seoul-1"
          }
          
          # 华为云配置
          huawei_config = {
            access_key = "${{ secrets.HW_ACCESS_KEY }}"
            secret_key = "${{ secrets.HW_SECRET_KEY }}"
            region     = "cn-north-4"
          }
          
          # Google Cloud 配置
          gcp_config = {
            project_id   = "${{ secrets.GCP_PROJECT_ID }}"
            region       = "asia-northeast3"
            zone         = "asia-northeast3-a"
            credentials  = "/tmp/gcp-key.json"
          }
          
          # DigitalOcean 配置
          do_config = {
            token  = "${{ secrets.DO_TOKEN }}"
            region = "sgp1"
          }
          
          # AWS 配置
          aws_config = {
            access_key = "${{ secrets.AWS_ACCESS_KEY_ID }}"
            secret_key = "${{ secrets.AWS_SECRET_ACCESS_KEY }}"
            region     = "ap-northeast-1"
          }
          EOF
          
      - name: OpenTofu Init
        run: |
          PROVIDER="${{ github.event.inputs.provider || 'oracle-cloud' }}"
          cd infrastructure/providers/$PROVIDER
          tofu init
          
      - name: OpenTofu Plan
        run: |
          ENV="${{ github.event.inputs.environment || 'dev' }}"
          PROVIDER="${{ github.event.inputs.provider || 'oracle-cloud' }}"
          cd infrastructure/providers/$PROVIDER
          tofu plan \
            -var-file="../../../environments/$ENV/terraform.tfvars" \
            -out=tfplan
            
      - name: OpenTofu Apply
        run: |
          PROVIDER="${{ github.event.inputs.provider || 'oracle-cloud' }}"
          cd infrastructure/providers/$PROVIDER
          tofu apply -auto-approve tfplan
          
      - name: Save State
        run: |
          ENV="${{ github.event.inputs.environment || 'dev' }}"
          PROVIDER="${{ github.event.inputs.provider || 'oracle-cloud' }}"
          cd infrastructure/providers/$PROVIDER
          
          # 这里可以配置远程状态存储
          # 例如上传到 S3, GCS, 或其他存储
          echo "State saved locally for now"
          
      - name: Generate Inventory
        run: |
          ENV="${{ github.event.inputs.environment || 'dev' }}"
          PROVIDER="${{ github.event.inputs.provider || 'oracle-cloud' }}"
          cd infrastructure/providers/$PROVIDER
          
          # 生成 Ansible 动态清单
          tofu output -json > ../../../configuration/inventories/$ENV/$PROVIDER-inventory.json
          
      - name: Trigger Ansible Deployment
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.actions.createWorkflowDispatch({
              owner: context.repo.owner,
              repo: context.repo.repo,
              workflow_id: 'ansible-deploy.yml',
              ref: 'main',
              inputs: {
                environment: '${{ github.event.inputs.environment || "dev" }}',
                provider: '${{ github.event.inputs.provider || "oracle-cloud" }}'
              }
            });