name: Application Deployment

on:
  push:
    branches: [ main ]
    paths:
      - 'configuration/**'
      - 'containers/**'
      - '.gitea/workflows/deploy.yml'
  workflow_dispatch:
    inputs:
      environment:
        description: 'Target environment'
        required: true
        default: 'dev'
        type: choice
        options:
          - dev
          - staging
          - production

jobs:
  ansible-check:
    runs-on: ubuntu-latest
    name: Ansible Syntax Check
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install Ansible
        run: |
          pip install ansible ansible-core
          ansible-galaxy collection install community.general
          ansible-galaxy collection install ansible.posix
          ansible-galaxy collection install community.docker

      - name: Ansible syntax check
        run: |
          cd configuration
          for playbook in playbooks/*/*.yml; do
            if [ -f "$playbook" ]; then
              echo "Checking $playbook"
              ansible-playbook --syntax-check "$playbook"
            fi
          done

  deploy:
    runs-on: ubuntu-latest
    name: Deploy Applications
    needs: ansible-check
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install Ansible
        run: |
          pip install ansible ansible-core
          ansible-galaxy collection install community.general
          ansible-galaxy collection install ansible.posix
          ansible-galaxy collection install community.docker

      - name: Deploy applications
        run: |
          cd configuration
          ENV="${{ github.event.inputs.environment || 'dev' }}"
          ansible-playbook -i "inventories/${ENV}/inventory.ini" playbooks/bootstrap/main.yml
        env:
          ANSIBLE_HOST_KEY_CHECKING: False
