name: Weekly Integration Tests

on:
  schedule:
    - cron: '0 8 * * 1'  # Monday 08:00 UTC
  workflow_dispatch:

permissions:
  issues: write

jobs:
  integration:
    runs-on: ubuntu-latest
    timeout-minutes: 30

    env:
      AGROBR_INMET_TOKEN: ${{ secrets.AGROBR_INMET_TOKEN }}
      AGROBR_USDA_API_KEY: ${{ secrets.AGROBR_USDA_API_KEY }}

    steps:
      - uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'
          cache: 'pip'

      - name: Install dependencies
        run: |
          pip install -e ".[dev,pdf,bigquery]"

      - name: Run integration tests
        id: integration
        run: |
          pytest -m integration --tb=short -v --timeout=120 2>&1 | tee integration_results.txt
          echo "exit_code=${PIPESTATUS[0]}" >> $GITHUB_OUTPUT
        continue-on-error: true

      - name: Upload results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: integration-results-${{ github.run_number }}
          path: integration_results.txt
          retention-days: 30

      - name: Create issue on failure
        if: steps.integration.outputs.exit_code != '0'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            let results = '';
            try {
              results = fs.readFileSync('integration_results.txt', 'utf8');
              results = results.slice(-2000);
            } catch (e) {
              results = 'Could not read results file';
            }
            await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: `Integration tests failed (run #${context.runNumber})`,
              body: `## Weekly integration tests failed\n\n**Run:** [#${context.runNumber}](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})\n**Date:** ${new Date().toISOString().slice(0, 10)}\n\n<details>\n<summary>Last 2000 chars of output</summary>\n\n\`\`\`\n${results}\n\`\`\`\n</details>`,
              labels: ['source-changed']
            });

      - name: Alert on failure
        if: steps.integration.outputs.exit_code != '0'
        env:
          AGROBR_ALERT_ENABLED: "true"
          AGROBR_ALERT_DISCORD_WEBHOOK: ${{ secrets.AGROBR_DISCORD_WEBHOOK }}
          AGROBR_ALERT_SLACK_WEBHOOK: ${{ secrets.AGROBR_SLACK_WEBHOOK }}
        run: |
          python -c "
          import asyncio
          from agrobr.alerts.notifier import AlertLevel, send_alert

          asyncio.run(send_alert(
              level=AlertLevel.WARNING,
              title='Weekly integration tests failed',
              details={'run': '${{ github.run_number }}', 'url': '${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}'},
          ))
          "
