"""도면 하나를 **여러 그룹이 같이 쓸 수 있다** (2026-09-19 실주행).

## 무엇이 결함이었나

`fp_container_interior` 를 두 그룹이 같이 썼다.

    bg_candlelit_container_home  → L166B01~B04
    bg_container_home_wash_yard  → L170B01

그런데 도면 프롬프트 단계는 **그룹 안에서만** 배경을 모으고 결과를 **도면
이름으로** 저장했다. 뒤 그룹이 앞 그룹을 **덮어써서** L166B0x 의 카메라 추천이
통째로 사라졌고, 세 단계 뒤에서 죽었다.

    floor_plan_overlay_payload: bg_id='L166B03' missing camera_recommendations
    entry under fp_id='fp_container_interior'

생산자에는 「추천 bg 가 대상과 정확히 일치」라는 검사가 **이미 있었다** —
그때의 「대상」이 한 그룹 몫이라 통과했을 뿐이다. 모집단이 틀렸다.
"""
from __future__ import annotations

import inspect


def test_jobs_merge_backgrounds_per_floor_plan():
    """도면 하나당 **모든 그룹의 배경을 합쳐** 한 번만 묻는지."""
    from app.core.steps import floor_plan_prompt_step as m

    src = inspect.getsource(m.FloorPlanPromptStep)
    assert "_by_fp" in src, "도면별로 합치는 자리가 없다"
    assert "setdefault(fp[\"fp_id\"]" in src or 'setdefault(fp["fp_id"]' in src
    assert "group_ids" in src, "여러 그룹이 쓴 것을 기록하지 않는다"


def test_merge_logic_dedupes_and_keeps_all():
    """합치는 규칙 자체 — 같은 bg 는 한 번, 다른 그룹 것은 다 남는다."""
    plans = {
        "g1": {"status": "ok", "plan": {
            "floor_plans": [{"fp_id": "fp_x"}],
            "backgrounds": [
                {"bg_id": "L166B03", "depends_on_fp": ["fp_x"],
                 "loc_id": "L166", "applies_to_shots": ["S1"]},
                {"bg_id": "L166B04", "depends_on_fp": ["fp_x"],
                 "loc_id": "L166", "applies_to_shots": ["S2"]},
            ]}},
        "g2": {"status": "ok", "plan": {
            "floor_plans": [{"fp_id": "fp_x"}],
            "backgrounds": [
                {"bg_id": "L170B01", "depends_on_fp": ["fp_x"],
                 "loc_id": "L170", "applies_to_shots": ["S3"]},
                # 같은 bg 가 두 그룹에 나와도 한 번만
                {"bg_id": "L166B03", "depends_on_fp": ["fp_x"],
                 "loc_id": "L166", "applies_to_shots": ["S1"]},
            ]}},
    }
    by_fp: dict = {}
    for gid, entry in plans.items():
        plan = entry["plan"]
        for fp in plan["floor_plans"]:
            applied = [b for b in plan["backgrounds"]
                       if fp["fp_id"] in (b.get("depends_on_fp") or [])]
            slot = by_fp.setdefault(fp["fp_id"], {"applied_bgs": [], "groups": []})
            slot["groups"].append(gid)
            seen = {b["bg_id"] for b in slot["applied_bgs"]}
            for b in applied:
                if b["bg_id"] not in seen:
                    slot["applied_bgs"].append(b)
                    seen.add(b["bg_id"])
    got = {b["bg_id"] for b in by_fp["fp_x"]["applied_bgs"]}
    assert got == {"L166B03", "L166B04", "L170B01"}, got
    assert by_fp["fp_x"]["groups"] == ["g1", "g2"]
