#!/usr/bin/env python3
import json
import sys
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
ALLOWED = {
    "Ngôn tình học đường / thanh xuân",
    "Hào môn / tổng tài / liên hôn",
    "Cưới trước yêu sau / hôn ước từ bé",
    "Thanh mai trúc mã / nuôi từ bé",
    "Trà xanh / bạch nguyệt quang / người thứ ba",
    "Thiên kim thật–giả / gia đình phản diện / trở về",
    "Yếu tố high-concept",
}
REQUIRED_MILESTONES = {
    "hook", "inciting_incident", "early_escalation", "midpoint",
    "crisis", "climax", "ending", "counterfactual_test",
}
FAMILY_TERMS = ("hôn ước", "hôn nhân", "nghĩa vụ", "điều khoản", "ly hôn", "lựa chọn")
FORBIDDEN_DOMINANT = ("cao trào nghề nghiệp", "tranh chấp cộng đồng", "điều tra hình sự")


def load(rel):
    return json.loads((PROJECT / rel).read_text(encoding="utf-8"))


def main():
    brief = load("script/story-brief.json")
    fmap = load("script/family-causal-map.json")
    outline = load("script/story-outline.json")
    issues = []
    family = brief.get("primary_story_family")
    if family not in ALLOWED:
        issues.append("family_not_in_closed_taxonomy")
    if family != fmap.get("primary_story_family") or family != outline.get("family"):
        issues.append("family_binding_mismatch")
    causal = fmap.get("causal_map", {})
    if not REQUIRED_MILESTONES.issubset(causal):
        issues.append("causal_milestones_missing")
    for milestone in REQUIRED_MILESTONES - {"counterfactual_test"}:
        value = str(causal.get(milestone, "")).casefold()
        if not any(term in value for term in FAMILY_TERMS):
            issues.append("family_engine_not_explicit:" + milestone)
    counterfactual = str(causal.get("counterfactual_test", "")).casefold()
    if "sụp" not in counterfactual or "không thể thay" not in counterfactual:
        issues.append("counterfactual_not_fail_closed")
    beats = outline.get("beats", [])
    family_beats = sum(bool(row.get("family_function")) and any(term in row["family_function"].casefold() for term in FAMILY_TERMS) for row in beats)
    if not beats or family_beats / len(beats) < 0.8:
        issues.append("family_causal_beat_coverage_below_80_percent")
    combined = json.dumps({"brief": brief, "map": fmap, "outline": outline}, ensure_ascii=False).casefold()
    for phrase in FORBIDDEN_DOMINANT:
        if phrase in combined and phrase not in json.dumps(brief.get("forbidden", []), ensure_ascii=False).casefold():
            issues.append("supporting_layer_dominates:" + phrase)
    result = {
        "verified": not issues,
        "primary_story_family": family,
        "taxonomy_closed": True,
        "milestones": len(REQUIRED_MILESTONES),
        "family_beat_coverage": family_beats / len(beats) if beats else 0,
        "issues": issues,
    }
    print(json.dumps(result, ensure_ascii=False))
    return 0 if not issues else 1


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