import json, re, sys, importlib.util
from collections import Counter

BASE = '/tmp/claude-0/-home-danvics-docker-quiz/c1e0577a-e42c-4a3d-b1ea-3edd61103a4e/scratchpad/mdm'
SRC = f'{BASE}/mdm-01.json'

ALLOWED = ["Clinical paths", "Diagnosis", "Management", "Prognosis and outcome"]

def strip_list_markers(text):
    return re.sub(r'(?m)^\s*\d+[.)]\s', '', text)

def markers(text):
    return Counter(re.findall(r'\[\[(\d+)\|', text))

def numbers(text):
    return Counter(re.findall(r'\d+(?:\.\d+)?', strip_list_markers(text)))

def load_part_modules(names):
    parts = {}
    for name in names:
        spec = importlib.util.spec_from_file_location(name, f'{BASE}/{name}.py')
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        parts.update(mod.PARTS)
    return parts

def check(article_ids, part_files):
    data = {d['article_id']: d for d in json.load(open(SRC))}
    parts = load_part_modules(part_files)
    ok = True
    for aid in article_ids:
        orig = data[aid]
        before_text = "\n".join(s['content'] for s in orig['sections'])
        if aid not in parts:
            print(f"[{aid}] MISSING from parts"); ok = False; continue
        new_secs = parts[aid]
        titles = [s['title'] for s in new_secs]
        after_text = "\n".join(s['content'] for s in new_secs)

        # title checks
        if len(set(titles)) != len(titles):
            print(f"[{aid}] DUPLICATE titles: {titles}"); ok = False
        core = [t for t in titles if t != "Prognosis and outcome"]
        if core != ["Clinical paths", "Diagnosis", "Management"]:
            print(f"[{aid}] BAD core order/set: {titles}"); ok = False
        for t in titles:
            if t not in ALLOWED:
                print(f"[{aid}] BAD title: {t}"); ok = False
        # prognosis must be last if present
        if "Prognosis and outcome" in titles and titles[-1] != "Prognosis and outcome":
            print(f"[{aid}] Prognosis not last: {titles}"); ok = False

        m_before, m_after = markers(before_text), markers(after_text)
        if m_before != m_after:
            print(f"[{aid}] MARKER MISMATCH before={m_before} after={m_after}"); ok = False

        n_before, n_after = numbers(before_text), numbers(after_text)
        if n_before != n_after:
            print(f"[{aid}] NUMBER MISMATCH")
            print("   before:", n_before)
            print("   after: ", n_after)
            ok = False

        lb, la = len(before_text), len(after_text)
        ratio = la/lb if lb else 1
        if not (0.8 <= ratio <= 1.3):
            print(f"[{aid}] LENGTH RATIO {ratio:.2f} (before={lb} after={la})"); ok = False
    if ok:
        print(f"ALL OK for {len(article_ids)} articles: {article_ids}")
    return ok

if __name__ == '__main__':
    pass
