"""Area #3 W3 — detect_offscreen_drift legacy single-function residue gate.

Production code 안에서 legacy single function의 import / call site 0 hits
의무. Path 1/2 split 후 단일 함수 폐기.

Scope: backend/app/**/*.py 안 import statement + function call site only.
Docstring / comment 안 historical name reference 는 false-positive 회피를
위해 무시 (단 W3.3 production docstring 작성 시 legacy literal 0 권장 —
worker note).
"""
import re
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[2]
BACKEND_APP = REPO_ROOT / "backend" / "app"

# Match legacy single-function name (NOT followed by underscore — excludes
# _structured / _proximity_diagnostic).
# Two surfaces caught:
#   1. function call site: `detect_offscreen_drift(`
#   2. import statement: `from ... import ...detect_offscreen_drift`
#      (where "..." stays single-token, not _structured/_proximity_diagnostic)
LEGACY_CALL_PATTERN = re.compile(r"\bdetect_offscreen_drift\(")
LEGACY_IMPORT_PATTERN = re.compile(
    r"^\s*from\s+app\.modules\.pipeline\.shot_visibility\s+import\s+"
    r"[^#\n]*\bdetect_offscreen_drift\b(?!_)",
    re.MULTILINE,
)


def _is_comment_line(line: str) -> bool:
    """Strip-and-check: is this line a pure comment (starts with #)?"""
    return line.lstrip().startswith("#")


def test_no_legacy_call_or_import_in_production():
    """backend/app 안 legacy single-function call site OR import statement
    0 hits.

    Docstring / comment 안 historical name mention 은 무시 (false-positive
    회피). W3.3 worker note: production docstring 안 legacy literal 0 권장
    (test가 catch 못해도 plan 의무).
    """
    hits = []
    for py_file in BACKEND_APP.rglob("*.py"):
        try:
            content = py_file.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            continue
        lines = content.split("\n")

        # 1) Call site
        for match in LEGACY_CALL_PATTERN.finditer(content):
            line_num = content[:match.start()].count("\n") + 1
            line = lines[line_num - 1] if line_num <= len(lines) else ""
            if _is_comment_line(line):
                continue
            hits.append(
                f"{py_file.relative_to(REPO_ROOT)}:{line_num}: "
                f"call site: {line.strip()}"
            )

        # 2) Import statement
        for match in LEGACY_IMPORT_PATTERN.finditer(content):
            line_num = content[:match.start()].count("\n") + 1
            line = lines[line_num - 1] if line_num <= len(lines) else ""
            hits.append(
                f"{py_file.relative_to(REPO_ROOT)}:{line_num}: "
                f"import: {line.strip()}"
            )

    assert len(hits) == 0, (
        f"Found {len(hits)} legacy detect_offscreen_drift call/import site(s) "
        f"in production code: {hits}. Area #3 W3 requires Path 1/2 split — "
        f"use detect_offscreen_drift_structured / "
        f"detect_offscreen_drift_proximity_diagnostic only."
    )
