"""합성 원고를 **저장 체크포인트 모양**으로 깔아 둔다. ★유료 0 · 외부 0.

`call_payload_table.py` 는 저장 체크포인트를 읽는다. 합성 원고로 같은 표를
내려면 그 모양으로 한 벌 깔아야 한다.

★프로덕션 `projects/` 를 **안 건드린다** — 받은 디렉토리에만 쓴다.
DB·프로젝트 파일 삭제 금지 규칙이 있는 자리라 **지우지도 않는다**.

    python tools/grounding_audit/materialize_synthetic.py <out_dir>
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tests"))

PID = "synthetic-episode"
EID = "ep-1"


def main() -> int:
    if len(sys.argv) < 2:
        print(__doc__)
        return 2
    out = Path(sys.argv[1])
    if "projects" in out.parts and "TheRoad-I1" in out.parts:
        # ★프로덕션 자리에 쓰지 않는다. 실수로 덮으면 되돌릴 방법이 없다.
        print("★프로덕션 projects/ 에는 안 쓴다 — 다른 자리를 달라")
        return 2
    from grounding.fixtures import synthetic_episode as ep

    ep.assert_planted()          # ★깔기 전에 원고가 약속대로인지 본다
    root = out / PID / "checkpoints" / "episodes" / EID

    cps = {
        "text_cleanup": {"cleaned_text": ep.manuscript()},
        "scene_save": {"segments": ep.segments()},
        "shot_validator": {"scenes": ep.shot_scenes()},
        # ★세계관은 **합성**이다 — 특정 시대·지역을 안 가리킨다.
        "visual_world_rules": {
            "era": "가상의 근대 이후 어느 시기",
            "region": "가상의 소도시",
            "rules": [{"rule_type": "architecture",
                       "visual_guideline": "건물은 낮고 간판은 손글씨다"}],
        },
    }
    # 엔티티 세 벌 — 원고에 심은 다섯 갈래 중 base 셋.
    base = {"characters": [{"short_id": "C01", "name": "운전사",
                            "shot_count": 3, "description": "제복 상의를 입은 사람"},
                           {"short_id": "C02", "name": "승객",
                            "shot_count": 2, "description": "표를 든 사람"}],
            "locations": [{"short_id": "L01", "name": "정류장",
                           "shot_count": 3, "description": "낮은 승강장"},
                          {"short_id": "L02", "name": "대합실",
                           "shot_count": 1, "description": "정류장 안쪽 방"}],
            "props": [{"short_id": "P01", "name": "가방", "shot_count": 2,
                       "description": "손잡이 한쪽이 남은 낡은 가방"},
                      {"short_id": "P02", "name": "표", "shot_count": 2,
                       "description": "끝이 접힌 종이"},
                      {"short_id": "P03", "name": "옛 요금표", "shot_count": 1,
                       "description": "손으로 덧칠한 숫자 칸"}]}
    for t, k in (("character", "characters"), ("location", "locations"),
                 ("prop", "props")):
        cps[f"entity_all_{t}"] = {k: [{"name": e["name"],
                                       "short_id": e["short_id"],
                                       "shot_count": e["shot_count"]}
                                      for e in base[k]]}
        cps[f"entity_extract_{t}"] = {k: base[k]}
    cps["entity_merge"] = dict(base)

    for step, data in cps.items():
        d = root / step
        d.mkdir(parents=True, exist_ok=True)
        (d / "manifest.json").write_text(
            json.dumps({"status": "completed", "data": data},
                       ensure_ascii=False, indent=1), encoding="utf-8")
    print(f"■ 깔았다 — {root}")
    print(f"  원문 {len(ep.manuscript()):,}자 · 씬 {len(ep.segments())} · "
          f"샷 {sum(len(s['shots']) for s in ep.shot_scenes())} · "
          f"엔티티 {sum(len(v) for v in base.values())}")
    print(f"  PROJECTS_DIR={out}  {PID} {EID}")
    return 0


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