"""讯飞录音文件转写(LFASR)诊断:验证 XFYUN_APPID/XFYUN_LFASR_SECRET_KEY + 订单链路是否通。

用法(.env 在仓库根):
  .venv/Scripts/python.exe scripts/diag_lfasr.py <音频文件> [cn|en]

上传 → 轮询到订单完成 → 打印时长/耗时/转写文本。
ASCII 标签输出(Windows 控制台 GBK,不打 emoji);secret 不打印。
"""
import os
import sys
import time

_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_lfasr import LfasrError, transcribe_file  # noqa: E402


def main() -> int:
    print(f"[env] XFYUN_APPID={os.getenv('XFYUN_APPID') or '(missing)'} "
          f"LFASR_SECRET_KEY={'set' if os.getenv('XFYUN_LFASR_SECRET_KEY') else '(missing)'}")
    if len(sys.argv) < 2:
        print("[usage] diag_lfasr.py <audio file> [cn|en]")
        return 2
    path = sys.argv[1]
    lang = sys.argv[2] if len(sys.argv) > 2 else "cn"
    data = open(path, "rb").read()
    print(f"[file] {path} ({len(data)} bytes) language={lang}")

    t0 = time.monotonic()
    try:
        result = transcribe_file(data, os.path.basename(path), language=lang)
    except LfasrError as e:
        print(f"[FAIL] {type(e).__name__}: {e}")
        return 1
    print(f"[ok] orderId={result['order_id']} duration={result['duration_s']:.1f}s "
          f"elapsed={result['elapsed_s']:.1f}s (wall {time.monotonic() - t0:.1f}s)")
    print("[text]")
    print(result["text"])
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
