import json
import pytest
from pathlib import Path
from unittest.mock import patch, MagicMock
from app.core.steps.background_classify_step import (
    BackgroundClassifyStep,
    SCHEMA_VERSION,
    PROMPT_VERSION,
    _build_locations_from_entities,
)


def test_build_locations_returns_flat_list_from_entity_merge():
    """entity_merge.locations[].description으로부터 raw locations flat list 생성.

    is_indoor는 LLM이 응답에서 결정 — 코드는 placeholder False로 둔다.
    visual_traits가 있으면 summary 끝에 부착.
    """
    entity_merge = {"data": {"locations": [
        {"short_id": "L01", "name": "옥탑방", "description": "rooftop unit interior",
         "visual_traits": ["좁은 거실", "낮은 천장"]},
        {"short_id": "L02", "name": "옥상", "description": "rooftop terrace"},
        {"short_id": "L03", "name": "복도", "description": "shared hallway"},
    ]}}
    shot_counts = {"L01": 12, "L02": 4, "L03": 6}
    locs = _build_locations_from_entities(entity_merge, None, shot_counts)
    by_id = {x["loc_id"]: x for x in locs}
    # is_indoor는 placeholder. LLM이 응답에서 채움.
    assert by_id["L01"]["is_indoor"] is False
    assert by_id["L01"]["shot_count"] == 12
    assert "rooftop unit interior" in by_id["L01"]["summary"]
    assert "좁은 거실" in by_id["L01"]["summary"]
    assert by_id["L01"]["label"] == "옥탑방"
    assert "rooftop terrace" in by_id["L02"]["summary"]


def test_build_locations_falls_back_when_detail_missing():
    """entity_detail이 없으면 indoor=False, summary=''이 default."""
    entity_merge = {"data": {"locations": [{"short_id": "L01", "name": "x"}]}}
    locs = _build_locations_from_entities(entity_merge, None, {"L01": 5})
    assert len(locs) == 1
    assert locs[0]["loc_id"] == "L01"
    assert locs[0]["is_indoor"] is False
    assert locs[0]["shot_count"] == 5


def test_build_locations_deterministic_order():
    """deterministic order — loc_id 정렬."""
    entity_merge = {"data": {"locations": [
        {"short_id": "L03", "name": "c"},
        {"short_id": "L01", "name": "a"},
        {"short_id": "L02", "name": "b"},
    ]}}
    locs = _build_locations_from_entities(entity_merge, None, {})
    assert [x["loc_id"] for x in locs] == ["L01", "L02", "L03"]


def test_step_disabled_when_mode_off():
    with patch("app.core.config.settings.background_mode", "off"):
        step = BackgroundClassifyStep.__new__(BackgroundClassifyStep)
        step.project_id = "p"; step.episode_id = "e"; step.project_config = {}
        step.build_opik_metadata = MagicMock(return_value={})
        result = step._execute()
        assert result["applicable_count"] == 0
        assert result["data"] == {}
