name: Build cameras.db

on:
  push:
    branches: [main]
    paths:
      - "brands/**"
      - "presets/**"
      - "scripts/build_sqlite.py"
      - "scripts/generate_presets.py"
      - ".github/workflows/build.yml"
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v5

      - uses: actions/setup-python@v6
        with:
          python-version: "3.12"

      - name: Validate brand files
        run: python3 scripts/validate.py

      - name: Build cameras.db
        run: python3 scripts/build_sqlite.py -o cameras.db

      - name: Upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: cameras-db
          path: cameras.db
          retention-days: 30

      - name: Update latest release
        if: github.ref == 'refs/heads/main'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          COMMIT_SHA: ${{ github.sha }}
        run: |
          SHORT_SHA="${COMMIT_SHA:0:7}"
          DATE="$(date -u +%Y-%m-%d)"
          gh release delete latest --yes --cleanup-tag 2>/dev/null || true
          gh release create latest cameras.db \
            --title "Latest build" \
            --notes "Auto-built from \`${SHORT_SHA}\` on ${DATE}" \
            --prerelease

      - name: Create versioned release
        if: startsWith(github.ref, 'refs/tags/v')
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAG_REF: ${{ github.ref }}
        run: |
          TAG="${TAG_REF#refs/tags/}"
          gh release create "${TAG}" cameras.db \
            --title "${TAG}" \
            --generate-notes
