"""floor_plan 의존은 **계획 안에서 닫혀야** 한다 (2026-09-19 실주행).

## 무엇이 결함이었나

모델이 `fp_ground_floor_entrance` 의 의존으로 `fp_basement_stairs` 를 적었는데
그런 floor_plan 을 만들지 않았다. 그 검사가 **재시도 밖**(`_build_gen_order`,
모든 그룹이 끝난 뒤)에 있어서, **다시 물어볼 기회 없이** 단계가 통째로 죽었다.

    Step background_master_plan failed: _build_gen_order: missing dependency
    'fp_basement_stairs' (referenced from 'fp_ground_floor_entrance')

재시도는 이미 3회 있었다 — 검사가 그 **안에** 없었을 뿐이다.
"""
from __future__ import annotations

import pytest

from app.modules.pipeline.background_master_plan import (
    MasterPlanError, validate_plan_fp_dependencies)


def test_closed_plan_passes():
    validate_plan_fp_dependencies({"floor_plans": [
        {"fp_id": "fp_a", "depends_on_fp": []},
        {"fp_id": "fp_b", "depends_on_fp": ["fp_a"]},
    ]})


def test_dangling_dependency_is_caught():
    with pytest.raises(MasterPlanError) as e:
        validate_plan_fp_dependencies({"floor_plans": [
            {"fp_id": "fp_ground_floor_entrance",
             "depends_on_fp": ["fp_basement_stairs"]},
        ]})
    assert "fp_basement_stairs" in str(e.value)
    assert "fp_ground_floor_entrance" in str(e.value)


def test_empty_plan_is_fine():
    validate_plan_fp_dependencies({})
    validate_plan_fp_dependencies({"floor_plans": []})


def test_the_check_runs_inside_the_retry_loop():
    """★밖에 두면 재시도가 못 돈다 — 그것이 이번 결함이었다."""
    import inspect

    from app.modules.pipeline import background_master_plan as m

    src = inspect.getsource(m.run_background_master_plan)
    assert "validate_plan_fp_dependencies(result)" in src
    assert "for attempt in range(max_retries)" in src
    # 검사가 retry 루프 안쪽인지 — 들여쓰기로 본다
    for line in src.splitlines():
        if "validate_plan_fp_dependencies(result)" in line:
            assert len(line) - len(line.lstrip()) >= 12, "루프 밖에 있다"
            break
    else:
        raise AssertionError("호출 줄을 못 찾았다")
