"""
Area #7c — t2i_review v6 placeholder example abstraction W2 integrated test wave.

5 verify gate (closed-world, no live LLM, NO VLM):
(a) Residue gate — 7 strict exact legacy phrase 0 count in new v7 dir.
(b) Schema sibling identity — 2 schema file v6 → v7 sha256 byte-identical.
(c) load_prompt / load_schema latest v7 activation — 4 stem (content-level smoke).
(d) STEP_MANIFEST["t2i_review"].schema_version == 1 preservation.
(e) Source-path version proof — _resolve_stem_in_pack 4 stem v7 dir resolution
    (Codex plan iter 1 IMPORTANT 1 흡수: v6/v7 schemas byte-identical;
    Gate (b) sha256 alone cannot prove v7 schema activation).
"""

from __future__ import annotations

import hashlib
from pathlib import Path

from app.core.step_manifest import STEP_MANIFEST
from app.modules.prompt_loader import (
    _resolve_stem_in_pack,
    load_prompt,
    load_schema,
)


T2I_REVIEW_PROMPT_BASE = (
    Path(__file__).resolve().parents[3] / "prompts" / "_base" / "t2i_review"
)
V6_DIR_NAME = "6.202605181200"


def _latest_v7_dir() -> Path:
    candidates = sorted(
        p for p in T2I_REVIEW_PROMPT_BASE.iterdir()
        if p.is_dir() and p.name.startswith("7.")
    )
    assert candidates, "no v7 t2i_review dir found under prompts/_base/t2i_review"
    return candidates[-1]


# ----------------------------------------------------------------------------
# Gate (a) — Residue gate: 7 strict exact legacy phrase 0 count in v7 dir.
# ----------------------------------------------------------------------------

STRICT_RESIDUE_SCENE: list[str] = [
    "subject's hands",
    "feet visible at lower frame edge with floor below",
    "full silhouette including head and feet visible",
    "sits hunched in the left background",
    "a hand reaching from the right edge holding a small object",
]

STRICT_RESIDUE_ENTITY: list[str] = [
    "'security guard'",
    "Asian / Korean 인종 형용사",
]


def test_residue_gate_scene_strict_phrase_absent():
    """scene_system.md v7 안 5 strict scene phrase substring 0 count."""
    v7 = _latest_v7_dir()
    content = (v7 / "scene_system.md").read_text(encoding="utf-8")
    for phrase in STRICT_RESIDUE_SCENE:
        assert phrase not in content, (
            f"strict residue scene phrase remains in v7 scene_system.md: {phrase!r}"
        )


def test_residue_gate_entity_strict_phrase_absent():
    """entity_system.md v7 안 2 strict entity phrase substring 0 count."""
    v7 = _latest_v7_dir()
    content = (v7 / "entity_system.md").read_text(encoding="utf-8")
    for phrase in STRICT_RESIDUE_ENTITY:
        assert phrase not in content, (
            f"strict residue entity phrase remains in v7 entity_system.md: {phrase!r}"
        )


def test_residue_gate_total_count():
    """7 strict residue catalog count = 5 scene + 2 entity (closed-world membership)."""
    assert len(STRICT_RESIDUE_SCENE) == 5
    assert len(STRICT_RESIDUE_ENTITY) == 2
    assert len(STRICT_RESIDUE_SCENE) + len(STRICT_RESIDUE_ENTITY) == 7


# ----------------------------------------------------------------------------
# Gate (b) — Schema sibling identity: 2 file v6 → v7 sha256 byte-identical.
# ----------------------------------------------------------------------------

def _sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def test_schema_sibling_scene_byte_identical():
    """scene_schema.json v6 = v7 sha256 byte-identical."""
    v6 = T2I_REVIEW_PROMPT_BASE / V6_DIR_NAME / "scene_schema.json"
    v7 = _latest_v7_dir() / "scene_schema.json"
    assert _sha256_file(v6) == _sha256_file(v7), (
        "scene_schema.json sha256 drift v6→v7 (Area #7c content-only contract)"
    )


def test_schema_sibling_entity_byte_identical():
    """entity_schema.json v6 = v7 sha256 byte-identical."""
    v6 = T2I_REVIEW_PROMPT_BASE / V6_DIR_NAME / "entity_schema.json"
    v7 = _latest_v7_dir() / "entity_schema.json"
    assert _sha256_file(v6) == _sha256_file(v7), (
        "entity_schema.json sha256 drift v6→v7 (Area #7c content-only contract)"
    )


# ----------------------------------------------------------------------------
# Gate (c) — load_prompt / load_schema latest v7 activation: 4 stem
# (content-level smoke; explicit v7 source proof in Gate (e)).
# ----------------------------------------------------------------------------

def test_load_prompt_scene_system_resolves_v7():
    """load_prompt('t2i_review', 'scene_system') content has new abstract wording."""
    content = load_prompt("t2i_review", "scene_system")
    assert content, "load_prompt scene_system returned empty"
    assert (
        "subject-frame-edge contact cue" in content
        or "subject body part / extended limb at frame edge" in content
    ), "scene_system.md v7 missing new abstract wording for line 31"


def test_load_prompt_entity_system_resolves_v7():
    """load_prompt('t2i_review', 'entity_system') content has new abstract wording."""
    content = load_prompt("t2i_review", "entity_system")
    assert content
    assert "common-noun character role" in content, (
        "entity_system.md v7 missing new abstract wording for line 33"
    )
    assert "required demographic descriptor" in content, (
        "entity_system.md v7 missing new abstract wording for line 34"
    )


def test_load_schema_scene_resolves_v7():
    """load_schema('t2i_review', 'scene_schema') resolves to v7 dict."""
    schema = load_schema("t2i_review", "scene_schema")
    assert isinstance(schema, dict), f"unexpected schema type: {type(schema)!r}"
    assert ("type" in schema) or ("properties" in schema) or ("items" in schema)


def test_load_schema_entity_resolves_v7():
    """load_schema('t2i_review', 'entity_schema') resolves to v7 dict."""
    schema = load_schema("t2i_review", "entity_schema")
    assert isinstance(schema, dict), f"unexpected schema type: {type(schema)!r}"


# ----------------------------------------------------------------------------
# Gate (d) — STEP_MANIFEST["t2i_review"].schema_version == 1 preservation.
# ----------------------------------------------------------------------------

def test_step_manifest_t2i_review_schema_version_preserved():
    """STEP_MANIFEST['t2i_review'].schema_version == 1 (Area #7c content-only)."""
    entry = STEP_MANIFEST["t2i_review"]
    schema_version = getattr(entry, "schema_version", None)
    if schema_version is None and isinstance(entry, dict):
        schema_version = entry.get("schema_version")
    assert schema_version == 1, (
        f"STEP_MANIFEST['t2i_review'].schema_version drift "
        f"(expected 1, got {schema_version!r})"
    )


# ----------------------------------------------------------------------------
# Gate (e) — Source-path version proof: 4 stem v7 dir resolution.
# (Codex plan iter 1 IMPORTANT 1: v6/v7 schemas byte-identical; Gate (b)
# sha256 alone cannot prove v7 schema activation. _resolve_stem_in_pack
# returns (path, found_version, all_versions); assert found_version starts
# with "7." for all 4 stems.)
# ----------------------------------------------------------------------------

def _assert_stem_resolves_v7(name: str, ext: str = ".md") -> None:
    fpath, found_ver, _versions = _resolve_stem_in_pack(
        "t2i_review", name, ext=ext
    )
    assert fpath is not None, f"stem {name}{ext} not resolved"
    assert found_ver is not None, f"stem {name}{ext} resolved to no version"
    assert found_ver.startswith("7."), (
        f"stem {name}{ext} resolved to non-v7 version: {found_ver}"
    )


def test_resolve_scene_system_v7():
    """scene_system.md stem resolves to latest v7 dir (not v6 fallback)."""
    _assert_stem_resolves_v7("scene_system", ext=".md")


def test_resolve_scene_schema_v7():
    """scene_schema.json stem resolves to latest v7 dir (Gate (b) sha256 alone cannot prove v7 source)."""
    _assert_stem_resolves_v7("scene_schema", ext=".json")


def test_resolve_entity_system_v7():
    """entity_system.md stem resolves to latest v7 dir."""
    _assert_stem_resolves_v7("entity_system", ext=".md")


def test_resolve_entity_schema_v7():
    """entity_schema.json stem resolves to latest v7 dir (Gate (b) sha256 alone cannot prove v7 source)."""
    _assert_stem_resolves_v7("entity_schema", ext=".json")
