name: Sync Cloudflare DNS

on:
  push:
    paths:
      - 'ops/domains.yaml'
    branches:
      - main
  workflow_dispatch: # Allow manual triggers

jobs:
  sync-dns:
    name: Sync DNS Records to Cloudflare
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.10'
          cache: 'pip'

      - name: Install dependencies
        run: |
          pip install -r scripts/cloudflare/requirements.txt

      - name: Validate domains.yaml
        run: |
          python -c "import yaml; yaml.safe_load(open('ops/domains.yaml'))"

      - name: Sync DNS records (dry run)
        env:
          CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }}
          CF_ZONE_ID: ${{ secrets.CF_ZONE_ID }}
        run: |
          python scripts/cloudflare/sync_dns.py --dry-run

      - name: Sync DNS records
        env:
          CF_API_TOKEN: ${{ secrets.CF_API_TOKEN }}
          CF_ZONE_ID: ${{ secrets.CF_ZONE_ID }}
        run: |
          python scripts/cloudflare/sync_dns.py

      - name: Validate DNS configuration
        run: |
          python scripts/cloudflare/validate_dns.py --domain blackroad.systems --dns-only
        continue-on-error: true # Don't fail if DNS hasn't propagated yet

      - name: Comment on commit (if manual trigger)
        if: github.event_name == 'workflow_dispatch'
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.repos.createCommitComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              commit_sha: context.sha,
              body: '✅ Cloudflare DNS sync completed successfully!'
            })
