#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""G4.5a canary — view-mixing extension (G4.4 carry + Rule J extension, Task 4.4).

Detect:
1. **G4.4 view-mixing carry** — same-character-ID full-body verb (`stands`/
   `seated`/`leaning`/`walking`/`running`/`kneeling`/`lying`) co-occurrence
   with body-part close-up trigger (`focus on`/`close on`/`tight on`/
   `detail on`) within ±20 token nearest-character distance. baseline
   regression 0 verification — G4.4 v19 baseline must remain at 0.
2. **G4.5a Rule J extension** — close-framing shot scope, **2 distinct
   character IDs** both having face/head close-up keyword (`face` / `눈` /
   `얼굴`) within their respective ±20 token windows. close-framing scope
   uses `_SPATIAL_FRAMING_CLOSE_KEYWORDS` 9-entry production-aligned (RO-5).

Total `view_mixing_extension_count = g4_4_view_mixing_count + two_face_close_up_count`.

Scope: ALL pinned shots — both detectors are intent-agnostic (G4.4 carry
+ G4.5a extension).

PR4-B7 binding: STRICT 0 — exit 1 on any violation. baseline regression
gate enforces G4.4 v19 == 0 condition (carry verification).

Trap #1 silent-fallback ban / Trap #3 CP shape / Trap #4 pinned-tuple
post-loop / Trap #8 module-level constants.

Override O-17 — regex/substring detector is 1차 only. baseline 비0 시 P1
follow-up: LLM-validator (gpt-5.4-mini judge) 전환.

Usage (config mode):
    python scripts/canary/g4_5a_view_mixing_extension.py \\
        --config canary_config.json \\
        --cp-root data/projects/<pid>/checkpoints/scene_detail \\
        --prompt-version 20.<timestamp> \\
        --role candidate \\
        --output results/g4_5a_view_mixing_ext_candidate.json
"""
from __future__ import annotations

import argparse
import re
import sys
from datetime import datetime
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from _g4_5a_common import (  # noqa: E402
    _load_scenes_or_fail,
    _validate_scene_preflight,
    build_pinning_scene_set,
    emit_output,
    load_cp_manifest,
    load_pinning_from_args,
    render_prompt_card_imports,
    resolve_cp_root,
    validate_pinning,
)

_CONSTS = render_prompt_card_imports()
_SPATIAL_FRAMING_CLOSE_KEYWORDS = _CONSTS["_SPATIAL_FRAMING_CLOSE_KEYWORDS"]
# RO-11 binding: G4.3 `_ID_BODY_PART_TRIGGERS` external import — NO alias.
# Spec §5.4 Trap #8 also re-imports `compute_render_strategy_snapshot_hash` so
# module-level dependency is auditable via grep (helper is invoked transitively
# by preflight helper).
from app.core.steps.render_prompt_card import (  # noqa: E402,F401
    _ID_BODY_PART_TRIGGERS,
    compute_render_strategy_snapshot_hash,
)

_ID_REGEX = re.compile(r"\bC\d{2}(?:O\d{2})?\b")

# G4.4 ground-truth: 7 full-body verbs (G4.4 carry — `g4_4_view_mixing.py`
# alignment).
_VIEW_MIXING_FULL_BODY_VERBS: tuple[str, ...] = (
    "stands",
    "seated",
    "leaning",
    "walking",
    "running",
    "kneeling",
    "lying",
)

# G4.5a Rule J extension: face/head close-up keywords (paired with character ID
# proximity ±20 tokens). LLM-facing card 11-entry list 와 다름 (canary 만 사용).
_FACE_CLOSE_UP_KEYWORDS: tuple[str, ...] = (
    "face",
    "눈",
    "얼굴",
)

# ±20 tokens (G4.4 carry — view-mixing window).
_WINDOW_TOKENS = 20


def iso8601_now() -> str:
    return datetime.utcnow().isoformat() + "Z"


def _tokenize(text: str) -> list[str]:
    """Whitespace tokenizer (G4.4 carry parity)."""
    return text.split()


def _build_cid_positions(tokens: list[str]) -> dict[str, list[int]]:
    """Build dict {cid: [token_pos]}."""
    cid_positions: dict[str, list[int]] = {}
    for pos, tok in enumerate(tokens):
        m = _ID_REGEX.search(tok)
        if m is not None:
            cid = m.group()
            if cid in cid_positions:
                cid_positions[cid].append(pos)
            else:
                cid_positions[cid] = [pos]
    return cid_positions


def _nearest_cid(
    target_pos: int,
    cid_positions: dict[str, list[int]],
) -> tuple[str | None, int]:
    """Return (cid, distance) for nearest cid within ±20 tokens."""
    best_cid: str | None = None
    best_dist = _WINDOW_TOKENS + 1
    for cid, positions in cid_positions.items():
        for cp in positions:
            d = abs(cp - target_pos)
            if d <= _WINDOW_TOKENS and d < best_dist:
                best_cid = cid
                best_dist = d
    return best_cid, best_dist


def _detect_g4_4_view_mixing(prompt: str) -> int:
    """G4.4 carry — same-character-ID full-body verb + body-part trigger
    co-occurrence within ±20 token nearest-character distance.

    Returns count of view-mixing pairs in this prompt.
    """
    tokens = _tokenize(prompt)
    cid_positions = _build_cid_positions(tokens)
    if not cid_positions:
        return 0

    n = len(tokens)
    # Collect full-body verb positions (single token substring).
    fb_positions: list[int] = []
    for pos, tok in enumerate(tokens):
        tok_lower = tok.lower()
        if any(v.lower() in tok_lower for v in _VIEW_MIXING_FULL_BODY_VERBS):
            fb_positions.append(pos)

    # Collect body-part close-up trigger positions (multi-word).
    trig_positions: list[int] = []
    for pos in range(n):
        for trigger in _ID_BODY_PART_TRIGGERS:
            tlen = len(trigger.split())
            if pos + tlen > n:
                continue
            window_text = " ".join(tokens[pos:pos + tlen]).lower()
            if window_text == trigger.lower():
                trig_positions.append(pos)
                break

    if not fb_positions or not trig_positions:
        return 0

    violations = 0
    seen_pairs: set[tuple[int, int]] = set()
    for tpos in trig_positions:
        cid_trigger, dist_trigger = _nearest_cid(tpos, cid_positions)
        if cid_trigger is None or dist_trigger > _WINDOW_TOKENS:
            continue
        for fpos in fb_positions:
            cid_body, dist_body = _nearest_cid(fpos, cid_positions)
            if cid_body is None or dist_body > _WINDOW_TOKENS:
                continue
            if cid_trigger == cid_body:
                pair_key = (tpos, fpos)
                if pair_key in seen_pairs:
                    continue
                seen_pairs.add(pair_key)
                violations += 1
    return violations


def _detect_two_face_close_up(prompt: str) -> int:
    """G4.5a Rule J extension — close-framing scope, 2 distinct cids each with
    face/head close-up keyword within ±20 token nearest-character distance.

    Returns 1 if 2+ distinct character IDs each have a face/head close-up
    keyword within their respective ±20 windows; else 0. Per-shot scope.
    """
    prompt_lower = prompt.lower()
    # close-framing scope filter (RO-5 — 9-entry production-aligned).
    if not any(
        kw.lower() in prompt_lower for kw in _SPATIAL_FRAMING_CLOSE_KEYWORDS
    ):
        return 0

    tokens = _tokenize(prompt)
    cid_positions = _build_cid_positions(tokens)
    if len(cid_positions) < 2:
        return 0

    # Collect face/head keyword positions.
    face_positions: list[int] = []
    for pos, tok in enumerate(tokens):
        tok_lower = tok.lower()
        if any(kw.lower() in tok_lower for kw in _FACE_CLOSE_UP_KEYWORDS):
            face_positions.append(pos)

    if len(face_positions) < 2:
        return 0

    # For each face position, find nearest cid; collect distinct cids that
    # have a face keyword within ±20 token window.
    cids_with_face: set[str] = set()
    for fpos in face_positions:
        cid, dist = _nearest_cid(fpos, cid_positions)
        if cid is not None and dist <= _WINDOW_TOKENS:
            cids_with_face.add(cid)

    return 1 if len(cids_with_face) >= 2 else 0


def main() -> int:
    parser = argparse.ArgumentParser(
        description=(
            "G4.5a canary: view-mixing extension (G4.4 carry baseline 회귀 "
            "0 + Rule J extension, all pinned shots, STRICT 0)."
        )
    )
    parser.add_argument("--config", type=str, default=None)
    parser.add_argument("--pid", type=str, default=None)
    parser.add_argument("--cp-root", type=str, default=None)
    parser.add_argument("--prompt-version", type=str, required=True)
    parser.add_argument(
        "--role",
        type=str,
        default="candidate",
        choices=["baseline", "candidate"],
    )
    parser.add_argument("--scene-index-list", type=str, default=None)
    parser.add_argument(
        "--shot-index-list-per-scene", type=str, default=None
    )
    parser.add_argument("--model-routing", type=str, default=None)
    parser.add_argument(
        "--prompt-source-mode",
        type=str,
        default=None,
        choices=[None, "file", "db"],
    )
    parser.add_argument("--card-commit-hash", type=str, default=None)
    parser.add_argument(
        "--render-strategy-card-snapshot-hash", type=str, default=None
    )
    parser.add_argument("--output", type=str, required=True)
    args = parser.parse_args()

    pinning = load_pinning_from_args(args)
    validate_pinning(pinning)
    cp_root = resolve_cp_root(args)
    cp = load_cp_manifest(cp_root)

    measurement_failures: list[str] = []
    scenes = _load_scenes_or_fail(cp, measurement_failures)
    if scenes is None:
        out = _empty_output(args, pinning, measurement_failures)
        emit_output(out, args)
        return 1

    pinning_set = build_pinning_scene_set(pinning)
    seen_in_cp: set[tuple[int, int]] = set()

    total_shots = 0
    g4_4_view_mixing_count = 0
    two_face_close_up_count = 0
    view_mixing_per_shot: dict[str, dict[str, int]] = {}
    scene_set_out: list[dict] = []

    for scene in scenes:
        if not isinstance(scene, dict):
            measurement_failures.append("scene entry is not dict")
            continue
        if "scene_index" not in scene or "_shot_index" not in scene:
            measurement_failures.append(
                "scene missing scene_index/_shot_index"
            )
            continue
        si = scene["scene_index"]
        shi = scene["_shot_index"]
        if si is None or shi is None:
            continue
        si_int = int(si)
        shi_int = int(shi)
        if (si_int, shi_int) not in pinning_set:
            continue
        seen_in_cp.add((si_int, shi_int))

        variations = _validate_scene_preflight(
            scene, si_int, shi_int, measurement_failures
        )
        if variations is None:
            continue

        scene_set_out.append({
            "scene_index": si_int,
            "shot_index": shi_int,
        })
        total_shots += 1

        shot_g4_4 = 0
        shot_two_face = 0
        for vi, var in enumerate(variations):
            if not isinstance(var, dict):
                measurement_failures.append(
                    f"s{si_int}_sh{shi_int}_v{vi}: variation not a dict"
                )
                continue
            if "t2i_prompt" not in var:
                measurement_failures.append(
                    f"s{si_int}_sh{shi_int}_v{vi}: t2i_prompt key missing"
                )
                continue
            prompt = var["t2i_prompt"]
            if not isinstance(prompt, str) or not prompt.strip():
                measurement_failures.append(
                    f"s{si_int}_sh{shi_int}_v{vi}: t2i_prompt missing, "
                    f"empty, or not str"
                )
                continue
            shot_g4_4 += _detect_g4_4_view_mixing(prompt)
            shot_two_face += _detect_two_face_close_up(prompt)

        g4_4_view_mixing_count += shot_g4_4
        two_face_close_up_count += shot_two_face
        if shot_g4_4 > 0 or shot_two_face > 0:
            view_mixing_per_shot[f"{si_int}_{shi_int}"] = {
                "g4_4_view_mixing": shot_g4_4,
                "two_face_close_up": shot_two_face,
            }

    # Trap #4 — pinned-tuple post-loop validation.
    for (si, shi) in pinning_set:
        if (si, shi) not in seen_in_cp:
            measurement_failures.append(
                f"pinning (s{si}_sh{shi}): not present in CP data.scenes"
            )

    view_mixing_extension_count = (
        g4_4_view_mixing_count + two_face_close_up_count
    )

    out = {
        "timestamp": iso8601_now(),
        "prompt_version": args.prompt_version,
        "role": args.role,
        "pinning": pinning,
        "scene_set": scene_set_out,
        "metrics": {
            "total_shots": total_shots,
            "g4_4_view_mixing_count": g4_4_view_mixing_count,
            "two_face_close_up_count": two_face_close_up_count,
            "view_mixing_extension_count": view_mixing_extension_count,
            "view_mixing_per_shot": view_mixing_per_shot,
            "trigger_phrases_used": list(_ID_BODY_PART_TRIGGERS),
            "full_body_verbs_used": list(_VIEW_MIXING_FULL_BODY_VERBS),
            "face_close_up_keywords_used": list(_FACE_CLOSE_UP_KEYWORDS),
        },
        "measurement_failures": measurement_failures,
        "exit_criteria_threshold": 0,
        "exit_criteria_pass": (
            not measurement_failures
            and view_mixing_extension_count == 0
        ),
        "measurement_scripts": {
            "view_mixing_extension": (
                "scripts/canary/g4_5a_view_mixing_extension.py "
                "(all pinned shots, G4.4 carry baseline 회귀 0 + Rule J "
                "extension ±20 tokens, Override O-17 regex 1차 only)"
            )
        },
    }

    emit_output(out, args)

    print(
        f"[g4_5a_view_mixing_extension] role={args.role} "
        f"prompt_version={args.prompt_version}\n"
        f"  total_shots={total_shots}\n"
        f"  g4_4_view_mixing_count={g4_4_view_mixing_count}  "
        f"two_face_close_up_count={two_face_close_up_count}\n"
        f"  view_mixing_extension_count={view_mixing_extension_count}\n"
        f"  measurement_failures: {len(measurement_failures)}\n"
        f"Exit criteria (STRICT 0): "
        f"candidate.metrics.view_mixing_extension_count == 0",
        file=sys.stderr,
    )

    if measurement_failures:
        return 1
    if args.role == "candidate" and view_mixing_extension_count > 0:
        return 1
    return 0


def _empty_output(
    args: argparse.Namespace,
    pinning: dict,
    measurement_failures: list,
) -> dict:
    return {
        "timestamp": iso8601_now(),
        "prompt_version": args.prompt_version,
        "role": args.role,
        "pinning": pinning,
        "scene_set": [],
        "metrics": {
            "total_shots": 0,
            "g4_4_view_mixing_count": 0,
            "two_face_close_up_count": 0,
            "view_mixing_extension_count": 0,
            "view_mixing_per_shot": {},
            "trigger_phrases_used": list(_ID_BODY_PART_TRIGGERS),
            "full_body_verbs_used": list(_VIEW_MIXING_FULL_BODY_VERBS),
            "face_close_up_keywords_used": list(_FACE_CLOSE_UP_KEYWORDS),
        },
        "measurement_failures": measurement_failures,
        "exit_criteria_threshold": 0,
        "exit_criteria_pass": False,
        "measurement_scripts": {
            "view_mixing_extension": (
                "scripts/canary/g4_5a_view_mixing_extension.py "
                "(all pinned shots, G4.4 carry + Rule J extension)"
            )
        },
    }


if __name__ == "__main__":
    sys.exit(main())
