name: Deploy to Modal

permissions:
  contents: read
  issues: write
  pull-requests: write

on:
  push:
    branches:
      - main
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  deploy:
    name: Deploy Canvas Chat
    runs-on: ubuntu-latest
    env:
      MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }}
      MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }}
    outputs:
      test_url: ${{ steps.deploy-test.outputs.url }}
      main_url: ${{ steps.deploy-main.outputs.url }}

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Install uv
        uses: astral-sh/setup-uv@v7

      - name: Deploy to test environment (PR)
        if: github.event_name == 'pull_request'
        id: deploy-test
        run: |
          OUTPUT=$(uv run --with modal modal deploy modal_app.py -e test 2>&1)
          echo "$OUTPUT"
          URL=$(echo "$OUTPUT" | grep -oE 'https://modal\.com/apps/[^ ]+' | head -1)
          echo "url=$URL" >> $GITHUB_OUTPUT

      - name: Deploy to main environment (push to main)
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        id: deploy-main
        run: |
          OUTPUT=$(uv run --with modal modal deploy modal_app.py 2>&1)
          echo "$OUTPUT"
          URL=$(echo "$OUTPUT" | grep -oE 'https://modal\.com/apps/[^ ]+' | head -1)
          echo "url=$URL" >> $GITHUB_OUTPUT

      - name: Health check (test deploy)
        if: github.event_name == 'pull_request' && steps.deploy-test.outputs.url != ''
        run: |
          URL=${{ steps.deploy-test.outputs.url }}
          echo "Checking health for $URL"
          for i in 1 2 3 4 5; do
            status=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 --max-time 10 "$URL" || echo "000")
            echo "Attempt $i: HTTP $status"
            if [ "$status" = "200" ] || [ "$status" = "301" ] || [ "$status" = "302" ]; then
              echo "Deployment healthy"
              exit 0
            fi
            sleep 2
          done
          echo "Deployment health check failed for $URL"
          exit 1

      - name: Health check (main deploy)
        if: github.event_name == 'push' && steps.deploy-main.outputs.url != ''
        run: |
          URL=${{ steps.deploy-main.outputs.url }}
          echo "Checking health for $URL"
          for i in 1 2 3 4 5; do
            status=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 --max-time 10 "$URL" || echo "000")
            echo "Attempt $i: HTTP $status"
            if [ "$status" = "200" ] || [ "$status" = "301" ] || [ "$status" = "302" ]; then
              echo "Deployment healthy"
              exit 0
            fi
            sleep 2
          done
          echo "Deployment health check failed for $URL"
          exit 1

      - name: Write deployment summary
        run: |
          echo "## 🚀 Modal Deployment" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          if [ "${{ github.event_name }}" == "pull_request" ]; then
            echo "**Environment:** test" >> $GITHUB_STEP_SUMMARY
            echo "**URL:** ${{ steps.deploy-test.outputs.url }}" >> $GITHUB_STEP_SUMMARY
          else
            echo "**Environment:** main" >> $GITHUB_STEP_SUMMARY
            echo "**URL:** ${{ steps.deploy-main.outputs.url }}" >> $GITHUB_STEP_SUMMARY
          fi


  post-pr-comment:
    name: Post PR comment
    runs-on: ubuntu-latest
    needs: deploy
    if: github.event_name == 'pull_request'
    steps:
      - name: Post or update PR comment
        uses: actions/github-script@v7
        with:
          script: |
            const marker = '<!-- modal-deploy-comment -->';
            const url = '${{ needs.deploy.outputs.test_url }}';
            const body = `${marker}
            ## 🚀 Modal Deployment

            **Environment:** test
            **URL:** ${url}

            _This comment is automatically updated on each push._`;

            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });

            const existing = comments.find(c => c.body.includes(marker));

            if (existing) {
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: existing.id,
                body: body,
              });
            } else {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: body,
              });
            }
