#!/usr/bin/env python3
"""Spot check stories and swap data across all week generators."""

import re
import os
from pathlib import Path

ELA_ROOT = Path(os.path.expanduser("~/Home_School/2nd_Grade/English_Language_Arts"))

def extract_stories(filepath):
    """Extract STORY variables from a week generator file."""
    source = filepath.read_text()
    stories = []
    
    # Find multi-line string assignments like MONDAY_STORY = (
    pattern = r'(MONDAY_STORY|THURSDAY_STORY|FRIDAY_REVIEW_STORY)\s*=\s*\(\s*"((?:[^"\\]|\\.)*)"\s*\)'
    for match in re.finditer(pattern, source, re.DOTALL):
        name = match.group(1)
        text = match.group(2).replace('\\n', '\n').replace('<strong>', '**').replace('</strong>', '**')
        words = re.findall(r'\b(\w+)\b', re.sub(r'<[^>]+>', '', text))
        stories.append((name, text, len(words)))
    
    return stories

# Check all week generators
weeks_checked = []
for week_dir in sorted(ELA_ROOT.glob("Week_*")):
    for f in week_dir.glob("generate_week*.py"):
        if "CORRUPTED" not in f.name and "backup" not in f.name and "_new" not in f.name:
            stories = extract_stories(f)
            if stories:
                week_num = f.parent.name
                weeks_checked.append((week_num, stories))

# Print summary
print("STORY AUDIT SUMMARY")
print("=" * 70)

for week, stories in weeks_checked:
    for name, text, word_count in stories:
        display = text.replace('\n', ' ')[:150] + "..."
        print(f"\n{week} - {name} ({word_count} words)")
        print(f"  {display}")

# Also check swap data
print("\n" + "=" * 70)
print("SWAP DATA SPOT CHECK")
print("=" * 70)

for week_dir in sorted(ELA_ROOT.glob("Week_*")):
    for f in week_dir.glob("generate_week*.py"):
        if "CORRUPTED" in f.name or "backup" in f.name or "_new" in f.name:
            continue
        
        source = f.read_text()
        week_num = f.parent.name
        
        for day in ['TUESDAY_SWAP_DATA', 'THURSDAY_SWAP_DATA']:
            match = re.search(rf'{day}\s*=\s*\[(.*?)\]', source, re.DOTALL)
            if match:
                block = match.group(1)
                sentences = re.findall(r'"([^"]*)"', block)
                if sentences:
                    print(f"\n{week_num} - {day}:")
                    for s in sentences[:4]:
                        plain = re.sub(r'<[^>]+>', '', s)
                        print(f"  \"{plain[:100]}\"")
                        if re.search(r'\b[aA]\s+insect\b', s):
                            print(f"  ⚠️ 'a insect' error!")
                        if re.search(r'\b[aA]\s+octopus\b', s):
                            print(f"  ⚠️ 'a octopus' error!")
                        if re.search(r'\b[aA]\s+elephant\b', s):
                            print(f"  ⚠️ 'a elephant' error!")