#!/usr/bin/env python3
"""本地 Ref2VA 提示词校验器（DSH 机自用）。

背景：原校验器随 GPU 机重装丢失（`~/minimax-h3-video-studio/skills/h3-ref2va-prompt-compiler/
scripts/validate_h3_ref2va_prompt.py`，2026-10-05 无备份）。本脚本按 2026-09-27 读到的
原脚本规则重写（正则与判定同源），用于提交前自检。

用法：
    python3 validate_h3_ref2va_local.py --profile identity-migration PROMPT.txt
通过打印：OK: valid H3 Ref2VA prompt (identity-migration)
"""
from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

SECTIONS = (
    "subject_definitions",
    "summary",
    "retention_analysis",
    "detailed_description",
    "overall_soundscape",
    "non_diegetic_music",
)
SECTION_RE = re.compile(r"(?m)^([a-z][a-z_]*):\s*$")
LABEL_RE = re.compile(r"<(Subject|Picture|Video|Audio)\s+([1-9]\d*)>")
SUBJECT_DEFINITION_RE = re.compile(r"(?m)^<Subject\s+([1-9]\d*)>\s+is\b")
RETENTION_LINE_RE = re.compile(
    r"^<(Subject|Picture|Video|Audio)\s+([1-9]\d*)>"
    r"(?:\s*\([^\n]*\))?:\s*([a-z_]+)(\s+-\s+|\.\s+|\s+for\s+|\s+as\s+)\S"
)
SHOT_RE = re.compile(r"\[Shot\s+([1-9]\d*)](?:\s+At\s+(\d{2}):(\d{2})\.(\d{3}),)?")
SUMMARY_PREFIX_RE = re.compile(r"^\[([^\]]+)]")

VISIBLE_MARKERS = {"fully_preserved", "partially_preserved", "attribute_transfer", "weak_reference"}
AUDIO_MARKERS = {"fully_copy", "partially_copy", "reference", "weak_reference"}
IDENTITY_MIGRATION_MARKERS = {"identity_not_preserved", "fully_referenced", "identity_fully_preserved"}
TASK_TYPES = {
    "keyframe completion", "reference generation", "video editing",
    "video continuation", "audio reuse", "audio reference",
}
IDENTITY_MIGRATION_TASK_TYPES = {
    "character replacement", "object replacement", "identity migration", "three-view identity reference",
}


def split_sections(prompt: str) -> tuple[list[str], dict[str, str]]:
    matches = list(SECTION_RE.finditer(prompt))
    names = [m.group(1) for m in matches]
    bodies: dict[str, str] = {}
    for i, m in enumerate(matches):
        end = matches[i + 1].start() if i + 1 < len(matches) else len(prompt)
        bodies[m.group(1)] = prompt[m.end():end]
    return names, bodies


def validate(prompt: str, profile: str) -> list[str]:
    errors: list[str] = []
    names, bodies = split_sections(prompt)

    present = [n for n in SECTIONS if n in bodies]
    if present != list(SECTIONS):
        missing = [n for n in SECTIONS if n not in bodies]
        if missing:
            errors.append(f"missing sections: {missing}")
    order = [n for n in names if n in SECTIONS]
    if order != [n for n in SECTIONS if n in order]:
        errors.append(f"section order wrong: {order}")
    if "reference_interpretation" in bodies:
        idx = names.index("reference_interpretation")
        if not (names.index("retention_analysis") < idx < names.index("detailed_description")):
            errors.append("reference_interpretation must sit between retention_analysis and detailed_description")

    summary_body = bodies.get("summary", "")
    m = SUMMARY_PREFIX_RE.match(summary_body.strip())
    if not m:
        errors.append("summary must start with a [task type] prefix")
    else:
        # 原校验器允许 identity-migration 专用任务词（character replacement 等）出现在前缀里
        allowed_types = TASK_TYPES | IDENTITY_MIGRATION_TASK_TYPES
        for part in [p.strip() for p in m.group(1).split("+")]:
            if part not in allowed_types:
                errors.append(f"unknown task type in summary prefix: {part}")
        if profile == "identity-migration":
            lower = summary_body.lower()
            if not any(t in lower for t in IDENTITY_MIGRATION_TASK_TYPES):
                errors.append("identity migration summary must explicitly name the replacement operation")

    defined_subjects = {int(n) for n in SUBJECT_DEFINITION_RE.findall(prompt)}
    for kind in ("Subject", "Picture", "Video", "Audio"):
        numbers = sorted({int(n) for k, n in LABEL_RE.findall(prompt) if k == kind})
        if numbers and numbers != list(range(1, max(numbers) + 1)):
            errors.append(f"{kind} labels are not contiguous from 1: {numbers}")

    retention = bodies.get("retention_analysis", "")
    for line in retention.splitlines():
        if not LABEL_RE.match(line):
            continue
        match = RETENTION_LINE_RE.match(line)
        if not match:
            errors.append(f"invalid retention line format: {line}")
            continue
        kind, _number, marker, separator = match.groups()
        allowed = AUDIO_MARKERS if kind == "Audio" else VISIBLE_MARKERS
        if profile == "identity-migration" and kind != "Audio":
            allowed = allowed | IDENTITY_MIGRATION_MARKERS
        if marker not in allowed:
            errors.append(f"invalid {kind} retention marker: {marker}")
        if profile == "official" and not separator.strip().startswith("-"):
            errors.append(f"invalid retention line format: {line}")

    shots = SHOT_RE.findall(bodies.get("detailed_description", ""))
    if shots:
        shot_numbers = [int(n) for n, *_ in shots]
        if shot_numbers != list(range(1, len(shot_numbers) + 1)):
            errors.append(f"shot numbers must be consecutive from 1: {shot_numbers}")
        if shots[0][1]:
            errors.append("[Shot 1] must not have a timestamp")
        for number, minutes, seconds, _ms in shots[1:]:
            if not minutes:
                errors.append(f"[Shot {number}] must use At MM:SS.mmm,")
            elif int(seconds) >= 60:
                errors.append(f"[Shot {number}] timestamp seconds must be below 60")

    if prompt.count("<d>") != prompt.count("</d>"):
        errors.append("dialogue tags are unbalanced")

    if profile == "identity-migration":
        summary_lower = summary_body.lower()
        retention_lower = retention.lower()
        detail_lower = bodies.get("detailed_description", "").lower()
        if not ({1, 2} <= defined_subjects):
            errors.append("identity migration must define source <Subject 1> and target <Subject 2>")
        if not any(v in prompt.lower() for v in
                   ("replace <subject 1> with <subject 2>", "<subject 2> completely replaces <subject 1>")):
            errors.append("identity migration must explicitly replace <Subject 1> with <Subject 2>")
        for label, marker in (("<subject 1>", "identity_not_preserved"),
                              ("<picture 1>", "fully_referenced"),
                              ("<subject 2>", "identity_fully_preserved")):
            if not re.search(rf"(?m)^{re.escape(label)}[^\n]*:\s*{marker}\b", retention_lower):
                errors.append(f"identity migration requires {label} to use {marker}")
        if not re.search(r"(?m)^<video 1>[^\n]*:\s*fully_preserved\b", retention_lower):
            errors.append("identity migration requires <Video 1> non-identity content to be fully_preserved")
        if not any(t in summary_lower for t in ("character replacement", "object replacement", "identity migration")):
            errors.append("identity migration summary must explicitly name the replacement operation")
        if "at 0.00 seconds" not in detail_lower:
            errors.append("identity migration must anchor the target identity at 0.00 seconds")

        declares_three_view = "three-view" in prompt.lower() or all(
            t in prompt.lower() for t in ("front view", "side view", "back view"))
        interpretation = bodies.get("reference_interpretation", "").lower()
        if declares_three_view:
            if not interpretation:
                errors.append("three-view identity migration requires reference_interpretation")
            for term in ("front", "side", "back", "same"):
                if term not in interpretation:
                    errors.append(f"reference_interpretation must explain: {term}")
    return errors


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("prompt_file")
    ap.add_argument("--profile", default="identity-migration",
                    choices=["identity-migration", "official"])
    a = ap.parse_args()
    text = Path(a.prompt_file).read_text(encoding="utf-8")
    errs = validate(text, a.profile)
    if errs:
        for e in errs:
            print("ERROR:", e)
        return 1
    print(f"OK: valid H3 Ref2VA prompt ({a.profile})")
    return 0


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