name: Hydra Deployment Manager (Odoo 14)

on:
  push:
    branches:
      - 'dev_**'
      - 'preprod_**'
      # - 'master_**' # ❌ Disabled auto-push to master (Production is Manual only as requested)
  
  workflow_dispatch:
    inputs:
      target_env:
        description: 'Target Environment'
        required: true
        type: choice
        options:
          - dev
          - preprod
          - prod
        default: 'dev'
      specific_host:
        description: 'Specific Server IP (Optional)'
        required: false
        type: string
        default: ''
      force_restart:
        description: 'Force Service Restart'
        required: true
        type: boolean
        default: true

jobs:
  deploy:
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - name: Extract Context
        id: context
        run: |
          REF_NAME=${{ github.ref_name }}
          EVENT_NAME=${{ github.event_name }}
          INPUT_ENV=${{ inputs.target_env }}
          
          echo "Processing Event: $EVENT_NAME on Ref: $REF_NAME"
          
          # Default values
          ENV=""
          MODULE=""
          PORT=""
          
          # Logic:
          # 1. PUSH EVENT (Auto)
          if [ "$EVENT_NAME" == "push" ]; then
             if [[ "$REF_NAME" == dev_* ]]; then
                ENV="dev"
                MODULE=${REF_NAME#dev_}
             elif [[ "$REF_NAME" == preprod_* ]]; then
                ENV="preprod"
                MODULE=${REF_NAME#preprod_}
             fi
             
          # 2. DISPATCH EVENT (Manual)
          elif [ "$EVENT_NAME" == "workflow_dispatch" ]; then
             ENV="$INPUT_ENV"
             
             # Extract module from branch name regardless of prefix
             # e.g. master_odex25_hr -> odex25_hr
             # e.g. dev_odex25_hr -> odex25_hr
             
             if [[ "$REF_NAME" == dev_* ]]; then
                MODULE=${REF_NAME#dev_}
             elif [[ "$REF_NAME" == preprod_* ]]; then
                MODULE=${REF_NAME#preprod_}
             elif [[ "$REF_NAME" == master_* ]]; then
                MODULE=${REF_NAME#master_}
             else
                # Fallback for non-standard branches? Maybe feature?
                # For now assume the user runs this on a valid tier branch
                echo "::error::Manual deployment must be run from a dev_, preprod_, or master_ branch to identify the module."
                exit 1
             fi
          fi
          
          # Set Port based on ENV
          if [ "$ENV" == "dev" ]; then
             PORT="14000"
          elif [ "$ENV" == "preprod" ]; then
             PORT="14010"
          elif [ "$ENV" == "prod" ]; then
             PORT="14069"
          fi
          
          echo "Resolved: ENV=$ENV, MODULE=$MODULE, PORT=$PORT"
          
          echo "ENV=$ENV" >> $GITHUB_OUTPUT
          echo "MODULE=$MODULE" >> $GITHUB_OUTPUT
          echo "PORT=$PORT" >> $GITHUB_OUTPUT

      - name: Deploy to Hydra Server (SSH)
        if: steps.context.outputs.ENV != ''
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ inputs.specific_host != '' && inputs.specific_host || secrets.HYDRA_HOST }}
          username: ${{ secrets.HYDRA_USER }}
          key: ${{ secrets.HYDRA_SSH_KEY }}
          port: 22
          script: |
            MODULE="${{ steps.context.outputs.MODULE }}"
            ENV="${{ steps.context.outputs.ENV }}"
            BRANCH="${{ github.ref_name }}"
            FORCE_RESTART="${{ inputs.force_restart }}"
            
            echo "🚀 Deploying $MODULE to $ENV Environment..."
            
            # Directory Mapping
            # Currently only DEV is mapped to /root/odoo-infra/odoo14/addons/custom_modules
            # Future structure:
            #   /root/odoo-infra/dev/custom_modules
            #   /root/odoo-infra/preprod/custom_modules
            #   /root/odoo-infra/prod/custom_modules
            
            if [ "$ENV" == "dev" ]; then
                TARGET_ROOT="/root/odoo-infra/odoo14/addons/custom_modules"
                SERVICE="odoo-14"  # We renamed it to generic odoo-14 for now, but logical dev
            else
                echo "🚧 Environment '$ENV' folder structure is not yet created on the server. Deployment simulated."
                exit 0
            fi
            
            TARGET_DIR="$TARGET_ROOT/$MODULE"
            
            if [ -d "$TARGET_DIR" ]; then
                cd "$TARGET_DIR"
                echo "⬇️ Pulling changes from $BRANCH..."
                git fetch origin
                git reset --hard origin/$BRANCH
                
                if [ "$FORCE_RESTART" == "true" ] || [ "${{ github.event_name }}" == "push" ]; then
                   echo "🔄 Restarting Service..."
                   cd /root/odoo-infra
                   docker compose restart $SERVICE
                fi
                
                echo "✅ Deployment Successful."
            else
                echo "⚠️ Module directory not found: $TARGET_DIR"
                exit 1
            fi
