#!/usr/bin/env python3
"""Validate independently written Chinese and English synastry reports.

The validator checks shared evidence coverage against a private dossier. It
does not translate prose and never treats one language as the other's source.
"""

from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from typing import Any, Mapping


SCHEMA = "jyotish.full_synastry_bilingual_delivery_receipt.v1"
ZH_HEADINGS = ("结论总纲", "各自带入关系的需求", "情绪安全与相处感受", "吸引与亲密", "沟通、冲突与修复", "关系如何推进", "共同生活的收益与压力", "能不能稳定走下去", "关系应期")
EN_HEADINGS = ("Relationship Thesis", "What Each Person Brings", "Emotional Safety and Lived Experience", "Attraction and Closeness", "Communication, Conflict and Repair", "How the Relationship Progresses", "Shared Life: Gains and Pressures", "Can It Stay Steady?", "Relationship Weather")
EVIDENCE_LABELS = (
    "multi_system_consensus", "single_system_inference", "parameter_sensitive",
    "unclosed_divisional_chart", "user_history_verification_required", "blocked",
)
SUPPLEMENTARY_METHOD_TERMS = ("Shukuyo", "Western synastry", "Composite chart", "Davison", "Prashna", "宿曜", "星宿关系", "西占合盘", "组合盘", "问卦")
PRIVATE_EVIDENCE_TERMS = (
    "execution_receipt", "source_map", "delivery_readiness", "module_inventory", "modules.",
    "pair_interaction_evidence", "mutual_affection_activation", "reader_section_brief",
    "recipient_experience_evidence", "d1_recipient_evidence", "d9_recipient_evidence",
    "parallel_personal_timing", "event_resonance_gate",
    "原始模块索引", "执行回执", "证据包路径", "章节证据简报", "接收方证据",
)
ZH_READER_MIN_CHARACTERS = 2000
EN_READER_MIN_WORDS = 1200
READER_BANNED_TERMS = ("灵魂伴侣", "宇宙安排", "百分百", "一定会", "soulmate", "the universe", "guaranteed", "100%")
ZH_D9_TERMS = ("D9", "九分盘", "婚姻分盘", "Navamsa", "Navamsha")
EN_D9_TERMS = ("D9", "Navamsa", "Navamsha")
ZH_ANALYST_LED_OPENERS = ("这段关系的核心", "这段关系不是", "不是有没有吸引", "不是“", "不是\"")
EN_ANALYST_LED_OPENERS = ("the core of this relationship", "this relationship is not")
ZH_AFFECTION_OPENING_TERMS = ("珍惜", "靠近", "在意", "被理解", "被重视", "安心", "温暖", "好感", "心动", "亲近", "回应", "投入")
EN_AFFECTION_OPENING_TERMS = ("cherish", "close", "care", "understood", "valued", "safe", "warm", "drawn", "affection", "respond", "invest")
ZH_SECTION_MIN_CHARACTERS = 100
EN_SECTION_MIN_WORDS = 70
ZH_AFFECTION_SECTION_WARMTH_TERMS = ("珍惜", "靠近", "在意", "被理解", "被重视", "安心", "温暖", "好感", "心动", "亲近")
ZH_AFFECTION_SECTION_BOUNDARY_TERMS = ("空间", "压力", "边界", "催促", "忽略", "退缩")
EN_AFFECTION_SECTION_WARMTH_TERMS = ("cherish", "close", "care", "understood", "valued", "safe", "warm", "drawn", "affection")
EN_AFFECTION_SECTION_BOUNDARY_TERMS = ("space", "pressure", "boundary", "rush", "ignored", "withdraw")


def _heading_status(text: str, headings: tuple[str, ...]) -> dict[str, bool]:
    return {heading: heading in text for heading in headings}


def _opening_after_heading(text: str, heading: str, headings: tuple[str, ...]) -> str:
    """Return the reader-visible opening of one section, not the whole report."""
    return _section_bodies(text, headings).get(heading, "")[:500]


def _section_bodies(text: str, headings: tuple[str, ...]) -> dict[str, str]:
    """Extract heading bodies without mistaking prose mentions for headings."""
    found: list[tuple[int, int, str]] = []
    for heading in headings:
        pattern = re.compile(
            rf"^[ \t]*(?:#{{1,6}}[ \t]*)?(?:(?:[一二三四五六七八九十]+|[0-9]+|[IVXLCDM]+)[、.．)][ \t]*)?{re.escape(heading)}[ \t#]*$",
            re.MULTILINE,
        )
        match = pattern.search(text)
        if match:
            found.append((match.start(), match.end(), heading))
    found.sort()
    bodies = {heading: "" for heading in headings}
    for index, (_start, end, heading) in enumerate(found):
        next_start = found[index + 1][0] if index + 1 < len(found) else len(text)
        bodies[heading] = text[end:next_start].strip()
    return bodies


def _opening_quality(chinese: str, english: str) -> dict[str, Any]:
    zh_opening = _opening_after_heading(chinese, "结论总纲", ZH_HEADINGS)
    en_opening = _opening_after_heading(english, "Relationship Thesis", EN_HEADINGS)
    zh_hits = [phrase for phrase in ZH_ANALYST_LED_OPENERS if phrase in zh_opening]
    en_lower = en_opening.lower()
    en_hits = [phrase for phrase in EN_ANALYST_LED_OPENERS if phrase in en_lower]
    return {
        "chinese_analyst_led_openers": zh_hits,
        "english_analyst_led_openers": en_hits,
        "status": "passed" if not zh_hits and not en_hits else "review_required",
        "boundary": "The thesis must begin with the reader's lived relationship question and answer, not an analyst-led contrast such as 'not X but Y'.",
    }


def _dossier_status(dossier: Mapping[str, Any]) -> dict[str, str]:
    rows = dossier.get("source_map", []) if isinstance(dossier.get("source_map"), list) else []
    return {
        str(row.get("label")): str(row.get("status"))
        for row in rows if isinstance(row, Mapping) and row.get("label")
    }


def _d9_pair_evidence_status(dossier: Mapping[str, Any]) -> str:
    interaction = dossier.get("pair_interaction_evidence")
    if not isinstance(interaction, Mapping):
        return "not_available"
    d9 = interaction.get("d9_interaction_evidence")
    return str(d9.get("status")) if isinstance(d9, Mapping) else "not_available"


def _mutual_affection_status(dossier: Mapping[str, Any]) -> str:
    brief = dossier.get("mutual_affection_activation")
    return str(brief.get("status")) if isinstance(brief, Mapping) else "not_available"


def _opening_affection_coverage(
    dossier: Mapping[str, Any], chinese: str, english: str,
) -> dict[str, Any]:
    """Require a warm, evidence-backed opening only when the brief exists."""
    status = _mutual_affection_status(dossier)
    required = status == "executed"
    zh_opening = _opening_after_heading(chinese, "结论总纲", ZH_HEADINGS)
    en_opening = _opening_after_heading(english, "Relationship Thesis", EN_HEADINGS).lower()
    chinese_terms = [term for term in ZH_AFFECTION_OPENING_TERMS if term in zh_opening]
    english_terms = [term for term in EN_AFFECTION_OPENING_TERMS if term in en_opening]
    return {
        "available_status": status,
        "required_in_opening": required,
        "chinese_terms": chinese_terms,
        "english_terms": english_terms,
        "status": "passed" if not required or (chinese_terms and english_terms) else "review_required",
        "boundary": (
            "A warm opening describes evidence-backed conditions for reciprocal care. "
            "It must not promise love, consent, fidelity, or an outcome."
        ),
    }


def _section_depth_coverage(chinese: str, english: str) -> dict[str, Any]:
    chinese_bodies = _section_bodies(chinese, ZH_HEADINGS)
    english_bodies = _section_bodies(english, EN_HEADINGS)
    chinese_rows = {
        heading: len(re.findall(r"[\u4e00-\u9fff]", body))
        for heading, body in chinese_bodies.items()
    }
    english_rows = {
        heading: len(re.findall(r"\b[A-Za-z][A-Za-z'-]*\b", body))
        for heading, body in english_bodies.items()
    }
    return {
        "chinese_characters": chinese_rows,
        "chinese_minimum_per_section": ZH_SECTION_MIN_CHARACTERS,
        "english_words": english_rows,
        "english_minimum_per_section": EN_SECTION_MIN_WORDS,
        "status": "passed" if (
            all(count >= ZH_SECTION_MIN_CHARACTERS for count in chinese_rows.values())
            and all(count >= EN_SECTION_MIN_WORDS for count in english_rows.values())
        ) else "review_required",
        "boundary": "This guards against heading-only sections and does not certify astrological correctness or narrative quality.",
    }


def _attraction_reciprocity_coverage(dossier: Mapping[str, Any], chinese: str, english: str) -> dict[str, Any]:
    """Require warmth and boundary coverage when reciprocal evidence exists."""
    required = _mutual_affection_status(dossier) == "executed"
    chinese_section = _section_bodies(chinese, ZH_HEADINGS)["吸引与亲密"]
    english_section = _section_bodies(english, EN_HEADINGS)["Attraction and Closeness"].lower()
    chinese_warmth = [term for term in ZH_AFFECTION_SECTION_WARMTH_TERMS if term in chinese_section]
    chinese_boundary = [term for term in ZH_AFFECTION_SECTION_BOUNDARY_TERMS if term in chinese_section]
    english_warmth = [term for term in EN_AFFECTION_SECTION_WARMTH_TERMS if term in english_section]
    english_boundary = [term for term in EN_AFFECTION_SECTION_BOUNDARY_TERMS if term in english_section]
    passed = not required or (
        chinese_warmth and chinese_boundary and english_warmth and english_boundary
    )
    return {
        "required": required,
        "chinese_warmth_terms": chinese_warmth,
        "chinese_boundary_terms": chinese_boundary,
        "english_warmth_terms": english_warmth,
        "english_boundary_terms": english_boundary,
        "status": "passed" if passed else "review_required",
        "boundary": (
            "This requires reciprocal-care and space/pressure language when evidence is executed. "
            "It does not prove consent, attraction, fidelity or any relationship outcome."
        ),
    }


def build_delivery_receipt(dossier: Mapping[str, Any], chinese: str, english: str) -> dict[str, Any]:
    source_status = _dossier_status(dossier)
    cited_labels = {label: {"zh": label in chinese, "en": label in english} for label in EVIDENCE_LABELS}
    primary_pair_tasks = [
        row for row in (dossier.get("execution_receipt", {}) or {}).get("pair_execution_tasks", [])
        if isinstance(row, Mapping) and row.get("status") in {"ready_for_comparison", "parameter_sensitive", "blocked"}
    ]
    english_cjk_ratio = len(re.findall(r"[\u4e00-\u9fff]", english)) / max(len(english), 1)
    chinese_characters = len(re.findall(r"[\u4e00-\u9fff]", chinese))
    english_words = len(re.findall(r"\b[A-Za-z][A-Za-z'-]*\b", english))
    zh_headings = _heading_status(chinese, ZH_HEADINGS)
    en_headings = _heading_status(english, EN_HEADINGS)
    d9_status = _d9_pair_evidence_status(dossier)
    d9_required = d9_status == "executed"
    d9_coverage = {
        "available_status": d9_status,
        "required_in_narrative": d9_required,
        "chinese": any(term in chinese for term in ZH_D9_TERMS),
        "english": any(term.lower() in english.lower() for term in EN_D9_TERMS),
    }
    opening_quality = _opening_quality(chinese, english)
    opening_affection = _opening_affection_coverage(dossier, chinese, english)
    section_depth = _section_depth_coverage(chinese, english)
    attraction_reciprocity = _attraction_reciprocity_coverage(dossier, chinese, english)
    return {
        "schema": SCHEMA,
        "dossier_schema": dossier.get("schema"),
        "composition": {
            "chinese": "direct_from_structured_dossier",
            "english": "direct_from_structured_dossier_not_translated_from_chinese",
        },
        "headings": {"chinese": zh_headings, "english": en_headings},
        "evidence_labels": cited_labels,
        "source_map_status": source_status,
        "pair_tasks": [{"task": row.get("task"), "status": row.get("status")} for row in primary_pair_tasks],
        "d9_narrative_coverage": d9_coverage,
        "opening_quality": opening_quality,
        "opening_affection_coverage": opening_affection,
        "section_depth_coverage": section_depth,
        "attraction_reciprocity_coverage": attraction_reciprocity,
        "supplementary_method_terms": {
            "chinese": {term: term in chinese for term in SUPPLEMENTARY_METHOD_TERMS},
            "english": {term: term in english for term in SUPPLEMENTARY_METHOD_TERMS},
        },
        "private_evidence_terms": {
            "chinese": {term: term in chinese for term in PRIVATE_EVIDENCE_TERMS},
            "english": {term: term in english for term in PRIVATE_EVIDENCE_TERMS},
        },
        "english_cjk_ratio": round(english_cjk_ratio, 5),
        "reader_depth": {
            "chinese_characters": chinese_characters,
            "chinese_minimum": ZH_READER_MIN_CHARACTERS,
            "english_words": english_words,
            "english_minimum": EN_READER_MIN_WORDS,
            "status": "passed" if chinese_characters >= ZH_READER_MIN_CHARACTERS and english_words >= EN_READER_MIN_WORDS else "review_required",
        },
        "reader_language_terms": {
            "chinese": {term: term in chinese for term in READER_BANNED_TERMS},
            "english": {term: term in english.lower() for term in READER_BANNED_TERMS},
        },
        "status": "passed" if (
            dossier.get("delivery_readiness") == "ready_for_narrative"
            and all(zh_headings.values())
            and all(en_headings.values())
            and opening_quality["status"] == "passed"
            and opening_affection["status"] == "passed"
            and section_depth["status"] == "passed"
            and attraction_reciprocity["status"] == "passed"
            and (not d9_required or (d9_coverage["chinese"] and d9_coverage["english"]))
            and not any(term in chinese for term in SUPPLEMENTARY_METHOD_TERMS)
            and not any(term in english for term in SUPPLEMENTARY_METHOD_TERMS)
            and not any(term in chinese for term in PRIVATE_EVIDENCE_TERMS)
            and not any(term in english for term in PRIVATE_EVIDENCE_TERMS)
            and chinese_characters >= ZH_READER_MIN_CHARACTERS
            and english_words >= EN_READER_MIN_WORDS
            and not any(term in chinese for term in READER_BANNED_TERMS)
            and not any(term in english.lower() for term in READER_BANNED_TERMS)
            and english_cjk_ratio < 0.05
        ) else "review_required",
        "boundary": "This validates delivery structure and shared evidence coverage. It does not prove a translation is absent or replace technical review.",
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Validate independent Chinese and English full synastry reports.")
    parser.add_argument("--dossier", required=True, help="Private full-synastry dossier JSON")
    parser.add_argument("--chinese", required=True, help="Chinese Markdown report")
    parser.add_argument("--english", required=True, help="English Markdown report written directly from the dossier")
    parser.add_argument("--output", help="Private receipt output path")
    args = parser.parse_args()
    dossier = json.loads(Path(args.dossier).read_text(encoding="utf-8"))
    chinese = Path(args.chinese).read_text(encoding="utf-8")
    english = Path(args.english).read_text(encoding="utf-8")
    receipt = build_delivery_receipt(dossier, chinese, english)
    encoded = json.dumps(receipt, ensure_ascii=False, indent=2)
    if args.output:
        Path(args.output).write_text(encoded + "\n", encoding="utf-8")
    else:
        print(encoded)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
