"""시대 원고 fixture — **다섯 갈래가 자연스럽게 다 지나는** 판. ★유료 0.

지어낸 지역(`synthetic_episode`)으로는 두 가지를 못 했다 —

    ①고증 정확성을 못 잰다 — 그 형태의 사진이 세상에 없다
    ②`character` 가 고증 대상이 못 된다 — 사람 생김새는 지역 특유가 없다

그리고 저장소의 실제 원고 47편은 **전부 현대 한국**이라 `outlook`(신발·시계)이
「그리기 어려운 것」이 아니다.

★그래서 **실제 시대·지역**(1960년대 한국)을 골랐다. 그 시대는 옷·신·그릇·
가게 꼴이 전부 지금과 달라 다섯 갈래가 **자연스럽게** 고증 대상이 되고,
**실제로 있던 것**이라 사진이 세상에 있어 사람이 눈으로 판정할 수 있다.
"""
from __future__ import annotations

import pytest

from tests.grounding.fixtures import period_episode as pe


class TestAllFiveOwnersAreNaturallyGrounded:
    def test_it_holds_together(self):
        pe.assert_planted()

    def test_every_owner_has_a_grounding_target(self):
        assert pe.acquisition_owners() == {
            "prop", "character", "location", "location_part", "outlook"}

    def test_nothing_was_forced(self):
        """★근거는 **세계 사실에 적힌 것**에서만 온다 — 지어내지 않았다."""
        w = pe.WORLD_FACTS
        for key in pe.acquisition_targets():
            basis = pe.AXIS_BASIS[key]["basis"]
            assert len(basis) > 20, f"★{key} 의 근거가 너무 짧다"
            # ★근거의 핵심 낱말이 세계 사실에 실제로 있는지
            head = basis.split(" — ")[0].split("은 ")[0].split("는 ")[0]
            assert any(tok in w for tok in head.split()[:3]), \
                f"★{key} 의 근거가 세계 사실에 없다: {head[:24]}"

    def test_there_are_negatives_too(self):
        """★전부 양성이면 축이 무디다."""
        neg = [k for k, v in pe.AXIS_BASIS.items()
               if not (v["hard"] and v["notice"])]
        assert len(neg) >= 2, f"★음성이 {len(neg)}개뿐"


class TestItLooksLikeAStoredCheckpoint:
    def test_segments_match_the_manuscript_offsets(self):
        m = pe.manuscript()
        for s in pe.segments():
            assert s["text"] in m
            assert s["length"] == len(s["text"])

    def test_shots_are_shaped_like_shot_validator(self):
        sc = pe.shot_scenes()
        assert len(sc) == 4
        n = sum(len(s["shots"]) for s in sc)
        assert n >= 6, f"★샷이 {n}개뿐 — 6~8 이상이어야"
        for s in sc:
            for sh in s["shots"]:
                assert {"shot_index", "description", "characters"} <= set(sh)

    def test_bundling_uses_the_one_shared_function(self):
        """★구간 나누기를 여기서 다시 적지 않는다."""
        import ast
        import inspect

        tree = ast.parse(inspect.getsource(pe.bundles))
        names = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)}
        assert "bundle_scenes" in names
        assert "BUNDLE_TARGET" not in names


class TestNoWorkProperNouns:
    """★역할어와 일반명사만. 특정 작품·인물·지명을 안 가리킨다."""

    def test_the_shots_name_roles_not_people(self):
        roles = {c for s in pe.shot_scenes() for sh in s["shots"]
                 for c in sh["characters"]}
        assert roles <= {"학생", "이발사", "노인", "주인"}, \
            f"★역할어가 아닌 것이 있다: {roles}"

    def test_the_era_and_region_live_only_in_world_facts(self):
        """★시대·지역은 **세계 사실 블록에만** 적는다."""
        body = pe.manuscript()
        for token in ("1960", "대한민국"):
            assert token not in body, f"★원고 본문에 {token} 이 있다"
        assert "1960년대 대한민국" in pe.WORLD_FACTS
