name: Deploy AgentLens

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

env:
  COMPOSE_PROJECT_NAME: agentlens
  DOCKER_HOST: tcp://192.168.1.133:2375

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

      - name: Verify Docker access
        run: |
          docker version
          docker compose version

      - name: Write environment file
        run: |
          cat > .env <<'ENVEOF'
          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 }}
          ENVEOF
          sed -i 's/^[[:space:]]*//' .env

      - 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 inspect --format='{{.State.Running}}' agentlens-web-1 2>/dev/null || true)
            if [ "$STATUS" = "true" ]; then
              echo "Container running (attempt $i)"
              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: Create Gitea Release
        if: startsWith(gitea.ref, 'refs/tags/')
        env:
          RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
        run: |
          TAG="${{ gitea.ref_name }}"
          curl -s -X POST \
            "https://gitea.vectry.tech/api/v1/repos/Vectry/agentlens/releases" \
            -H "Authorization: token ${RELEASE_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\", \"body\": \"Automated release for ${TAG}\", \"draft\": false, \"prerelease\": false}" \
            || echo "Release may already exist — skipping"

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