import json
import re
import sys
import os

sys.path.insert(0, os.path.dirname(__file__))
from new_content import NEW_CONTENT

BASE = "/tmp/claude-0/-home-danvics-docker-quiz/c1e0577a-e42c-4a3d-b1ea-3edd61103a4e/scratchpad/prose"
IN_PATH = os.path.join(BASE, "batch-03.json")
OUT_PATH = os.path.join(BASE, "batch-03.done.json")

with open(IN_PATH, "r", encoding="utf-8") as f:
    data = json.load(f)

print(f"Total entries: {len(data)}")
print(f"Entries with new content mapped: {len(NEW_CONTENT)}")

missing = []
for entry in data:
    sid = entry["section_id"]
    if sid not in NEW_CONTENT:
        missing.append((entry["article_id"], sid))

if missing:
    print("MISSING mappings for:", missing)
    sys.exit(1)

num_re = re.compile(r"\d+(?:\.\d+)?")
marker_re = re.compile(r"\[\[(\d+)\|")

results = []
fail = False
for entry in data:
    sid = entry["section_id"]
    old_content = entry["content"]
    new_content = NEW_CONTENT[sid]

    old_nums = num_re.findall(old_content)
    new_nums = num_re.findall(new_content)

    old_markers = marker_re.findall(old_content)
    new_markers = marker_re.findall(new_content)

    ratio = len(new_content) / len(old_content)

    ok = True
    problems = []
    if sorted(old_nums) != sorted(new_nums):
        ok = False
        problems.append(f"NUMBER MISMATCH old={old_nums} new={new_nums}")
    if old_markers != new_markers:
        ok = False
        problems.append(f"MARKER MISMATCH old={old_markers} new={new_markers}")
    if not (0.85 <= ratio <= 1.25):
        ok = False
        problems.append(f"LENGTH RATIO OUT OF BAND: {ratio:.3f} (old_len={len(old_content)}, new_len={len(new_content)})")

    if not ok:
        fail = True
        print(f"FAIL article_id={entry['article_id']} section_id={sid} title={entry.get('article_title')} / {entry.get('section_title')}")
        for p in problems:
            print("   ", p)
    else:
        print(f"OK   article_id={entry['article_id']} section_id={sid[:8]} ratio={ratio:.3f}")

    new_entry = dict(entry)
    new_entry["content"] = new_content
    results.append(new_entry)

with open(OUT_PATH, "w", encoding="utf-8") as f:
    json.dump(results, f, ensure_ascii=False, indent=2)

print()
if fail:
    print("VERIFICATION FAILED - see FAIL lines above")
    sys.exit(1)
else:
    print(f"VERIFICATION PASSED for all {len(results)} entries")
    print(f"Output written to: {OUT_PATH}")
