name: Calibration Backlog (Registry Drift Watch)

on:
  schedule:
    - cron: "15 2 * * 1-5"   # UTC 02:15 = KST 11:15, weekday backlog update
  workflow_dispatch:

jobs:
  build-calibration-backlog:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout Code
      run: |
        if [ -d .git ]; then
          git remote set-url origin http://x-access-token:${{ secrets.GITHUB_TOKEN }}@192.168.123.100:8418/KimJaeHyun/myfinance.git
        else
          git init
          git remote add origin http://x-access-token:${{ secrets.GITHUB_TOKEN }}@192.168.123.100:8418/KimJaeHyun/myfinance.git
        fi
        git fetch origin main --depth=1
        git reset --hard FETCH_HEAD

    - name: Configure Runtime Paths
      run: |
        export PATH=/usr/local/bin:$PATH
        echo "/usr/local/bin" >> $GITHUB_PATH
        /usr/bin/python3 --version

    - name: Setup Python Environment
      run: |
        VENV_BASE=/volume1/gitea/python_venv
        REQ_HASH=$(md5sum tools/build_calibration_priority_v1.py 2>/dev/null | cut -d' ' -f1 || echo "calib-default")
        VENV="$VENV_BASE/$REQ_HASH"

        if [ ! -f "$VENV/bin/python" ]; then
          mkdir -p "$VENV_BASE"
          /usr/bin/python3 -m venv "$VENV"
          if [ ! -f "$VENV/bin/pip" ]; then
            curl -sS https://bootstrap.pypa.io/pip/3.8/get-pip.py -o get-pip.py
            "$VENV/bin/python" get-pip.py --quiet
            rm get-pip.py
          fi
          "$VENV/bin/pip" install --upgrade pip --quiet
          "$VENV/bin/pip" install pyyaml --quiet
        fi
        echo "$VENV/bin" >> $GITHUB_PATH

    - name: Validate Calibration Registry
      run: python3 tools/validate_calibration_registry_v1.py

    - name: Build Calibration Priority Backlog
      run: python3 tools/build_calibration_priority_v1.py

    - name: Build Calibration Change Ledger
      run: python3 tools/build_calibration_change_ledger_v4.py

    - name: Build Calibration Review Report
      run: python3 tools/build_calibration_review_report_v1.py

    - name: Build Calibration Approval List
      run: python3 tools/build_calibration_approval_list_v1.py

    - name: Build Calibration Decision Draft
      run: python3 tools/build_calibration_decision_draft_v1.py

    - name: Validate Calibration Change Ledger
      run: python3 tools/validate_calibration_change_ledger_v1.py

    - name: Summarize Backlog
      if: always()
      run: |
        STATUS="${{ job.status }}"
        echo "=== Calibration Backlog Result ==="
        echo "status: $STATUS"
        echo "priority: Temp/calibration_priority_v1.json"
        echo "ledger: Temp/calibration_change_ledger_v4.json"
        echo "review: Temp/calibration_review_report_v1.md"
        echo "approval: Temp/calibration_approval_list_v1.md"
        echo "decision: Temp/calibration_decision_draft_v1.md"
