"""task-3070 B-3: 서버와 동일한 프롬프트를 조립해 claude -p 를 실호출하고 마커 출력을 측정한다.

단위테스트로는 이 결함이 안 잡힌다(t3068 실증) — 실제 모델 응답을 봐야 한다.
사용: python3 realcall.py <server_dir> <label> <model> [<model>...]
"""
import importlib.util, json, os, re, subprocess, sys, time

SERVER_DIR = os.path.abspath(sys.argv[1])
LABEL = sys.argv[2]
MODELS = sys.argv[3:]

sys.path.insert(0, SERVER_DIR)
spec = importlib.util.spec_from_file_location("bm_main", os.path.join(SERVER_DIR, "main.py"))
main = importlib.util.module_from_spec(spec)
sys.modules["bm_main"] = main
spec.loader.exec_module(main)

FIX = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "benchmark_fixture.json")))
ROW = FIX[0]  # 대장암 자가진단 / image_count=6 — 회장 장애 재현 케이스

bm = main.BenchmarkGrounding(
    keyword=ROW["keyword"], url=ROW["url"], channel=ROW["channel"], rank=ROW["rank"],
    title=ROW["title"], bodyText=ROW["body_text"],
    sourceCharCount=ROW["char_count"], sourceImageCount=ROW["image_count"],
    sourceBodyKeywordCount=ROW["body_keyword_count"],
    charCount=ROW["char_count"], imageCount=ROW["image_count"],
    bodyKeywordCount=ROW["body_keyword_count"],
)
benchmark_prompt = main.build_benchmark_prompt(bm)

kwargs = dict(
    topic=ROW["keyword"], channel="블로그",
    settings={"insuranceCategory": "건강보험", "contentTone": "자동"},
    skills=["base"], channel_prompt="", compliance_prompt="",
    profile_prompt="", personal_reg_prompt="", extra_prompt="",
    benchmark_prompt=benchmark_prompt,
)
import inspect
if "benchmark" in inspect.signature(main.build_content_prompt).parameters:
    kwargs["benchmark"] = bm
full_prompt = main.build_content_prompt(**kwargs)

MARKER_RE = re.compile(r"^[ \t]*#{1,6}[ \t]*이미지\s*프롬프트[ \t]*$", re.M)
ITEM_RE = re.compile(r"^\s*(\d+)\.\s+\S", re.M)

print(f"### {LABEL} | prompt {len(full_prompt)}자 | image_count={ROW['image_count']}")
print(f"### 최종 지시(§7) 꼬리 200자: {full_prompt[-200:]!r}\n")

results = []
for model in MODELS:
    env = {**os.environ}
    env.pop("CLAUDECODE", None)
    t0 = time.time()
    p = subprocess.run(["claude", "-p", "--model", model, "--output-format", "text"],
                       input=full_prompt.encode(), capture_output=True, timeout=900, env=env)
    dt = time.time() - t0
    raw = p.stdout.decode(errors="replace").strip()
    post = main.limit_hashtags(raw)
    m = MARKER_RE.search(post)
    n_items = 0
    if m:
        n_items = len(ITEM_RE.findall(post[m.end():]))
    r = dict(label=LABEL, model=model, rc=p.returncode, secs=round(dt, 1), chars=len(post),
             marker_raw=bool(MARKER_RE.search(raw)), marker_post=bool(m), items=n_items,
             target=ROW["image_count"])
    results.append(r)
    print(f"[{LABEL}/{model}] rc={p.returncode} {dt:.1f}s {len(post)}자 "
          f"marker(raw)={r['marker_raw']} marker(post)={r['marker_post']} 항목={n_items}/{r['target']}")
    open(f"/home/jay/workspace/teams/dev4/task-3070/out_{LABEL}_{model}.md", "w").write(post)

json.dump(results, open(f"/home/jay/workspace/teams/dev4/task-3070/res_{LABEL}.json", "w"),
          ensure_ascii=False, indent=2)
