"""讯飞语音听写(IAT)诊断:验证 XFYUN_* 凭据 + wss 协议链路是否通。

用法(.env 在仓库根):
  .venv/Scripts/python.exe scripts/diag_asr.py            # 2s 静音冒烟(验鉴权/协议,预期空文本)
  .venv/Scripts/python.exe scripts/diag_asr.py <pcm文件>  # 真实音频(16k/16bit/mono 裸 PCM)

ASCII 输出(Windows 控制台 GBK,不打 emoji);secret 不打印。
常见错误码:10105/10313=appid 错;11200=服务未开通或量用完;11201=当日超限。
"""
import asyncio
import os
import sys

_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _ROOT not in sys.path:
    sys.path.insert(0, _ROOT)


def _load_env(path: str) -> None:
    try:
        from dotenv import load_dotenv
        load_dotenv(path)
        return
    except Exception:
        pass
    try:
        with open(path, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))
    except FileNotFoundError:
        pass


_load_env(os.path.join(_ROOT, ".env"))

from core.asr_xfyun import SAMPLE_RATE, XfyunASRError, transcribe  # noqa: E402


def main() -> int:
    appid = os.getenv("XFYUN_APPID", "")
    print(f"[env] XFYUN_APPID={appid or '(missing)'} "
          f"API_KEY={'set' if os.getenv('XFYUN_API_KEY') else '(missing)'} "
          f"API_SECRET={'set' if os.getenv('XFYUN_API_SECRET') else '(missing)'}")

    if len(sys.argv) > 1:
        pcm = open(sys.argv[1], "rb").read()
        print(f"[audio] file={sys.argv[1]} bytes={len(pcm)} "
              f"({len(pcm) / (SAMPLE_RATE * 2):.1f}s @16k/16bit/mono)")
    else:
        pcm = b"\x00" * (SAMPLE_RATE * 2 * 2)  # 2s 静音:只验鉴权+协议,预期识别为空
        print("[audio] builtin 2s silence (auth/protocol smoke, empty text expected)")

    try:
        text = asyncio.run(transcribe(pcm))
    except XfyunASRError as e:
        print(f"[FAIL] code={e.code} {e}")
        return 1
    print(f"[OK] text={text!r}")
    return 0


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