"""Capture a real /query response shape for the Apipost example.

直接复用 tests/test_it_diagnosis.py 里的 FakeVectorStore / FakeWebSearchProvider,
跑一次完整的 AgenticRAGService.invoke,把返回体序列化到 stdout。
这样产出的 JSON 与 FastAPI /query 在生产路径下的字段顺序、字段名完全一致,
只是工具结果被 fixture 取代,便于在 README/作业文档里贴出真实响应。
"""

from __future__ import annotations

import json
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from app.config import Settings  # noqa: E402
from app.schemas import Evidence, KnowledgeType, QueryRequest  # noqa: E402
from app.service import AgenticRAGService  # noqa: E402
from app.sql_store import initialize_database  # noqa: E402


class FakeVectorStore:
    def search(self, query, top_k=5, service_name="", client_os="", doc_type=""):
        return [
            Evidence(
                source_type="milvus",
                source="vpn_troubleshooting.md",
                content=(
                    "Windows 客户端排查顺序：检查日志 → 验证证书 → "
                    "重建 Profile → 联系厂商。"
                ),
                score=0.91,
                knowledge_type=KnowledgeType.INTERNAL_DOC,
                metadata={
                    "doc_type": doc_type,
                    "service_name": service_name,
                    "category": client_os,
                },
            )
        ]


class FakeWebSearchProvider:
    def search(self, query, max_results=5):
        return [
            Evidence(
                source_type="web",
                source="https://help.aliyun.com/zh/vpn/product-overview/notice/",
                content=(
                    "【示例夹具】阿里云 SSL-VPN 当前运行正常，无服务异常公告。"
                ),
                score=0.95,
                knowledge_type=KnowledgeType.REALTIME,
                metadata={
                    "title": "阿里云 VPN 网关动态与公告",
                    "url": "https://help.aliyun.com/zh/vpn/product-overview/notice/",
                    "published_date": None,
                },
            )
        ]


def main() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        database = Path(tmp) / "incidents.db"
        initialize_database(database, reset=True)
        settings = Settings(
            _env_file=None,
            llm_provider="demo",
            sqlite_path=database,
            max_retrieval_rounds=2,
            min_evidence_score=0.35,
        )
        service = AgenticRAGService(
            settings,
            FakeVectorStore(),
            FakeWebSearchProvider(),
        )
        response = service.invoke(
            QueryRequest(
                query=(
                    "今天上午阿里云 SSL-VPN 频繁断开,Windows 客户端提示认证超时。"
                    "请统计过去 30 天同类故障发生次数,结合内部 VPN 排障手册和"
                    "厂商官网最新服务公告,判断更可能是本地配置问题还是"
                    "公共服务异常,并给出排查步骤。"
                ),
                debug=True,
            )
        )
        print(json.dumps(response.model_dump(), ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
