name: Paper Emails

on:
  schedule:
    # Daily suggestion at 8am ET (1pm UTC)
    - cron: '0 13 * * *'
    # Weekly digest on Sunday at 9am ET (2pm UTC)
    - cron: '0 14 * * 0'
    # Monthly themes on 1st at 10am ET (3pm UTC)
    - cron: '0 15 1 * *'
  workflow_dispatch:
    inputs:
      command:
        description: 'Command to run'
        required: true
        default: '--suggest-email'
        type: choice
        options:
          - '--suggest-email'
          - '--send-digest'
          - '--themes'

jobs:
  send-email:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - uses: astral-sh/setup-uv@v5
        with:
          version: 'latest'

      - name: Install dependencies
        run: |
          uv venv
          uv pip install python-dotenv requests "anthropic>=0.40.0" "resend>=2.0.0"
          uv pip install --no-deps -e .

      - name: Fetch state from gist
        run: |
          curl -sL "https://api.github.com/gists/${{ secrets.STATE_GIST_ID }}" \
            | jq -r '.files["state.json"].content' > state.json

      - name: Determine command
        id: cmd
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            echo "args=${{ inputs.command }}" >> "$GITHUB_OUTPUT"
          elif [ "${{ github.event.schedule }}" = "0 14 * * 0" ]; then
            echo "args=--send-digest" >> "$GITHUB_OUTPUT"
          elif [ "${{ github.event.schedule }}" = "0 15 1 * *" ]; then
            echo "args=--themes" >> "$GITHUB_OUTPUT"
          else
            echo "args=--suggest-email" >> "$GITHUB_OUTPUT"
          fi

      - name: Run command
        run: .venv/bin/distillate ${{ steps.cmd.outputs.args }}
        env:
          ZOTERO_API_KEY: ${{ secrets.ZOTERO_API_KEY }}
          ZOTERO_USER_ID: ${{ secrets.ZOTERO_USER_ID }}
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          RESEND_API_KEY: ${{ secrets.RESEND_API_KEY }}
          DIGEST_TO: ${{ secrets.DIGEST_TO }}
          DIGEST_FROM: ${{ secrets.DIGEST_FROM }}
          STATE_GIST_ID: ${{ secrets.STATE_GIST_ID }}
          GH_GIST_TOKEN: ${{ secrets.GH_GIST_TOKEN }}
