# =============================================================================
# AWOOOI AI Technology Watch (Gitea Actions)
# =============================================================================
# 每 6 小時只讀監控主流 AI 技術 primary sources。此 workflow 只產生
# Gitea step summary；不安裝 SDK、不呼叫 LLM API、不 commit report、不發
# Telegram、不切換 provider route、不修改 production。

name: AI 技術雷達監控

on:
  workflow_dispatch:
  schedule:
    - cron: '0 */6 * * *'

jobs:
  ai-technology-watch:
    runs-on: awoooi-non110-ubuntu
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4

      - name: 執行只讀 AI 技術雷達監控
        id: watch
        run: |
          set -euo pipefail
          REPORT="/tmp/ai_technology_watch_report.json"
          PREVIOUS_REPORT="$(find docs/evaluations -maxdepth 1 -type f -name 'ai_technology_watch_report_*.json' | sort | tail -n 1 || true)"
          PREVIOUS_ARGS=()
          if [ -n "$PREVIOUS_REPORT" ]; then
            PREVIOUS_ARGS=(--previous-report "$PREVIOUS_REPORT")
            echo "使用已提交的上一份 AI 技術雷達 baseline: $PREVIOUS_REPORT"
          else
            echo "找不到已提交的 AI 技術雷達 baseline，執行第一次 live baseline。"
          fi

          python3 scripts/agents/ai-technology-watch.py \
            --registry docs/ai/ai-technology-watch-sources.v1.json \
            --output "$REPORT" \
            --mode live \
            --timeout-seconds 12 \
            "${PREVIOUS_ARGS[@]}"

          python3 -m json.tool "$REPORT" >/dev/null
          python3 - "$REPORT" <<'PY'
          import json
          import os
          import sys

          report_path = sys.argv[1]
          with open(report_path, encoding="utf-8") as handle:
              data = json.load(handle)

          if data.get("schema_version") != "ai_technology_watch_report_v1":
              raise SystemExit("AI 技術雷達 schema_version 不正確")
          if data.get("mode") != "live":
              raise SystemExit("AI 技術雷達 workflow 必須以 live mode 執行")

          policy = data.get("policy") or {}
          forbidden = [
              "sdk_installation_approved",
              "paid_api_calls_approved",
              "production_routing_approved",
              "telegram_send_approved",
              "model_provider_switch_approved",
              "host_write_approved",
          ]
          unsafe = [key for key in forbidden if policy.get(key) is not False]
          if unsafe:
              raise SystemExit(f"AI 技術雷達 policy 必須維持 false: {unsafe}")
          if policy.get("read_only") is not True:
              raise SystemExit("AI 技術雷達必須維持 read_only")

          summary = data.get("summary")
          if not isinstance(summary, dict):
              raise SystemExit("缺少 AI 技術雷達 summary")
          required = [
              "technology_count",
              "technology_area_count",
              "source_count",
              "changed_technologies",
              "watch_only_technologies",
              "review_queue_count",
              "source_failure_count",
              "high_priority_count",
          ]
          missing = [key for key in required if key not in summary]
          if missing:
              raise SystemExit(f"缺少 AI 技術雷達 summary keys: {missing}")

          output_path = os.environ.get("GITHUB_OUTPUT")
          if output_path:
              with open(output_path, "a", encoding="utf-8") as handle:
                  for key in required:
                      handle.write(f"{key}={summary.get(key, 0)}\n")

          step_summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
          if step_summary_path:
              with open(step_summary_path, "a", encoding="utf-8") as handle:
                  handle.write("## AI 技術雷達監控\n\n")
                  handle.write(f"- 技術項目：{summary['technology_count']}\n")
                  handle.write(f"- 技術領域：{summary['technology_area_count']}\n")
                  handle.write(f"- 來源數：{summary['source_count']}\n")
                  handle.write(f"- 變更技術：{summary['changed_technologies']}\n")
                  handle.write(f"- 審核佇列：{summary['review_queue_count']}\n")
                  handle.write(f"- 來源失敗：{summary['source_failure_count']}\n")
                  handle.write(f"- 高優先級技術：{summary['high_priority_count']}\n")
                  handle.write("\nPolicy: 只讀監控；此 workflow 不批准 SDK/API/provider/Telegram/host/production 變更。\n")

          print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
          PY
