name: DouYin Spark Flow Schedule Run

on:
  workflow_dispatch:
    inputs:
      run_task:
        description: "Run the real Douyin send task after checks"
        required: false
        default: false
        type: boolean
  schedule:
    - cron: "0 2 * * *" # 10:00 Asia/Shanghai

permissions:
  contents: read

concurrency:
  group: douyin-sparkflow-scheduled-send
  cancel-in-progress: false

defaults:
  run:
    working-directory: DouYinSparkFlow

jobs:
  run-main:
    timeout-minutes: 30
    runs-on: ubuntu-latest
    environment:
      name: user-data
      deployment: false
    steps:
      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
      - name: Set up Python
        uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
        with:
          python-version: "3.11"
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
      - name: Run unit tests
        env:
          USER_DATA: "[]"
        run: python -m unittest discover -s tests -v
      - name: Test Douyin accessibility
        run: |
          status="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 30 https://creator.douyin.com/)"
          test "$status" != "000"
      - name: Validate USER_DATA secret
        if: ${{ github.event_name == 'schedule' || inputs.run_task }}
        env:
          USER_DATA: ${{ secrets.USER_DATA }}
        run: |
          python - <<'PY'
          import json
          import os

          raw = os.environ.get("USER_DATA", "")
          if not raw.strip():
              raise SystemExit(
                  "USER_DATA is missing in the 'user-data' Environment; "
                  "add/update that Environment secret before running the send task."
              )
          try:
              data = json.loads(raw)
          except json.JSONDecodeError as exc:
              raise SystemExit(f"USER_DATA is not valid JSON: {exc.msg}") from exc
          if not isinstance(data, list) or not data:
              raise SystemExit("USER_DATA must be a non-empty JSON array of account objects.")
          if any(not isinstance(account, dict) for account in data):
              raise SystemExit("USER_DATA must contain only JSON objects.")
          print(f"USER_DATA validated: {len(data)} account(s); sensitive contents hidden.")
          PY
      - name: Ensure Chromium is installed
        if: ${{ github.event_name == 'schedule' || inputs.run_task }}
        run: playwright install chromium --with-deps --only-shell
      - name: Run DouYin Spark Flow
        if: ${{ github.event_name == 'schedule' || inputs.run_task }}
        env:
          USER_DATA: ${{ secrets.USER_DATA }}
          SPARKFLOW_BROWSER_PROFILE_ROOT: ${{ runner.temp }}/douyin-sparkflow-browser-profiles
          SPARKFLOW_MANUAL_RUN: "1"
          PYTHONUNBUFFERED: "1"
        run: python main.py --doTask
      - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
        if: ${{ !cancelled() }}
        with:
          name: run-logs
          path: DouYinSparkFlow/logs/
          if-no-files-found: ignore
          retention-days: 3

  workflow-keepalive:
    if: github.event_name == 'schedule'
    runs-on: ubuntu-latest
    permissions:
      actions: write
    steps:
      - uses: liskin/gh-workflow-keepalive@f72ff1a1336129f29bf0166c0fd0ca6cf1bcb38c # v1