#!/usr/bin/env python3
"""SlopFilter pass on the four falsification-target inputs Ed greenlit 2026-04-26.

Targets:
  1. voynichmanuscript.online (Vigslist / Nuvira) — site-capture summary
  2. voynich_structural_analysis_upgraded.pdf — Downloads
  3. The_Voynich_Manuscript_as_a_Womens_Pharm.pdf — Downloads
  4. ../../../resources/tools/provenance/index.html#s-0d5d6de4c2fd405b given for falsification/ — composite codebase + docs
  5. (RETROACTIVE) AC literature survey — surfaced from this session for re-vetting

Uses the same local deterministic rubric as ~/hail/audit/scripts/corpus_slopfilter.py
+ ~/hail/audit/2026-04-26-vms-filter/local_score.py. MODE_1 local. No LLM.
"""
from __future__ import annotations

import json
import re
from datetime import datetime
from pathlib import Path

VERDICT_VERBS = ["prove", "disprove", "shows", "demonstrates", "invalidates", "decoded", "deciphered", "solves", "solved", "complete", "definitive"]
AUTHORITY_CUES = ["experts say", "studies show", "researchers agree", "consensus", "well-established", "the literature"]
URGENCY_SIGNALS = ["urgent", "immediate", "critical", "breakthrough"]
EMOTION_SIGNALS = ["shocking", "outrageous", "terrifying", "remarkable", "unprecedented"]

CITE_PATTERNS = [
    r"\b\d{4}\b",  # year-like cites (loose)
    r"\bpp?\.\s*\d+", r"\bvol\.\s*\d+",
    r"\bDOI:?\s*10\.\d+", r"\bdoi\.org/",
    r"\bMS\.? [A-Z]", r"Pal\.lat\.\d+", r"Vat\.lat\.\d+", r"Clm \d+",
    r"BnF [A-Z][a-z]+\.\d+", r"BL [A-Z][a-z]+ \d+",
    r"https?://[^\s)]+",
    r"\(\d{4}\)",  # author (year) form
]

GHOST_FLAG_PATTERNS = {
    "RIGOROUS_WRAPPER": [
        r"\b(?:rigorous|rigorously|systematic|systematically|methodical|methodically|comprehensively|exhaustively|complete|definitive|deciphered|decoded)\b",
        r"\b(?:framework|paradigm|methodology|epistemology|ontology|protocol)\b",
    ],
    "AUTHORITY_BLEED": [
        r"\b(?:consensus|widely accepted|well[-\s]established|the literature|the field|canonical|standard|definitive)\b",
    ],
    "FORMAL_DRESS": [
        r"\bp\s*[<=]\s*0\.\d+", r"\bchi[-\s]?squared?", r"\bF1\b", r"\bnull[-\s]?model",
        r"\b\d+(?:\.\d+)?%\s+(?:coverage|accuracy|confirmed)",
        r"\bblind[-\s]?test", r"\badversarial",
    ],
    "ADVERSARIAL_LOOP": [
        r"\b(?:but (?:then|actually)|however, (?:upon|on) (?:reflection|reconsideration))\b",
        r"\bcounter[-\s]?example", r"\bobjection.*answered",
    ],
    "CLOSED_LOOP": [
        r"\b(?:as (?:I|we) (?:said|noted|established|demonstrated)|as (?:previously|earlier) (?:noted|stated|discussed))\b",
        r"\binternal[-\s]?validation", r"\bself[-\s]?validating",
    ],
    "NARRATIVE_PRESSURE": [
        r"\b(?:persecut|witch[-\s]?hunt|inquisition|secret(?:s|ly)|forbidden|hidden truth)\b",
        r"\b(?:conspiracy|cover[-\s]?up|silenced|suppressed)\b",
    ],
}


def count_substrings(text_lower: str, needles: list[str]) -> list[str]:
    return [n for n in needles if n in text_lower]


def count_citations(text: str) -> int:
    n = 0
    for p in CITE_PATTERNS:
        n += len(re.findall(p, text))
    return n


def detect_ghost_flags(text: str, size_bytes: int) -> tuple[dict, list]:
    counts = {}
    detected = []
    for flag, patterns in GHOST_FLAG_PATTERNS.items():
        n = 0
        for p in patterns:
            n += len(re.findall(p, text, re.IGNORECASE))
        counts[flag] = n
        threshold = max(2, size_bytes // 4000)
        if n >= threshold:
            detected.append(flag)
    return counts, detected


def derive_score(signal_count: int, citation_count: int, size_bytes: int, ghost_flags: list) -> tuple[str, int]:
    score = 80
    score -= signal_count * 8
    kb = max(1, size_bytes // 1024)
    cite_per_kb = citation_count / kb
    if cite_per_kb >= 2:
        score += 10
    elif cite_per_kb >= 1:
        score += 5
    elif citation_count == 0:
        score -= 10
    score -= len(ghost_flags) * 5
    score = max(0, min(100, score))
    if score >= 75:
        label = "CLEAN"
    elif score >= 50:
        label = "MARGINAL"
    elif score >= 25:
        label = "CONTAMINATED"
    else:
        label = "GHOST"
    return label, score


def score_file(path: Path, label_override: str = None) -> dict:
    text = path.read_text(encoding="utf-8", errors="replace")
    size = len(text.encode("utf-8"))
    t_lower = text.lower()
    verdict = count_substrings(t_lower, VERDICT_VERBS)
    auth = count_substrings(t_lower, AUTHORITY_CUES)
    urg = count_substrings(t_lower, URGENCY_SIGNALS)
    emo = count_substrings(t_lower, EMOTION_SIGNALS)
    sig = len(verdict) + len(auth) + len(urg) + len(emo)
    cites = count_citations(text)
    flag_counts, flags_detected = detect_ghost_flags(text, size)
    label, score = derive_score(sig, cites, size, flags_detected)
    return {
        "path": str(path),
        "display_name": label_override or path.name,
        "size_bytes": size,
        "label": label,
        "score": score,
        "citation_count": cites,
        "citation_per_kb": round(cites / max(1, size // 1024), 2),
        "signal_count": sig,
        "verdict_verbs": verdict,
        "authority_cues": auth,
        "urgency_signals": urg,
        "emotion_signals": emo,
        "ghost_flag_counts": flag_counts,
        "ghost_flags_detected": flags_detected,
        "ts": datetime.now().isoformat(timespec="seconds"),
    }


# Inputs
TARGETS = [
    ("../../../resources/tools/provenance/index.html#s-4b7c7da4fc785acd",
     "voynichmanuscript.online (Vigslist/Nuvira) [SITE-CAPTURE]"),
    ("../../../resources/tools/provenance/index.html#s-381f36e45a8094bc",
     "voynich_structural_analysis_upgraded.pdf [DOWNLOADS]"),
    ("../../../resources/tools/provenance/index.html#s-4216898443f5ab29",
     "The_Voynich_Manuscript_as_a_Womens_Pharm.pdf [DOWNLOADS]"),
    # falsification dir composite — score the FAQ + paleographic spec + bibliography as the most claim-bearing docs
    ("../../../resources/tools/provenance/index.html#s-a651444517f82bec",
     "Works given for falsification — FAQ.md [retained archive]"),
    ("../../../resources/tools/provenance/index.html#s-892db8c0020663ee",
     "Works given for falsification — PALEOGRAPHIC_TRANSCRIPTION_SPEC.md [retained archive]"),
    ("../../../resources/tools/provenance/index.html#s-a597d2be7d4b0599",
     "Works given for falsification — BIBLIOGRAPHY.md [retained archive]"),
    ("../../../resources/tools/provenance/index.html#s-aa069f0e854d639d",
     "Works given for falsification — PHASE1_REDO_IMAGE_ANALYSIS.md [retained archive]"),
    ("../../../resources/tools/provenance/index.html#s-778eabdc32f9ebb7",
     "Works given for falsification — LATIN_PHARMACEUTICAL_VOCABULARY.md [retained archive]"),
    # Retroactive: AC literature survey
    ("../../../resources/tools/provenance/index.html#s-301f58d9580f24e0",
     "AC RELAY 2026-04-26 — Voynich scholarship survey [RETROACTIVE]"),
]


def main():
    out_dir = Path("../../../resources/tools/provenance/index.html#s-dde783be1dc45bf7")
    out_jsonl = out_dir / "results.jsonl"
    rows = []
    print(f"{'LABEL':14s} {'SCORE':>5} {'CITES':>5} {'C/KB':>6} {'SIG':>4} {'FLAGS':35s} TARGET")
    print("-" * 130)
    for path_str, display in TARGETS:
        p = Path(path_str)
        if not p.exists():
            print(f"  MISSING: {path_str}")
            continue
        r = score_file(p, label_override=display)
        rows.append(r)
        flags = ",".join(r["ghost_flags_detected"]) or "-"
        print(f"{r['label']:14s} {r['score']:>5} {r['citation_count']:>5} {r['citation_per_kb']:>6} {r['signal_count']:>4} {flags:35s} {r['display_name'][:75]}")
    with out_jsonl.open("w") as fh:
        for r in rows:
            fh.write(json.dumps(r) + "\n")
    print(f"\nResults: {out_jsonl}")


if __name__ == "__main__":
    main()

# Section 8 follow-on: Greshko 2025 full paper now on disk
