name: Deploy AgentLens

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:

env:
  COMPOSE_PROJECT_NAME: agentlens

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Docker CLI
        run: |
          curl -fsSL https://get.docker.com | sh

      - name: Write environment file
        run: |
          cat > .env << EOF
          AUTH_SECRET=${{ secrets.AUTH_SECRET }}
          STRIPE_SECRET_KEY=${{ secrets.STRIPE_SECRET_KEY }}
          STRIPE_WEBHOOK_SECRET=${{ secrets.STRIPE_WEBHOOK_SECRET }}
          POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }}
          REDIS_PASSWORD=${{ secrets.REDIS_PASSWORD }}
          EMAIL_PASSWORD=${{ secrets.EMAIL_PASSWORD }}
          EOF

      - name: Build and deploy
        run: |
          echo "Deploying AgentLens ${{ gitea.ref_name }}..."
          docker compose build web migrate
          docker compose up -d --no-deps --remove-orphans web migrate redis postgres
          echo "Waiting for migration and startup..."
          sleep 25

      - name: Health check
        run: |
          for i in 1 2 3 4 5; do
            STATUS=$(docker compose exec -T web wget -qO- http://127.0.0.1:3000/api/health 2>/dev/null || true)
            if [ -n "$STATUS" ]; then
              echo "Health check passed (attempt $i): $STATUS"
              exit 0
            fi
            echo "Attempt $i/5 — retrying in 10s..."
            sleep 10
          done
          echo "Health check failed after 5 attempts"
          docker compose logs web --tail 50
          exit 1

      - name: Cleanup
        if: always()
        run: docker image prune -f
