"""1-D canary — 일반화한 BUILT SPACE 문안이 두 종류 공간에서 어떻게 읽히나.

두 장을 태운다 (Codex 권고):
  A 탈것 아닌 좁은 실내  — 어구 창고 (조종 설비가 **없다**)
  B 실제 조종 설비 실내  — 초계정 조타실 (helm·계기가 **있다**)

재는 것: 판정이 내놓는 **BUILT SPACE 판독문**.
  ① 없는 조종 장치를 지어내지 않는가 (A)
  ② 있는 설비를 여전히 세는가 (B) — 재료가 사라지지 않았는가

프로덕션 경로 그대로: 전역 팩(v16) judge_sys + `make_gemini_judge_fn`.
같은 그림을 두 후보로 넣는다 — 선정이 목적이 아니라 **판독문**이 목적이다.
"""
import json
import os
import sys
from pathlib import Path

BACKEND = Path("/Users/manta/Documents/Projects/TheRoad-I1/backend")
sys.path.insert(0, str(BACKEND))
os.chdir(BACKEND)  # config.py 의 env_file=".env" 는 상대 경로다

ROOT = Path("/Users/manta/Documents/Projects/TheRoad-I1")

CASES = [
    ("A 탈것 아님 (어구 창고)",
     "projects/e716bafb-24bb-42b7-aea0-fdb383844ee8/images/",
     "988b2be1",
     "Inside the dim fishing-gear warehouse near its dusty window "
     "overlooking the pier."),
    ("B 조종 설비 있음 (초계정 조타실)",
     "projects/e716bafb-24bb-42b7-aea0-fdb383844ee8/images/",
     "3f64eebd",
     "Inside the patrol boat's compact wheelhouse, enclosed by the helm, "
     "windows and controls."),
]


def _resolve(asset_id_prefix: str) -> Path:
    import subprocess
    out = subprocess.run(
        ["psql", "-h", "localhost", "-U", "theroad", "-d", "theroad",
         "-t", "-A", "-c",
         f"SELECT file_path FROM image_asset WHERE id::text LIKE "
         f"'{asset_id_prefix}%' LIMIT 1;"],
        capture_output=True, text=True,
        env={**os.environ, "PGPASSWORD": "theroad_dev_2026"})
    rel = out.stdout.strip()
    return ROOT / rel if rel else None


def main() -> int:
    from app.modules.pipeline.multiroll_gemini import (
        JUDGE_PACK_VERSION, make_gemini_judge_fn, resolve_judge_pack_version,
        resolve_judge_texts,
    )
    from app.modules.pipeline.multiroll_select import (
        build_judge_schema, roll_labels,
    )

    texts = resolve_judge_texts(2, judge_name="judge_still")  # 전역 팩
    print(f"전역 팩 : {JUDGE_PACK_VERSION} → "
          f"{resolve_judge_pack_version(JUDGE_PACK_VERSION)}")
    print(f"judge_sys: {len(texts['judge_sys']):,}자")
    print("─" * 70)

    labels = list(roll_labels(2))
    judge_fn = make_gemini_judge_fn(
        judge_sys=texts["judge_sys"],
        judge_schema=build_judge_schema(labels, with_physics=False),
        step_tag="builtspace_canary")

    for name, _, prefix, brief in CASES:
        img = _resolve(prefix)
        if img is None or not img.is_file():
            print(f"✗ {name}: 그림을 못 찾았다 ({prefix})")
            continue
        print(f"\n══ {name}")
        print(f"   {img.name}  ({img.stat().st_size:,} bytes)")
        out = judge_fn("builtspace_canary", brief, [],
                       [str(img), str(img)], labels)
        if not isinstance(out, dict):
            print(f"   ✗ 응답이 dict 가 아니다: {type(out)}")
            continue
        for r in (out.get("readings") or out.get("candidates") or []):
            if not isinstance(r, dict):
                continue
            bs = (r.get("built_space") or r.get("built_space_reading")
                  or r.get("structure"))
            if bs:
                print(f"   BUILT SPACE: {bs}")
                break
        else:
            print("   (readings 에서 built_space 칸을 못 찾았다 — 원문)")
            print("   " + json.dumps(out, ensure_ascii=False)[:900])
    return 0


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