#!/usr/bin/env python3
"""Fixed sentences, banned words, tense, person, dialogue, card, length and form checks: python check_story.py raw/<tool>.md"""
import re, sys
text = open(sys.argv[1], encoding="utf-8").read()
ans = text.split("\n## Answer", 1)[1] if "\n## Answer" in text else text
a = ans.replace(" ", " ").replace("–", "-").replace("—", "-").replace("’", "'").replace("‘", "'").strip()
lines = [l for l in a.split("\n") if l.strip()]
title = lines[0].strip("# *_").strip() if lines else ""
body = "\n".join(lines[1:]) if len(lines) > 1 else a
words = len(re.findall(r"\S+", body))
first_ok = body.lstrip().startswith("The book was due on the ninth of June, 1995.")
last_ok = body.rstrip().rstrip('"”*_').endswith("I keep the receipt.")
low = body.lower()
banned = ["suddenly","realise","realize","realised","realized","breath","breathe","breathing","heart","heartbeat","silence","silent","shattered","tears","tearful","whisper","whispered","whispers","echo","echoes","echoed","somehow"]
used = {w: len(re.findall(r"\b" + w + r"\b", low)) for w in banned}
used = {w: n for w, n in used.items() if n}
dialogue = re.findall(r"[\"“]([^\"”]{2,})[\"”]", body)
dwords = sum(len(re.findall(r"\S+", d)) for d in dialogue)
nodialog = re.sub(r"[\"“][^\"”]*[\"”]", " ", body)
past = len(re.findall(r"\b(i|she|he|it|they|we) (was|were|had|said|asked|looked|walked|took|put|opened|held|saw|went|came|turned|nodded|smiled)\b", nodialog, re.I))
third = len(re.findall(r"\b(he|his|him|they|them|their)\b", nodialog, re.I))
card = len(re.findall(r"library card|the card|her card|my card|a card|card\b", low))
twist = bool(re.search(r"\b(ghost|dead all along|i died|had died|a dream|wake up|woke up|it was all|never really|i am not real)\b", low))
moral = bool(re.search(r"(i understand now|i realise now|i realize now|it was never about|that is what|that's what .* means|the point was|i know now that)", low))
notes = bool(re.search(r"(would you like|let me know|note:|word count|\(\d{3} words\)|i've kept|i have kept)", low))
preface = bool(re.search(r"^(here('s| is)|sure|certainly|below is|of course)", lines[0].lower())) if lines else False
headings = bool(re.search(r"^\s*#{1,6}\s|^\s*\*\*[^*]{3,60}\*\*\s*$", body, re.M))
print(f"title: {title[:70]!r}")
print(f"words (below title): {words}  ->  {'in window' if 700 <= words <= 800 else ('SHORT' if words < 700 else 'LONG')}")
print(f"first sentence exact: {first_ok} | last sentence exact: {last_ok}")
print(f"banned words used: {used}")
print(f"dialogue words: {dwords} (limit 80) in {len(dialogue)} quoted spans")
print(f"past-tense narration hits outside dialogue: {past} | third-person pronouns (he/they) outside dialogue: {third}")
print(f"'card' mentions: {card}")
print(f"twist/ghost/dream signal: {twist} | moral paragraph signal: {moral}")
print(f"preface: {preface} | notes/offer: {notes} | headings: {headings}")
