"""
Honeycutt Ai Labs-P2-GROUND-001 — Natural Language Grounding Test
Does Latin medical text show the same positional constraints as VMS operator chains?

Two approaches:
  A: Character-level mapping (each Latin letter → nearest EVA operator equivalent)
  B: Word-level structural mapping (treat Latin words as tokens, map word structure)

Critical test per ECP-1: if Latin PASSES (same constraints), we may be detecting
language structure, not shorthand structure, and the breviarium hypothesis loses
its primary computational evidence.
"""
import os
import re
import random
from collections import Counter, defaultdict

# ============================================================
# LATIN-TO-OPERATOR MAPPING (Approach A)
# Based on stroke-form analogy, not phonetics
# ============================================================

LATIN_CHAR_MAP = {
    # Vowels → VMS vowel-class
    'a': 'a', 'e': 'e', 'i': 'i', 'o': 'o', 'u': 'o',
    # Common consonants → single primitives
    'n': 'n', 'r': 'r', 's': 's', 't': 't', 'l': 'l',
    'd': 'd', 'k': 'k', 'c': 'k', 'm': 'm', 'f': 'f',
    'p': 'p', 'b': 'd', 'g': 'k', 'h': 'k',
    'v': 'o', 'w': 'o',
    'x': 'k', 'z': 's',
    'j': 'i', 'y': 'y',
    # q is nearly always followed by u in Latin → map to [QO] analog
    'q': 'k',  # mapped at char level; [QO] handled at bigram level
}

# Bigrams that map to compound operators (Approach A)
LATIN_BIGRAM_MAP = {
    'qu': '[QO]',  # q+u in Latin → prefix compound
    'ch': '[CH]',  # Latin ch → paired arc
    'sh': '[SH]',  # rare in Latin but present
    'th': 't',     # Latin th is NOT a gallows equivalent at char level
}


def map_latin_word_to_operators_A(word: str) -> list[str]:
    """Approach A: character-level mapping with bigram compounds."""
    ops = []
    i = 0
    w = word.lower()

    while i < len(w):
        # Try bigrams first
        if i + 1 < len(w):
            bigram = w[i:i+2]
            if bigram in LATIN_BIGRAM_MAP:
                result = LATIN_BIGRAM_MAP[bigram]
                if result.startswith('['):
                    ops.append(result)
                else:
                    ops.append(result)
                i += 2
                continue

        # Minim runs: consecutive i's (maps like VMS minims)
        if w[i] == 'i':
            run = 0
            while i + run < len(w) and w[i + run] == 'i':
                run += 1
            if run >= 2:
                ops.append(f"[M{run}]")
                i += run
                continue

        # Single char
        ch = w[i]
        if ch in LATIN_CHAR_MAP:
            ops.append(LATIN_CHAR_MAP[ch])
        # else skip (numbers, punctuation)
        i += 1

    return ops


def map_latin_word_to_operators_B(word: str) -> list[str]:
    """Approach B: word-level structural mapping.

    Treat each Latin word as a token. Map based on positional role
    within the word — initial consonant cluster, vowel core, terminal.
    This tests whether Latin WORD STRUCTURE produces VMS-like patterns.
    """
    # Same character mapping but we explicitly track position
    return map_latin_word_to_operators_A(word)  # For now, same mapping
    # The positional ANALYSIS (not mapping) is where Approach B differs


# ============================================================
# LOAD + PREPROCESS LATIN TEXT
# ============================================================

def load_latin_corpus(filepath: str, max_chars: int = 50000) -> list[str]:
    """Load Latin text, clean OCR artifacts, return list of words."""
    with open(filepath, 'r', encoding='latin-1') as f:
        raw = f.read(max_chars)

    # Basic OCR cleanup
    raw = re.sub(r'\d+', '', raw)  # remove digits (page numbers, OCR noise)
    raw = re.sub(r'[^\w\s]', ' ', raw)  # punctuation → space
    raw = re.sub(r'\s+', ' ', raw).strip()

    # Split into words, filter short junk
    words = [w.strip() for w in raw.split() if len(w.strip()) >= 2]
    return words


# ============================================================
# POSITIONAL ANALYSIS (same as reclassify.py)
# ============================================================

def positional_analysis(operator_chains: list[list[str]]) -> dict:
    """Compute position statistics for each operator."""
    positions = defaultdict(lambda: {"initial": 0, "medial": 0, "terminal": 0,
                                      "solo": 0, "total": 0})

    for ops in operator_chains:
        if len(ops) == 0:
            continue
        if len(ops) == 1:
            positions[ops[0]]["solo"] += 1
            positions[ops[0]]["total"] += 1
        else:
            for i, op in enumerate(ops):
                positions[op]["total"] += 1
                if i == 0:
                    positions[op]["initial"] += 1
                elif i == len(ops) - 1:
                    positions[op]["terminal"] += 1
                else:
                    positions[op]["medial"] += 1

    return dict(positions)


# ============================================================
# MONTE CARLO
# ============================================================

def monte_carlo_positional(operator_freq: Counter, chain_lengths: list[int],
                           constraints: dict, trials: int = 10000) -> dict:
    """Generate random sequences from the given frequency distribution.
    Check how many pass all positional constraints.

    constraints = {"n": {"terminal_min_pct": 0.95}, ...}
    """
    operators = list(operator_freq.keys())
    weights = [operator_freq[op] for op in operators]
    total_weight = sum(weights)
    probs = [w / total_weight for w in weights]

    passes = 0
    for _ in range(trials):
        # Generate random chains with the same length distribution
        random_chains = []
        for length in random.sample(chain_lengths, min(100, len(chain_lengths))):
            chain = random.choices(operators, weights=probs, k=length)
            random_chains.append(chain)

        # Check constraints
        pos = positional_analysis(random_chains)
        all_pass = True
        for op, rules in constraints.items():
            if op not in pos:
                continue
            p = pos[op]
            non_solo = p["total"] - p["solo"]
            if non_solo == 0:
                continue
            if "never_terminal" in rules and p["terminal"] > 0:
                all_pass = False
                break
            if "never_initial" in rules and p["initial"] > 0:
                all_pass = False
                break
            if "terminal_min_pct" in rules:
                term_pct = p["terminal"] / non_solo
                if term_pct < rules["terminal_min_pct"]:
                    all_pass = False
                    break

        if all_pass:
            passes += 1

    return {
        "trials": trials,
        "passes": passes,
        "pass_rate": passes / trials,
    }


# ============================================================
# VMS BASELINES (from f1r validated analysis)
# ============================================================

VMS_POSITIONAL_CONSTRAINTS = {
    "n": {"never_initial": True, "terminal_min_pct": 0.90},
    "[CH]": {"never_terminal": True},
    "[SH]": {"never_terminal": True},
    "a": {"never_terminal": True},
    "[M2]": {"never_terminal": True, "never_initial": True},
    "i": {"never_terminal": True, "never_initial": True},
    "t": {"never_terminal": True},
}


# ============================================================
# MAIN GROUNDING TEST
# ============================================================

def run_grounding_test():
    CORPUS_PATH = "../../../resources/tools/provenance/index.html#s-eb13fa64c160e592 medica.txt"

    print("=" * 70)
    print("Honeycutt Ai Labs-P2-GROUND-001 — Natural Language Grounding Test")
    print("=" * 70)
    print()

    # Load corpus
    print("Loading Montagnana Consilia Medica (1476)...")
    words = load_latin_corpus(CORPUS_PATH, max_chars=50000)
    print(f"  Words loaded: {len(words)}")
    print(f"  Sample: {' '.join(words[:15])}")
    print()

    # === APPROACH A: Character-level mapping ===
    print("=" * 50)
    print("APPROACH A: Character-level mapping")
    print("=" * 50)

    chains_A = [map_latin_word_to_operators_A(w) for w in words]
    chains_A = [c for c in chains_A if len(c) > 0]

    total_ops_A = sum(len(c) for c in chains_A)
    op_freq_A = Counter()
    for c in chains_A:
        op_freq_A.update(c)

    print(f"  Total operator units: {total_ops_A}")
    print(f"  Total chains (words): {len(chains_A)}")
    print(f"  Unique operators: {len(op_freq_A)}")
    print()

    # Positional analysis
    pos_A = positional_analysis(chains_A)

    print("  POSITIONAL CONSTRAINTS vs VMS BASELINES:")
    print(f"  {'Constraint':<30s} {'VMS f1r':<20s} {'Latin (A)':<20s} {'Match?'}")
    print("  " + "-" * 85)

    results_A = {}
    for op, rules in VMS_POSITIONAL_CONSTRAINTS.items():
        if op not in pos_A:
            print(f"  {op:<30s} (constrained)          (not present)          N/A")
            continue

        p = pos_A[op]
        non_solo = p["total"] - p["solo"]
        if non_solo == 0:
            continue

        term_pct = p["terminal"] / non_solo * 100 if non_solo else 0
        init_pct = p["initial"] / non_solo * 100 if non_solo else 0

        if "never_terminal" in rules:
            vms_desc = "0% terminal"
            latin_desc = f"{term_pct:.1f}% terminal ({p['terminal']}/{non_solo})"
            match = "✓ MATCH" if p["terminal"] == 0 else "✗ DIFFERENT"
            results_A[op] = {"constraint": "never_terminal", "latin_pct": term_pct,
                             "match": p["terminal"] == 0}
        elif "terminal_min_pct" in rules:
            min_pct = rules["terminal_min_pct"] * 100
            vms_desc = f"≥{min_pct:.0f}% terminal"
            latin_desc = f"{term_pct:.1f}% terminal ({p['terminal']}/{non_solo})"
            match = "✓ MATCH" if term_pct >= min_pct else "✗ DIFFERENT"
            results_A[op] = {"constraint": "terminal_min_pct", "latin_pct": term_pct,
                             "match": term_pct >= min_pct}

        if "never_initial" in rules:
            vms_init = "0% initial"
            latin_init = f"{init_pct:.1f}% initial ({p['initial']}/{non_solo})"
            init_match = "✓" if p["initial"] == 0 else "✗"
            results_A[op + "_init"] = {"constraint": "never_initial", "latin_pct": init_pct,
                                        "match": p["initial"] == 0}
            print(f"  {op + ' never-initial':<30s} {vms_init:<20s} {latin_init:<20s} {init_match}")

        print(f"  {op:<30s} {vms_desc:<20s} {latin_desc:<20s} {match}")

    print()

    # Count matches vs differences
    matches_A = sum(1 for v in results_A.values() if v["match"])
    diffs_A = sum(1 for v in results_A.values() if not v["match"])
    print(f"  SUMMARY: {matches_A} constraints match, {diffs_A} differ")
    print()

    # === APPROACH B analysis uses same mapping but we note it ===
    print("=" * 50)
    print("APPROACH B: Word-level structural mapping")
    print("(Same char→operator mapping, but analysis is on word-as-token)")
    print("=" * 50)
    print("  (Results identical to Approach A for positional analysis —")
    print("   the mapping is per-word, and positional analysis counts")
    print("   position within each word/token. Approach B diverges only")
    print("   if we use a DIFFERENT mapping strategy.)")
    print()

    # === MONTE CARLO ===
    print("=" * 50)
    print("MONTE CARLO — random sequences using LATIN frequencies")
    print("=" * 50)

    chain_lengths = [len(c) for c in chains_A if len(c) > 1]
    mc_result = monte_carlo_positional(
        op_freq_A, chain_lengths, VMS_POSITIONAL_CONSTRAINTS, trials=10000
    )
    print(f"  Trials: {mc_result['trials']}")
    print(f"  Passes (all constraints): {mc_result['passes']}")
    print(f"  Pass rate: {mc_result['pass_rate'] * 100:.3f}%")
    print()

    # === VERDICT ===
    print("=" * 70)
    print("VERDICT")
    print("=" * 70)
    print()

    if diffs_A >= 4:
        print("  RESULT: Latin FAILS the positional test.")
        print(f"  {diffs_A} of {matches_A + diffs_A} constraints show DIFFERENT patterns in Latin.")
        print("  The VMS positional structure is NOT explained by Latin language structure.")
        print("  → STRONG evidence that VMS constraints are shorthand-specific.")
        print("  → Proceed with Phase 2 folio analysis with HIGH confidence.")
        print("  → RECOMMENDATION: PROCEED")
    elif diffs_A >= 2:
        print("  RESULT: Latin PARTIALLY matches the positional test.")
        print(f"  {diffs_A} of {matches_A + diffs_A} constraints differ.")
        print("  Some constraints may be language-universal; others are shorthand-specific.")
        print("  → The differing constraints are the real discriminators.")
        print("  → RECOMMENDATION: PROCEED with caution, weight discriminating constraints higher")
    else:
        print("  RESULT: Latin PASSES the positional test.")
        print(f"  Only {diffs_A} of {matches_A + diffs_A} constraints differ.")
        print("  VMS positional structure may reflect language universals, not shorthand.")
        print("  → Need additional discriminators before proceeding.")
        print("  → RECOMMENDATION: REFINE protocol before scaling Phase 2")

    print()
    return {
        "matches": matches_A,
        "differences": diffs_A,
        "results": results_A,
        "monte_carlo": mc_result,
    }


if __name__ == "__main__":
    result = run_grounding_test()

    # Save report
    outpath = "90b476bbb719bc2bfa7e476d.txt"
    import io, sys
    old_stdout = sys.stdout
    sys.stdout = buffer = io.StringIO()
    run_grounding_test()
    sys.stdout = old_stdout
    with open(outpath, 'w') as f:
        f.write(buffer.getvalue())
    print(f"\nSaved: {outpath}")
