"""Area #6 v1 residue gate — scoped Python residue test (spec §6.2 strict gate 본체).

2 test:
  1. test_active_v6_no_target_suggestion_field — v6 pack 4 file 안 target/suggestion field syntax 0
  2. test_production_no_blind_mutation — t2i_review.py 안 mutation site + reader pattern 모두 0

Codex implementation-plan note (spec §6 verbatim): 본 scoped Python test 가
strict residue gate 본체, broad rg 는 advisory/manual reference only.
"""
import pathlib
import re

import pytest


# Path resolution: REPO_ROOT 기반 (parents[3] = repo root, PROMPT_DIR 가 backend 외부 prompts/).
# pytest CWD=backend/ 와 독립적으로 동작 (codebase 일관 패턴, plan amend 7 정합).
PROMPT_DIR = pathlib.Path(__file__).resolve().parents[3] / "prompts/_base/t2i_review"


def test_active_v6_no_target_suggestion_field():
    """v6 pack 4 file (entity_system.md / entity_schema.json / scene_system.md /
    scene_schema.json) 안 target/suggestion field syntax 0.

    Codex Round 5 NEEDS_REVISION_MINOR Finding 3 fix-up: .md system prompt 도 검사
    의무. .md 안 일반 영어 단어 false positive 회피 위해 schema field syntax pattern
    (`"target":` JSON / `- target:` markdown bullet) 만 검사.

    closure claim 단일화 (Codex Round 6 narrow finding): "field syntax 0" wording 만.
    """
    v6_dirs = sorted(PROMPT_DIR.glob("6.*"))
    assert len(v6_dirs) == 1, (
        f"single active v6 pack 의무, got {len(v6_dirs)}: {[d.name for d in v6_dirs]}"
    )
    v6 = v6_dirs[0]
    files = sorted(v6.iterdir())
    assert {f.name for f in files} == {
        "entity_system.md", "entity_schema.json", "scene_system.md", "scene_schema.json",
    }, f"v6 pack 4 file 의무, got {[f.name for f in files]}"

    forbidden_patterns = [
        r'"target"\s*:',            # JSON schema field
        r'"suggestion"\s*:',         # JSON schema field
        r'^\s*-\s*target\s*:',      # Markdown protocol bullet
        r'^\s*-\s*suggestion\s*:',  # Markdown protocol bullet
    ]
    for fp in files:
        s = fp.read_text()
        for pat in forbidden_patterns:
            hits = re.findall(pat, s, re.MULTILINE)
            assert not hits, (
                f"{fp.name} contains forbidden pattern {pat!r}: {hits[:3]}"
            )


def test_production_no_blind_mutation():
    """t2i_review.py 안 mutation site + target/suggestion reader pattern 모두 0.

    Codex Round 5 NEEDS_REVISION_MINOR Finding 3 fix-up: reader pattern 잔존 시
    v6 schema 활성 후 KeyError 발생. mutation site grep 만으로는 W1 atomicity
    보장 X — reader pattern 도 의무.
    """
    # Path resolution: BACKEND_ROOT 기반 (parents[2] = backend/). pytest CWD=backend/
    # 와 독립적으로 동작 (codebase 일관 패턴, plan amend 6/7 정합).
    BACKEND_ROOT = pathlib.Path(__file__).resolve().parents[2]
    src = (BACKEND_ROOT / "app/modules/pipeline/t2i_review.py").read_text()

    mutation_patterns = [
        r"old\.replace\(target,\s*suggestion\)",
        r"old_prompt\.replace\(target,\s*suggestion\)",
        r"\.replace\(target,\s*suggestion\)",
        r"target\s+in\s+old\b",
        r"target\s+in\s+old_prompt\b",
    ]
    # Codex Round 1 Important #3 fix-up: comma-default form (e.g., fix.get("target", "")) 도 잡히도록
    # close paren `\)` 폐기, open-ended match.
    reader_patterns = [
        r'iss\["target"\]',
        r'iss\["suggestion"\]',
        r'(?:iss|fix)\.get\(\s*["\']target["\']',     # open-ended: catches .get("target"), .get("target", ""), 등
        r'(?:iss|fix)\.get\(\s*["\']suggestion["\']',
        r'fix\["target"\]',
        r'fix\["suggestion"\]',
    ]
    for pat in mutation_patterns + reader_patterns:
        assert re.search(pat, src) is None, (
            f"forbidden pattern {pat!r} found in t2i_review.py"
        )

    # t2i_review_step.py 의 mutation site / reader pattern 도 0 확인 (caller scope)
    src_step = (BACKEND_ROOT / "app/core/steps/t2i_review_step.py").read_text()
    for pat in mutation_patterns + reader_patterns:
        assert re.search(pat, src_step) is None, (
            f"forbidden pattern {pat!r} found in t2i_review_step.py"
        )
