#!/usr/bin/env python3
"""
KM Vectorize CronJob 入口腳本 — ADR-073 Phase 4-3

每日由 K8s CronJob 呼叫，對新增 KM 條目執行向量化，
確保 RAG 查詢可存取最新知識（飛輪「學習固化」節點）。

2026-04-12 ogt (ADR-073 Phase 4-3, P2-1 重構)
"""

import asyncio
import os
import sys

import httpx


async def main() -> int:
    api_base = os.environ.get(
        "INTERNAL_API_URL",
        "http://awoooi-api-svc.awoooi-prod.svc.cluster.local:8000",
    )
    url = f"{api_base}/api/v1/knowledge/embed-all"

    async with httpx.AsyncClient(timeout=1800) as client:
        try:
            resp = await client.post(url)
            print(f"embed-all: {resp.status_code} {resp.text[:200]}")
            if resp.status_code >= 400:
                print(f"ERROR: embed-all returned {resp.status_code}", file=sys.stderr)
                return 1
            result = resp.json()
            if int(result.get("failed", 0)) > 0:
                print(f"ERROR: embed-all failed rows: {result}", file=sys.stderr)
                return 1
            return 0
        except httpx.RequestError as exc:
            print(f"ERROR: request failed — {exc}", file=sys.stderr)
            return 1


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))
