# -*- coding: utf-8 -*-
"""不联网的目录和请求组装检查。"""

from __future__ import annotations

import json

import catalog
import client

FORBIDDEN = ("sk_live_", "sk_test_", "fn_sk_", "ife2c966", "shanhaiyunduan")


def main() -> None:
    rows = catalog.load()
    assert len(rows) >= 100, len(rows)
    ids = {row["id"] for row in rows}
    assert "weather" in ids and "icp" in ids and "express-pro" in ids
    assert "_proxy" not in ids and "yandi-proxy" not in ids
    blob = json.dumps(rows, ensure_ascii=False)
    for token in FORBIDDEN:
        assert token not in blob, token

    weather = catalog.search("天气", limit=5)
    assert weather and weather[0]["id"] == "weather", weather
    icp = catalog.describe("icp")
    assert icp["found"] and "domain" in icp["params"]
    tender = catalog.describe("tender-search")
    assert "startDate" in tender["params"] and "endDate" in tender["params"]
    assert catalog.describe("no-such-api")["found"] is False

    try:
        client.prepare("idcard-2c", {"name": "张三", "idcard": "110101199001011234"}, None, "AUTO", False)
        raise SystemExit("核验接口没有被拦住")
    except client.CallError as exc:
        assert "confirm_sensitive" in str(exc)

    plan = client.prepare("weather", {"city": "北京"}, None, "AUTO", False)
    assert plan["method"] == "POST"
    assert plan["url"].endswith("/api/weather")
    assert "北京" in json.dumps(plan["payload"], ensure_ascii=False)

    info = client.prepare("user-info", None, None, "AUTO", False)
    assert info["method"] == "GET"

    shaped = client._shape(200, {"code": 0, "msg": "成功", "data": {"city": "北京"}, "request_id": "r1"})
    assert shaped["ok"] and shaped["data"]["city"] == "北京"
    chat = client._shape(200, {"choices": [{"message": {"content": "hi"}}]})
    assert chat["ok"] and "choices" in chat["data"]
    legacy = client._shape(200, {"code": "200", "desc": "success", "data": {"total_items": 1}})
    assert legacy["ok"] and legacy["data"]["total_items"] == 1
    denied = client._shape(200, {"code": "0001", "desc": "缺少参数"})
    assert denied["ok"] is False and "缺少" in denied["msg"]

    print(f"selfcheck ok, {len(rows)} apis")


if __name__ == "__main__":
    main()
