"""单独调用应用5-话术参考，完整输出。"""
import json, os, sys, time, urllib.request, urllib.error
from pathlib import Path
from dotenv import load_dotenv

load_dotenv(Path(__file__).resolve().parents[2] / ".env")

BAILIAN_API_KEY = os.environ.get("BAILIAN_API_KEY", "")
if not BAILIAN_API_KEY:
    print("BAILIAN_API_KEY 未设置"); sys.exit(1)

app_id = os.environ.get("BAILIAN_APP_ID_5_TACTICS", "")
if not app_id:
    print("BAILIAN_APP_ID_5_TACTICS 未设置"); sys.exit(1)

prompt = json.dumps({
    "scenario": "客户3天未到店，需要召回话术",
    "customer": {"name": "张三", "preference": "周末晚间", "favorite_table": "9号台"},
    "user_query": ""
}, ensure_ascii=False)

url = f"https://dashscope.aliyuncs.com/api/v1/apps/{app_id}/completion"
body = json.dumps({"input": {"prompt": prompt}, "parameters": {"has_thoughts": False}}).encode("utf-8")
headers = {"Authorization": f"Bearer {BAILIAN_API_KEY}", "Content-Type": "application/json"}

print(f"[输入] {prompt}")
print(f"[调用] {url}")
t0 = time.time()
try:
    req = urllib.request.Request(url, data=body, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=120) as resp:
        data = json.loads(resp.read().decode("utf-8"))
    elapsed = round(time.time() - t0, 2)
    text = data.get("output", {}).get("text", "")
    usage = data.get("usage", {})
    print(f"\n[OK] {elapsed}s")
    print(f"[usage] {json.dumps(usage, ensure_ascii=False)}")
    print(f"\n[输出]\n{text}")
except Exception as e:
    elapsed = round(time.time() - t0, 2)
    print(f"\n[ERROR] {elapsed}s: {e}")
