#!/usr/bin/env python3
"""Week 1 Generator - Short Vowels Review & Sentence Basics

Phonics: Short vowels (a, e, i, o, u)
Spelling: 12 words, all 6+ letters
Grammar: What is a sentence? Capital letters + periods
"""

import os
import random
from weasyprint import HTML

WEEK = os.path.expanduser("~/Home_School/2nd_Grade/English_Language_Arts/Week_01")

# 12 Words - exactly 12, all 6+ letters
WORDS = [
    ("basket", "short a", "a container for holding things"),
    ("garden", "short a", "a place where plants and flowers grow"),
    ("animal", "short a", "a living creature that can move"),
    ("elephant", "short e", "a very large animal with a long trunk"),
    ("helmet", "short e", "a hard hat worn for protection"),
    ("insect", "short i", "a small creature with six legs"),
    ("kitten", "short i", "a young cat"),
    ("winter", "short i", "the coldest season of the year"),
    ("octopus", "short o", "a sea creature with eight arms"),
    ("doctor", "short o", "someone who helps sick people"),
    ("umbrella", "short u", "something used to keep rain off you"),
    ("bubble", "short u", "a thin round ball of air or soap"),
]

WORD_NAMES = [w[0] for w in WORDS]
SHORT_A = [w[0] for w in WORDS if w[1] == "short a"]
SHORT_E = [w[0] for w in WORDS if w[1] == "short e"]
SHORT_I = [w[0] for w in WORDS if w[1] == "short i"]
SHORT_O = [w[0] for w in WORDS if w[1] == "short o"]
SHORT_U = [w[0] for w in WORDS if w[1] == "short u"]

CSS = """
@page { size: letter; margin: 0.7in 0.85in; }
body { font-family: 'Comic Neue', 'Comic Sans MS', sans-serif; color: #222; background: #fff; margin: 0; line-height: 1.4; }
p { orphans: 3; widows: 3; }
header { display: flex; justify-content: space-between; align-items: baseline; border-bottom: 3px solid #26A69A; padding-bottom: 6px; margin-bottom: 12px; }
header h1 { font-size: 17px; margin: 0; color: #26A69A; }
header .subtitle { font-size: 12px; color: #666; }
header .name-line { font-size: 12px; }
h2 { font-size: 14px; color: #26A69A; margin: 14px 0 4px 0; border-bottom: 2px solid #B2DFDB; padding-bottom: 2px; break-after: avoid; }
h2.coral { color: #FF7043; border-bottom-color: #FFAB91; }
.note { background: #E8F5E9; border-left: 4px solid #26A69A; padding: 6px 10px; border-radius: 4px; font-size: 11.5px; margin: 4px 0 10px 0; color: #333; break-inside: avoid; }
.activity { break-inside: avoid; page-break-inside: avoid; }
.word-grid { width: 100%; border-collapse: separate; border-spacing: 3px; }
.word-grid td { vertical-align: top; }
.word-card { border: 1.5px solid #B2DFDB; border-radius: 6px; padding: 4px 6px; background: #FAFAFA; break-inside: avoid; }
.word-card .word { font-size: 12px; font-weight: bold; color: #26A69A; margin-bottom: 1px; }
.word-card .def { font-size: 9px; color: #555; line-height: 1.15; }
.write-line {
    position: relative; height: 18px; margin: 1px 0; width: 100%;
}
tr { break-inside: avoid; }
.fb-item { background: #E0F2F1; border: 1.5px solid #80CBC4; border-radius: 6px; padding: 6px 8px; margin-bottom: 6px; font-size: 12px; break-inside: avoid; page-break-inside: avoid; }
.fb-item p { margin: 0 0 4px 0; }
.word-bank { background: #FFF3E0; border: 2px dashed #FFB74D; border-radius: 8px; padding: 8px 12px; margin: 8px 0; }
.word-bank-label { font-size: 11px; font-weight: bold; color: #FF7043; margin-bottom: 4px; }
.word-bank-words { display: flex; flex-wrap: wrap; gap: 6px; }
.word-bank-words span { background: white; border: 1px solid #FFB74D; border-radius: 4px; padding: 2px 8px; font-size: 11px; }
.ws-grid { display: inline-block; font-family: monospace; font-size: 12px; letter-spacing: 2px; line-height: 1.4; background: #F5F5F5; border: 2px solid #B2DFDB; border-radius: 6px; padding: 6px 8px; text-align: left; }
.ws-table { border-collapse: collapse; margin: 8px auto; background: #F5F5F5; border: 2px solid #B2DFDB; break-inside: avoid; page-break-inside: avoid; }
.ws-table td { width: 28px; height: 28px; text-align: center; vertical-align: middle; font-family: monospace; font-size: 14px; font-weight: bold; border: 1px solid #B2DFDB; color: #333; }
.ws-words { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 8px 0; justify-content: center; }
.ws-words span { font-size: 11px; background: #E0F2F1; border: 1px solid #80CBC4; border-radius: 3px; padding: 2px 6px; }
.mystery-box { background: #FFF8E1; border: 2px solid #FFD54F; border-radius: 8px; padding: 10px; margin: 8px 0; break-inside: avoid; }
.mystery-box .title { font-size: 13px; font-weight: bold; color: #FF7043; margin-bottom: 6px; }
.mystery-box li { font-size: 11px; margin: 3px 0; }
.write-line {
    position: relative; height: 22px; margin: 2px 0; width: 100%;
}
.write-line-sky {
    position: absolute; left: 0; right: 0; top: 0;
    border-top: 0.6pt solid rgb(0,0,255);
}
.write-line-ground {
    position: absolute; left: 0; right: 0; bottom: 0;
    border-bottom: 0.6pt solid rgb(0,0,255);
}
.write-line-fence {
    position: absolute; left: 0; right: 0; bottom: 12px;
    border-bottom: 0.4pt dashed rgb(255,0,0);
}
.copy-line {
    position: relative; height: 22px; margin: 2px 0; width: 100%;
}
.copy-line-sky {
    position: absolute; left: 0; right: 0; top: 0;
    border-top: 0.6pt solid rgb(0,0,255);
}
.copy-line-ground {
    position: absolute; left: 0; right: 0; bottom: 0;
    border-bottom: 0.6pt solid rgb(0,0,255);
}
.copy-line-fence {
    position: absolute; left: 0; right: 0; bottom: 12px;
    border-bottom: 0.4pt dashed rgb(255,0,0);
}
.story-box { background: #F3E5F5; border: 1.5px solid #CE93D8; border-radius: 8px; padding: 10px; font-size: 12px; line-height: 1.5; margin: 8px 0; break-inside: avoid; }
.test-item { display: flex; align-items: center; gap: 8px; font-size: 13px; margin: 6px 0; }
.test-item .num { font-weight: bold; color: #26A69A; min-width: 20px; }
.divider { border-top: 1px dashed #ccc; margin: 12px 0; }
"""


def header(title, subtitle=""):
    return (f'<header>'
            f'<h1>{title}</h1>'
            f'<div class="subtitle">{subtitle}</div>'
            f'<div class="name-line">Name: ________________</div>'
            f'</header>')

def sectitle(text, color="teal"):
    cls = "coral" if color == "coral" else ""
    return f'<h2 class="{cls}">{text}</h2>'

def secnote(text):
    return f'<div class="note">{text}</div>'

def word_bank(words, seed=99):
    rnd = random.Random(seed)
    shuffled = list(words)
    rnd.shuffle(shuffled)
    word_spans = "".join(f"<span>{w}</span>" for w in shuffled)
    return (f'<div class="word-bank">'
            f'<div class="word-bank-label">Word Bank</div>'
            f'<div class="word-bank-words">{word_spans}</div>'
            f'</div>')

def fill_blank_with_line(sentence):
    return (f'<div class="fb-item">'
            f'<p>{sentence}</p>'
            f'{write_line()}'
            f'</div>')

def word_search(word_list, rows=14, cols=14, seed=42):
    rnd = random.Random(seed)
    grid = [[""] * cols for _ in range(rows)]
    directions = [(0,1),(1,0),(1,1),(1,-1),(0,-1),(-1,0),(-1,-1),(-1,1)]
    for word in word_list:
        upper_word = word.upper()
        placed = False
        attempts = 0
        while not placed and attempts < 500:
            attempts += 1
            dr, dc = rnd.choice(directions)
            sr, sc = rnd.randint(0, rows-1), rnd.randint(0, cols-1)
            er, ec = sr + dr*(len(upper_word)-1), sc + dc*(len(upper_word)-1)
            if er < 0 or er >= rows or ec < 0 or ec >= cols:
                continue
            ok = True
            for i, ch in enumerate(upper_word):
                r, c = sr + dr*i, sc + dc*i
                if grid[r][c] and grid[r][c] != ch:
                    ok = False; break
            if ok:
                for i, ch in enumerate(upper_word):
                    grid[sr + dr*i][sc + dc*i] = ch
                placed = True
    letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for r in range(rows):
        for c in range(cols):
            if not grid[r][c]:
                grid[r][c] = rnd.choice(letters)
    cell_html = ""
    for row in grid:
        cell_html += "<tr>"
        for ch in row:
            cell_html += f'<td>{ch}</td>'
        cell_html += "</tr>"
    word_list_html = "".join(f"<span>{w.upper()}</span>" for w in word_list)
    return (f'<div class="ws-words">{word_list_html}</div>'
            f'<table class="ws-table"><tbody>{cell_html}</tbody></table>')

def remember_box(title, content):
    return (f'<div class="story-box" style="background:#E8F5E9;border-color:#A5D6A7;">'
            f'<strong style="color:#2E7D32;">{title}</strong><br>'
            f'{content}'
            f'</div>')

def write_line():
    return '<div class="write-line"><div class="write-line-sky"></div><div class="write-line-fence"></div><div class="write-line-ground"></div></div>'

def copy_line():
    return '<div class="copy-line"><div class="copy-line-sky"></div><div class="copy-line-fence"></div><div class="copy-line-ground"></div></div>'

def page_break():
    return '<div style="page-break-after:always;"></div>'


# =====================================================================
# MONDAY - Learn It (5 pages)
# =====================================================================

def generate_monday():
    day_dir = os.path.join(WEEK, "Monday")
    os.makedirs(day_dir, exist_ok=True)

    # Word cards — table layout: 6 rows, 2 columns
    card_items = '<table class="word-grid">'
    for i in range(0, len(WORDS), 2):
        card_items += '<tr>'
        for j in range(i, min(i+2, len(WORDS))):
            word, vowel, defn = WORDS[j]
            card_items += (f'<td><div class="word-card">'
                           f'<div class="word">{word}</div>'
                           f'<div class="def">{defn}</div>'
                           f'{write_line()}'
                           f'</div></td>')
        card_items += '</tr>'
    card_items += '</table>'

    # Vowel sort - shuffled word bank + blank columns to fill in
    sort_words = list(WORD_NAMES)
    random.Random(42).shuffle(sort_words)
    sort_word_bank = word_bank(sort_words, seed=42)

    sort_col_html = ""
    for vlabel in ["Short A", "Short E", "Short I", "Short O", "Short U"]:
        lines = "".join(write_line() for _ in range(3))
        sort_col_html += (f'<td style="width:20%;text-align:center;vertical-align:top;border:1.5px solid #B2DFDB;border-radius:6px;padding:6px;background:#FAFAFA;">'
                          f'<div style="font-weight:bold;font-size:11px;color:#26A69A;margin-bottom:6px;">{vlabel}</div>'
                          f'{lines}</td>')

    sort_html = (f'<div class="activity">{sort_word_bank}'
                 f'<table style="width:100%;border-collapse:separate;border-spacing:3px;">'
                 f'<tr>{sort_col_html}</tr></table></div>')

    # Grammar content
    grammar_text = ("A sentence is a group of words that makes a complete thought.<br>"
                    "Every sentence starts with a CAPITAL LETTER and ends with a PERIOD (.), "
                    "QUESTION MARK (?), or EXCLAMATION POINT (!).<br><br>"
                    "Example: <strong>The kitten is playing.</strong> &check;<br>"
                    "Not a sentence: <strong>kitten playing.</strong> &times;")

    # Copy practice — 24px words with taller writing lines
    copy_items = ""
    for i, (word, _, _) in enumerate(WORDS):
        copy_items += (f'<div style="display:flex;align-items:center;gap:12px;margin:10px 0;">'
                       f'<span style="font-weight:bold;font-size:24px;min-width:100px;color:#26A69A;line-height:34px;">{word}</span>'
                       f'<div style="flex:1;position:relative;height:34px;margin:2px 0;width:100%;">'
                       f'<div style="position:absolute;left:0;right:0;top:0;border-top:0.6pt solid rgb(0,0,255);"></div>'
                       f'<div style="position:absolute;left:0;right:0;bottom:18px;border-bottom:0.4pt dashed rgb(255,0,0);"></div>'
                       f'<div style="position:absolute;left:0;right:0;bottom:0;border-bottom:0.6pt solid rgb(0,0,255);"></div>'
                       f'</div></div>')

    # Sentence writing (first 4 words)
    sentence_words = WORDS[:4]
    sentence_items = ""
    for word, _, _ in sentence_words:
        sentence_items += (f'<div style="margin:6px 0;">'
                           f'<span style="font-size:11px;font-weight:bold;color:#26A69A;">{word}:</span>{write_line()}</div>')

    # Spelling story — Birthday party at home
    story_text = (
        'Today is my birthday and I got a <strong>kitten</strong> in a <strong>basket</strong>! '
        'My mom put a tiny <strong>helmet</strong> on a toy <strong>elephant</strong> for a photo. '
        'The vet <strong>doctor</strong> came to check every <strong>animal</strong> at the party. '
        'I found an <strong>insect</strong> on the cake and blew out a candle <strong>bubble</strong>. '
        'Even though it was <strong>winter</strong>, we opened our <strong>umbrella</strong> for a surprise <strong>octopus</strong> piñata! '
        'It was the best birthday ever!'
    )

    # Fill in the blank
    fill_data = [
        ("The ____ helps sick people feel better.", "doctor"),
        ("I blew a small ____ in the air.", "bubble"),
        ("She put on her ____ before riding her bike.", "helmet"),
        ("The ____ has eight arms.", "octopus"),
    ]
    fill_answers = [s[1] for s in fill_data]
    fill_bank = word_bank(fill_answers, seed=210)
    fill_items = "".join(fill_blank_with_line(s) for s, _ in fill_data)

    # Opposite match-up
    opposite_pairs = [
        ("winter", "summer"),
        ("kitten", "adult cat"),
    ]
    opposite_html = ""
    for word, opp in opposite_pairs:
        opposite_html += (f'<div style="margin:4px 0;font-size:12px;">'
                          f'{word} (opposite: {opp})<br>{write_line()}</div>')

    html = f"""<!DOCTYPE html>
    <html><head><meta charset="utf-8"><style>{CSS}</style></head><body>

    <div>
    {header("English Language Arts", "Week 1, Monday -- Short Vowels & Sentences")}
    {sectitle("Here's What We're Learning")}
    {secnote("Short vowels are the sounds a, e, i, o, u make in one-syllable words. Read each word carefully -- the vowel says its SHORT sound.")}
    <ul style="font-size:12px;margin:4px 0 8px 0;">
    <li>Short <strong>a</strong> as in <em>basket</em> /ba/</li>
    <li>Short <strong>e</strong> as in <em>elephant</em> /e/</li>
    <li>Short <strong>i</strong> as in <em>kitten</em> /i/</li>
    <li>Short <strong>o</strong> as in <strong>doctor</strong> /o/</li>
    <li>Short <strong>u</strong> as in <strong>bubble</strong> /u/</li>
    </ul>
    {secnote("Grammar: A sentence is a group of words that makes a complete thought. It starts with a capital letter and ends with punctuation.")}
    {sectitle("Word Cards")}
    {secnote("Read each word. Notice the short vowel sound.")}
    <div class="word-grid">{card_items}</div>
    </div>
    {page_break()}

    <div>
    {sectitle("Spelling Story")}
    {secnote("Read the story. Circle each spelling word as you find it.")}
    <div class="story-box">{story_text}</div>
    {sectitle("Grammar: What Is a Sentence?")}
    {secnote(grammar_text)}
    {sectitle("Practice: Capital Letters & Periods")}
    {secnote("Add capital letters and periods to these sentences.")}
    <div style="font-size:12px;margin:6px 0;">
    <div style="margin:4px 0;">the kitten plays outside.{write_line()}</div>
    <div style="margin:4px 0;">i see a big elephant{write_line()}</div>
    <div style="margin:4px 0;">the doctor helps the kitten{write_line()}</div>
    </div>
    </div>

    <div>
    {sectitle("Short Vowel Sort")}
    {secnote("Sort each word into the correct vowel column.")}
    {sort_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Copy Practice")}
    {secnote("Read each word carefully, then copy it neatly on the line.")}
    {copy_items}
    </div>
    {page_break()}

    <div>
    {sectitle("Fill in the Blank")}
    {secnote("Choose a word from the word bank to complete each sentence.")}
    {fill_bank}
    {fill_items}
    {sectitle("Opposite Match-Up")}
    {secnote("Write the opposite of each word.")}
    {opposite_html}
    {sectitle("Sentence Writing")}
    {secnote("Write a complete sentence using each word. Remember: capital letter and period!")}
    {sentence_items}
    </div>

    </body></html>"""

    HTML(string=html).write_pdf(os.path.join(day_dir, "Week01_Monday_Short_Vowels.pdf"))
    print("[ok] Monday generated")


# =====================================================================
# TUESDAY - Practice It (3 pages)
# =====================================================================

def generate_tuesday():
    day_dir = os.path.join(WEEK, "Tuesday")
    os.makedirs(day_dir, exist_ok=True)

    # 1. Word Scramble — 12 scrambled words, 2-column table
    scramble_rows = ""
    for i in range(0, len(WORDS), 2):
        scramble_rows += '<tr>'
        for j in range(i, min(i+2, len(WORDS))):
            word, vowel, _ = WORDS[j]
            scrambled = list(word)
            random.Random(hash(word) % 1000).shuffle(scrambled)
            if "".join(scrambled) == word:
                scrambled[0], scrambled[-1] = scrambled[-1], scrambled[0]
            scramble_rows += (f'<td style="padding:4px 8px;vertical-align:top;">'
                             f'<span style="font-family:monospace;font-size:16px;font-weight:bold;color:#FF7043;letter-spacing:2px;">'
                             f'{" ".join(scrambled)}</span>'
                             f'<div style="margin-top:4px;"><div class="write-line"><div class="write-line-sky"></div><div class="write-line-fence"></div><div class="write-line-ground"></div></div></div>'
                             f'</td>')
        scramble_rows += '</tr>'
    scramble_items = f'<table style="width:100%;border-collapse:separate;border-spacing:4px;">{scramble_rows}</table>'

    # 2. Reading Comprehension passage — Animal adventure
    reading_text = (
        'The <strong>kitten</strong> sat in a <strong>basket</strong> by the <strong>garden</strong> gate. '
        'It was cold <strong>winter</strong> morning, but the kitten felt safe. '
        'A small <strong>insect</strong> flew past and the kitten pounced! '
        'Then a big <strong>elephant</strong> walked by with a <strong>helmet</strong> on its trunk. '
        'The elephant said, "I am the <strong>animal</strong> <strong>doctor</strong>. I help every creature here!" '
        'The kitten laughed and blew a soap <strong>bubble</strong> at the elephant. '
        'An <strong>octopus</strong> swam by in a water tank, waving all eight arms. '
        'It started to rain, and the kitten opened a tiny <strong>umbrella</strong>. '
        'All the <strong>animal</strong> friends laughed and played in the rain together.'
    )

    # 3. Comprehension Questions (3 questions)
    comp_questions = [
        "Where was the kitten sitting at the beginning of the story?",
        "What did the elephant say it does?",
        "What happened when the rain started?",
    ]
    comp_html = ""
    for q in comp_questions:
        comp_html += (f'<div style="margin-bottom:8px;">'
                      f'<strong style="font-size:12px;">{q}</strong><br>'
                      f'{write_line()}</div>')

    # 4. Vowel Pattern Hunt — check/circle target vowel
    hunt_words = WORDS[:12]
    hunt_html = ""
    for word, vowel, _ in hunt_words:
        # Highlight the short vowel
        vowel_letter = vowel.split()[-1][0]  # extract 'a', 'e', 'i', 'o', 'u'
        highlighted = word.replace(vowel_letter, f'<span style="color:#FF7043;font-weight:bold;">{vowel_letter}</span>')
        hunt_html += (f'<div style="display:inline-block;width:30%;margin-bottom:4px;padding:4px 8px;'
                       f'background:#E0F2F1;border-radius:4px;border-left:3px solid #26A69A;font-size:12px;">'
                      f'<span style="display:inline-block;width:14px;height:14px;border:1.5px solid #80CBC4;'
                      f'border-radius:3px;margin-right:4px;vertical-align:middle;"></span> '
                      f'{highlighted}</div>')

    # Word Swap Challenge — swaps use words of the same type so the new sentence still makes sense
    swap_data = [
        ("The <strong>kitten</strong> slept in the <strong>basket</strong>.", ("kitten", "elephant"), ("basket", "garden")),
        ("The <strong>doctor</strong> saw a big <strong>octopus</strong>.", ("doctor", "helmet"), ("octopus", "insect")),
        ("I hold my <strong>umbrella</strong> in the <strong>winter</strong>.", ("umbrella", "bubble"), ("winter", "garden")),
    ]
    swap_html = ""
    for orig, (w1_orig, w1_swap), (w2_orig, w2_swap) in swap_data:
        swap_html += (f'<div style="margin-bottom:10px;padding:6px 8px;background:#FFF3E0;border-radius:5px;border:1px solid #FFB74D;">'
                      f'<div style="font-size:10.5px;font-weight:bold;color:#FF7043;margin-bottom:3px;">Original:</div>'
                      f'<div style="font-size:12px;font-style:italic;margin-bottom:4px;">'
                      f'{orig}</div>'
                      f'<div style="font-size:10.5px;font-weight:bold;color:#FF7043;margin-bottom:3px;">Now write using <strong>{w1_swap}</strong> and <strong>{w2_swap}</strong>:</div>'
                      f'{write_line()}</div>')

    # Sentence Builder — 3 prompts
    builder_prompts = [
        ("Write a sentence about a kitten.", "kitten"),
        ("Write a sentence about the animal doctor.", "doctor"),
        ("Write a sentence about something you do in winter.", "winter"),
    ]
    builder_html = ""
    for prompt, keyword in builder_prompts:
        builder_html += (f'<div style="margin-bottom:10px;padding:6px 8px;background:#FFF3E0;border-radius:5px;border:1px solid #FFB74D;">'
                         f'<div style="font-size:11px;color:#888;font-style:italic;margin-bottom:3px;">'
                         f'{prompt} (use: <strong style="color:#26A69A;font-style:normal;">{keyword}</strong>)</div>'
                         f'{write_line()}</div>')

    # Remember This boxes
    remember1 = (
        "Short vowels say their quick, short sounds:<br>"
        "- Short <strong>a</strong> as in <em>basket</em><br>"
        "- Short <strong>e</strong> as in <em>helmet</em><br>"
        "- Short <strong>i</strong> as in <em>kitten</em><br>"
        "- Short <strong>o</strong> as in <em>doctor</em><br>"
        "- Short <strong>u</strong> as in <em>bubble</em><br><br>"
        "<strong>Try This:</strong> What short vowel do you hear in <em>insect</em>? ___"
    )
    remember3 = (
        "To sort words by vowel sound, say each word slowly. Listen for the vowel:<br><br>"
        "<strong>basket</strong> &rarr; b-a-s-ket &rarr; short <strong>a</strong><br>"
        "<strong>helmet</strong> &rarr; h-e-l-met &rarr; short <strong>e</strong><br><br>"
        "<strong>Try This:</strong> What vowel sound is in <em>winter</em>? ___"
    )

    html = f"""<!DOCTYPE html>
    <html><head><meta charset="utf-8"><style>{CSS}</style></head><body>

    <div>
    {header("English Language Arts", "Week 1, Tuesday -- Pattern Deep Dive")}
    {sectitle("Here's What We're Learning")}
    {secnote("Today we practice short vowel sounds. Read each word slowly and listen for the short vowel. Then use your spelling words in reading and writing activities.")}
    <ul style="font-size:12px;margin:4px 0 8px 0;">
    <li>Short <strong>a</strong> as in <em>basket</em> &mdash; the <span style="color:#FF7043;font-weight:bold;">a</span> says /a/</li>
    <li>Short <strong>e</strong> as in <em>helmet</em> &mdash; the <span style="color:#FF7043;font-weight:bold;">e</span> says /e/</li>
    <li>Short <strong>i</strong> as in <em>kitten</em> &mdash; the <span style="color:#FF7043;font-weight:bold;">i</span> says /i/</li>
    <li>Short <strong>o</strong> as in <em>doctor</em> &mdash; the <span style="color:#FF7043;font-weight:bold;">o</span> says /o/</li>
    <li>Short <strong>u</strong> as in <em>bubble</em> &mdash; the <span style="color:#FF7043;font-weight:bold;">u</span> says /u/</li>
    </ul>
    {remember_box("Remember This!", remember1)}
    {sectitle("Word Scramble Challenge")}
    {secnote("Unscramble the letters to spell a word from this week.")}
    {scramble_items}
    <hr class="divider">
    {sectitle("Reading Comprehension")}
    {secnote("Read the story. Notice each spelling word in bold.")}
    <div class="story-box">{reading_text}</div>
    <hr class="divider">
    {sectitle("Comprehension Questions")}
    {secnote("Answer each question in a complete sentence.")}
    {comp_html}
    <hr class="divider">
    {sectitle("Vowel Pattern Hunt")}
    {secnote("Check the box next to each word. The short vowel is highlighted in orange.")}
    {hunt_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Word Swap Challenge")}
    {secnote("Read the original sentence, then write a new one using the swapped words.")}
    {swap_html}
    <hr class="divider">
    {sectitle("Sentence Builder")}
    {secnote("Write a complete sentence for each prompt. Use the suggested spelling word.")}
    {builder_html}
    </div>

    </body></html>"""

    HTML(string=html).write_pdf(os.path.join(day_dir, "Week01_Tuesday_Pattern_Practice.pdf"))
    print("[ok] Tuesday generated")


# =====================================================================
# WEDNESDAY - Connect It (3 pages)
# =====================================================================

def generate_wednesday():
    day_dir = os.path.join(WEEK, "Wednesday")
    os.makedirs(day_dir, exist_ok=True)

    # Reading passage — Camping trip in the woods
    reading = (
        "Last <strong>winter</strong>, my family went camping in the big woods. "
        "We packed a <strong>basket</strong> full of food and snacks. "
        "I wore my bike <strong>helmet</strong> on the hike because the trail was rocky. "
        "We saw an <strong>elephant</strong> seal picture in the park <strong>garden</strong>. "
        "Dad found a tiny <strong>insect</strong> on our tent and a <strong>kitten</strong> near the campfire. "
        "A park <strong>doctor</strong> came to help a hurt <strong>animal</strong> we found. "
        "At night we saw a big <strong>octopus</strong> star in the sky and blew a soap <strong>bubble</strong> with my sister. "
        "We opened our <strong>umbrella</strong> when the rain started. "
        "Camping was the best trip ever!"
    )

    comp_data = [
        ("Where did the family go camping?", ""),
        ("What did the dad find on the tent?", ""),
        ("Who came to help the hurt animal?", ""),
        ("What did they do when the rain started?", ""),
    ]
    comp_html = ""
    for i, (q, _) in enumerate(comp_data, 1):
        comp_html += (f'<div style="margin:6px 0;font-size:12px;">'
                      f'<strong>{i}.</strong> {q}<br>{write_line()}</div>')

    # Synonyms & Antonyms — each word gets both, no hints
    syn_ant_words = ["garden", "kitten", "winter", "bubble", "helmet", "animal"]
    syn_ant_html = ""
    for word in syn_ant_words:
        syn_ant_html += (f'<div style="margin:6px 0;padding:6px 8px;background:#E8F5E9;border-radius:5px;border:1px solid #A5D6A7;">'
                         f'<div style="font-size:13px;font-weight:bold;color:#26A69A;margin-bottom:2px;">{word}</div>'
                         f'<div style="font-size:10.5px;color:#888;">Synonym: _________________ &nbsp;&nbsp; Antonym: _________________</div>'
                         f'{write_line()}</div>')

    # Word webs — two category webs
    word_web = (
        f'<div style="text-align:center;margin:12px 0;">'
        f'<div style="display:inline-block;border:3px solid #26A69A;border-radius:50%;padding:12px 20px;font-weight:bold;font-size:14px;color:#26A69A;background:#E0F2F1;">animal</div>'
        f'<div style="margin-top:8px;display:flex;justify-content:center;gap:12px;flex-wrap:wrap;">'
        f'<span style="background:#FFF3E0;border:1px solid #FFB74D;border-radius:4px;padding:4px 10px;font-size:11px;">kitten</span>'
        f'<span style="background:#FFF3E0;border:1px solid #FFB74D;border-radius:4px;padding:4px 10px;font-size:11px;">elephant</span>'
        f'<span style="background:#FFF3E0;border:1px solid #FFB74D;border-radius:4px;padding:4px 10px;font-size:11px;">rabbit</span>'
        f'<span style="background:#FFF3E0;border:1px solid #FFB74D;border-radius:4px;padding:4px 10px;font-size:11px;">octopus</span>'
        f'<span style="background:#FFF3E0;border:1px solid #FFB74D;border-radius:4px;padding:4px 10px;font-size:11px;">insect</span>'
        f'</div></div>'
        f'<div style="text-align:center;margin:16px 0;">'
        f'<div style="display:inline-block;border:3px solid #FF7043;border-radius:50%;padding:12px 20px;font-weight:bold;font-size:14px;color:#FF7043;background:#FFF3E0;">winter</div>'
        f'<div style="margin-top:8px;display:flex;justify-content:center;gap:12px;flex-wrap:wrap;">'
        f'<span style="background:#E0F2F1;border:1px solid #80CBC4;border-radius:4px;padding:4px 10px;font-size:11px;">snow</span>'
        f'<span style="background:#E0F2F1;border:1px solid #80CBC4;border-radius:4px;padding:4px 10px;font-size:11px;">cold</span>'
        f'<span style="background:#E0F2F1;border:1px solid #80CBC4;border-radius:4px;padding:4px 10px;font-size:11px;">ice</span>'
        f'<span style="background:#E0F2F1;border:1px solid #80CBC4;border-radius:4px;padding:4px 10px;font-size:11px;">scarf</span>'
        f'<span style="background:#E0F2F1;border:1px solid #80CBC4;border-radius:4px;padding:4px 10px;font-size:11px;">gloves</span>'
        f'</div></div>'
    )

    # Sentence sort
    sorted_sents = [
        ["the", "big", "elephant", "trunk", "has", "a", "long", "."],
        ["in", "winter", "the", "cold", "it", "is", "."],
        ["a", "blow", "bubble", "soap", "with", "i", "."],
    ]
    sort_html = ""
    for words in sorted_sents:
        shuffled_words = list(words)
        random.Random(303).shuffle(shuffled_words)
        sort_html += (f'<div style="margin:6px 0;font-size:12px;">'
                      f'Words: {" ".join(shuffled_words)}<br>{write_line()}</div>')

    # Correct the sentences
    wrong_sents = [
        "the rabbit hps in the garndn",
        "i blew a big bubbl",
        "the elefant is very big",
    ]
    correct_html = ""
    for sent in wrong_sents:
        correct_html += (f'<div style="margin:4px 0;font-size:12px;">'
                         f'<span style="text-decoration:line-through;color:#E57373;">{sent}</span><br>'
                         f'{write_line()}</div>')

    # Context clues
    context_data = [
        ("The insect was very small and had six legs.", "insect"),
        ("She opened her umbrella when it started raining.", "umbrella"),
    ]
    context_html = ""
    for sentence, answer in context_data:
        context_html += (f'<div style="margin:4px 0;font-size:12px;">'
                         f'"&#8220;{sentence}&#8221; -- What word does this describe?<br>'
                         f'{write_line()}</div>')

    # Word Search
    ws_html = word_search(WORD_NAMES, rows=12, cols=12, seed=77)

    remember_text = (
        "Short vowels say their quick, short sounds:<br>"
        "- Short <strong>a</strong> as in <em>basket</em><br>"
        "- Short <strong>e</strong> as in <em>helmet</em><br>"
        "- Short <strong>i</strong> as in <em>kitten</em><br>"
        "- Short <strong>o</strong> as in <em>doctor</em><br>"
        "- Short <strong>u</strong> as in <em>bubble</em><br><br>"
        "Grammar: Every sentence starts with a CAPITAL and ends with . or ? or !"
    )

    html = f"""<!DOCTYPE html>
    <html><head><meta charset="utf-8"><style>{CSS}</style></head><body>

    <div>
    {header("English Language Arts", "Week 1, Wednesday -- Reading & Vocabulary")}
    {remember_box("Remember This!", remember_text)}
    {sectitle("Reading Comprehension")}
    {secnote("Read the passage carefully, then answer the questions.")}
    <div class="story-box">{reading}</div>
    {comp_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Synonyms & Antonyms")}
    {secnote("For each word, write a synonym (same meaning) AND an antonym (opposite). Think of your own words!")}
    {syn_ant_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Word Webs")}
    {secnote("Each web shows a category word in the center with related words around it. Think of more words that belong in each web and write them on the lines below.")}
    {word_web}
    {sectitle("Sentence Sort")}
    {secnote("Rearrange the jumbled words into correct sentences.")}
    {sort_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Correct the Sentences")}
    {secnote("Each sentence has spelling errors. Rewrite them correctly.")}
    {correct_html}
    {sectitle("Context Clues")}
    {secnote("Read the sentence and figure out which spelling word it describes.")}
    {context_html}
    {sectitle("Word Search")}
    {secnote("Find and circle all 12 spelling words hidden in the grid.")}
    {ws_html}
    </div>

    </body></html>"""

    HTML(string=html).write_pdf(os.path.join(day_dir, "Week01_Wednesday_Reading_Vocabulary.pdf"))
    print("[ok] Wednesday generated")


# =====================================================================
# THURSDAY - Use It: Writing & Reading (4 pages)
# =====================================================================

def generate_thursday():
    day_dir = os.path.join(WEEK, "Thursday")
    os.makedirs(day_dir, exist_ok=True)

    # Page 1: Spelling Story — Circus performance
    story_text = (
        'The <strong>circus</strong> came to town in the middle of <strong>winter</strong>! '
        'I carried a <strong>basket</strong> of popcorn to my seat and put on my red <strong>helmet</strong>. '
        'First, a <strong>kitten</strong> dressed as a ringmaster walked across the tightrope. '
        'Then a huge <strong>elephant</strong> balanced on a giant soap <strong>bubble</strong>. '
        'A <strong>doctor</strong> checked every <strong>animal</strong> before the show started. '
        'I saw a tiny <strong>insect</strong> sitting on my ticket! '
        'The best part was the <strong>octopus</strong> juggler — he had eight arms and threw <strong>umbrella</strong>s! '
        'After the show, we planted flowers in the circus <strong>garden</strong>. '
        'It was the most amazing performance ever!'
    )

    # Comprehension Questions (3)
    comp_q1 = "What animal dressed as a ringmaster?"
    comp_q2 = "What was the best part of the show?"
    comp_q3 = "What did the doctor do before the show?"
    comp_html = ""
    for i, q in enumerate([comp_q1, comp_q2, comp_q3], 1):
        comp_html += (f'<div style="margin:6px 0;font-size:12px;">'
                      f'<strong>{i}.</strong> {q}<br>{write_line()}</div>')

    # Remember This! box
    remember_text = (
        "When you write a paragraph, start with a topic sentence (what your paragraph is about). "
        "Then add 2-3 detail sentences. Finish with a closing sentence. "
        "Always use capital letters and periods!"
    )

    # Page 2: Sentence Sort (4 jumbled sentences — different from Wednesday)
    sorted_sents = [
        ["the", "kitten", "plays", "in", "the", "garden", "."],
        ["i", "see", "an", "animal", "at", "the", "zoo", "."],
        ["the", "doctor", "checks", "the", "animal", "."],
        ["i", "carry", "an", "umbrella", "in", "the", "rain", "."],
    ]
    sort_html = ""
    for words in sorted_sents:
        shuffled_words = list(words)
        random.Random(401).shuffle(shuffled_words)
        sort_html += (f'<div style="margin:6px 0;font-size:12px;">'
                      f'Words: {" ".join(shuffled_words)}<br>{write_line()}</div>')

    # Spelling Detective (passage with 5 misspelled words)
    detective_passage = (
        'Last <strong>winter</strong>, Mia went to the <strong>garden</strong>. '
        'She carried a <span style="text-decoration:wavy underline;color:#E57373;">bascket</span> '
        'and wore a <span style="text-decoration:wavy underline;color:#E57373;">helmt</span>. '
        'She saw a tiny <span style="text-decoration:wavy underline;color:#E57373;">inseckt</span> '
        'and a cute <span style="text-decoration:wavy underline;color:#E57373;">kittn</span>. '
        'Mia also opened her <span style="text-decoration:wavy underline;color:#E57373;">umbrela</span>. '
        'It was a fun day!'
    )
    detective_fix_items = [
        ("bascket", "basket"),
        ("helmt", "helmet"),
        ("inseckt", "insect"),
        ("kittn", "kitten"),
        ("umbrela", "umbrella"),
    ]
    detective_fix_html = ""
    for wrong, _ in detective_fix_items:
        detective_fix_html += (f'<div style="margin:4px 0;font-size:12px;">'
                               f'<strong style="text-decoration:line-through;color:#E57373;">{wrong}</strong>'
                               f' &rarr; Correct spelling: {write_line()}</div>')

    # Page 3: Word Swap (3 items — replace one word with a synonym)
    swap_data = [
        ("The kitten slept in the basket.", "kitten", "baby cat"),
        ("The doctor helped the elephant.", "doctor", "healer"),
        ("I blew a bubble in winter.", "bubble", "soap ball"),
    ]
    swap_html = ""
    for orig, orig_word, swap_word in swap_data:
        highlighted_orig = orig.replace(orig_word, f'<strong>{orig_word}</strong>')
        swap_html += (f'<div style="margin-bottom:10px;padding:6px 8px;background:#FFF3E0;border-radius:5px;border:1px solid #FFB74D;">'
                      f'<div style="font-size:10.5px;font-weight:bold;color:#FF7043;margin-bottom:3px;">Original:</div>'
                      f'<div style="font-size:12px;font-style:italic;margin-bottom:4px;">{highlighted_orig}</div>'
                      f'<div style="font-size:10.5px;font-weight:bold;color:#FF7043;margin-bottom:3px;">'
                      f'Replace <strong>{orig_word}</strong> with <strong>{swap_word}</strong> and write a new sentence:</div>'
                      f'{write_line()}</div>')

    # Spelling Map (table: Word | Vowel Pattern | What it means — 6 words, first 2 filled as examples)
    map_rows = [
        ("basket", "short <strong>a</strong>", "a container for holding things", True),
        ("helmet", "short <strong>e</strong>", "a hard hat worn for protection", True),
        ("kitten", "", "", False),
        ("insect", "", "", False),
        ("octopus", "", "", False),
        ("bubble", "", "", False),
    ]
    map_table_html = '<table style="width:100%;border-collapse:separate;border-spacing:0;font-size:12px;">'
    map_table_html += (f'<tr>'
                       f'<th style="background:#E0F2F1;border:2px solid #80CBC4;padding:6px;text-align:left;font-size:12px;">Word</th>'
                       f'<th style="background:#E0F2F1;border:2px solid #80CBC4;padding:6px;text-align:left;font-size:12px;">Vowel Pattern</th>'
                       f'<th style="background:#E0F2F1;border:2px solid #80CBC4;padding:6px;text-align:left;font-size:12px;">What It Means</th>'
                       f'</tr>')
    for word, pattern, meaning, filled in map_rows:
        bg = "#FAFAFA" if filled else "#FFF8E1"
        map_table_html += (f'<tr>'
                           f'<td style="border:1px solid #B2DFDB;padding:6px;background:{bg};font-weight:bold;color:#26A69A;">{word}</td>'
                           f'<td style="border:1px solid #B2DFDB;padding:6px;background:{bg};">{pattern}</td>'
                           f'<td style="border:1px solid #B2DFDB;padding:6px;background:{bg};">{meaning}</td>'
                           f'</tr>')
    map_table_html += '</table>'

    # Page 4: Paragraph Builder (guided writing with sentence starters)
    para_starters = [
        "My paragraph is about the circus I saw: ",
        "First, I noticed ",
        "Next, something amazing happened — ",
        "Then, the most exciting part was ",
        "In the end, ",
    ]
    para_html = ""
    for starter in para_starters:
        para_html += (f'<div style="margin:6px 0;font-size:12px;">'
                      f'<span style="color:#26A69A;font-weight:bold;">{starter}</span>'
                      f'{write_line()}</div>')

    # Write Your Own Story (creative writing prompt)
    story_lines = ""
    for _ in range(8):
        story_lines += write_line()

    # Build HTML with all pre-evaluated variables
    html = f"""<!DOCTYPE html>
    <html><head><meta charset="utf-8"><style>{CSS}</style></head><body>

    <div>
    {header("English Language Arts", "Week 1, Thursday -- Use It: Writing & Reading")}
    {sectitle("Here's What We're Learning")}
    {secnote("Today we use our spelling words in reading and writing. Read the story carefully, answer questions, and practice writing paragraphs and stories!")}
    {remember_box("Remember This!", remember_text)}
    {sectitle("Spelling Story")}
    {secnote("Read the story carefully. Notice how the spelling words are used in sentences.")}
    <div class="story-box">{story_text}</div>
    {sectitle("Comprehension Questions")}
    {secnote("Answer each question in a complete sentence. Remember: capital letter and period!")}
    {comp_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Sentence Sort")}
    {secnote("Rearrange the jumbled words into correct sentences. Use capital letters and periods!")}
    {sort_html}
    <hr class="divider">
    {sectitle("Spelling Detective")}
    {secnote("This passage has 5 misspelled words with wavy red underlines. Find each wrong word and write the correct spelling on the lines below.")}
    <div class="story-box">{detective_passage}</div>
    {detective_fix_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Word Swap")}
    {secnote("Read each original sentence. Then replace the bold word with the new word and write a fresh sentence.")}
    {swap_html}
    <hr class="divider">
    {sectitle("Spelling Map")}
    {secnote("Complete the chart. The first two rows are filled in as examples. For each word, identify its vowel pattern and write what it means.")}
    {map_table_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Paragraph Builder")}
    {secnote("Use the sentence starters below to write a paragraph about the circus. Follow the Remember This! rule: topic sentence, details, closing sentence.")}
    {para_html}
    <hr class="divider">
    {sectitle("Write Your Own Story")}
    {secnote("Write a creative story using at least 5 spelling words from this week. Use complete sentences with capital letters and periods!")}
    {story_lines}
    </div>

    </body></html>"""

    HTML(string=html).write_pdf(os.path.join(day_dir, "Week01_Thursday_Writing_Reading.pdf"))
    print("[ok] Thursday generated")


# =====================================================================
# FRIDAY - Review It (3 pages) -- NO learning/remember boxes
# =====================================================================

def generate_friday():
    day_dir = os.path.join(WEEK, "Friday")
    os.makedirs(day_dir, exist_ok=True)

    # Spelling test
    test_items = ""
    for i, (word, _, _) in enumerate(WORDS, 1):
        test_items += (f'<div class="test-item">'
                       f'<span class="num">{i}.</span>'
                       f'<div style="flex:1;">{write_line()}</div></div>')

    # Review reading — Beach day adventure
    review_story = (
        'Last <strong>winter</strong>, my family drove to the beach for a picnic. '
        'We packed a <strong>basket</strong> with sandwiches and juice boxes. '
        'I wore my swimming <strong>helmet</strong> and brought my toy <strong>elephant</strong> to the sand. '
        'A <strong>kitten</strong> from next door followed us all the way to the car! '
        'We saw an <strong>octopus</strong> in the tide pool and a tiny <strong>insect</strong> on the driftwood. '
        'The lifeguard <strong>doctor</strong> said every beach <strong>animal</strong> is special. '
        'I blew a big <strong>bubble</strong> and opened my <strong>umbrella</strong> for shade. '
        'We even visited the beach <strong>garden</strong> and picked flowers. '
        'It was the best day ever!'
    )

    # Story questions
    review_q_data = [
        ("Where did the family drive for their picnic?", ""),
        ("What did they see in the tide pool?", ""),
        ("What did the narrator blow at the beach?", ""),
    ]
    review_q_html = ""
    for i, (q, _) in enumerate(review_q_data, 1):
        review_q_html += (f'<div style="margin:6px 0;font-size:12px;">'
                          f'<strong>{i}.</strong> {q}<br>{write_line()}</div>')

    # Opposite pairs
    opp_pairs = [
        ("winter", "summer"),
        ("kitten", "adult cat"),
    ]
    opp_html = ""
    for word, opp in opp_pairs:
        opp_html += (f'<div style="margin:4px 0;font-size:12px;">'
                     f'{word} (opposite): {write_line()}</div>')

    # Sentence builder
    builder_words = ["the", "big", "octopus", "swims", "in", "the", "ocean", "."]
    builder_html = (f'<div style="display:flex;flex-wrap:wrap;gap:6px;margin:8px 0;">'
                    + "".join(f'<span style="background:#E0F2F1;border:1px solid #80CBC4;border-radius:4px;padding:3px 8px;font-size:12px;">{w}</span>' for w in builder_words)
                    + '</div>'
                    + write_line())

    # Show what you know
    show_html = ""
    for word in WORDS[:8]:
        show_html += (f'<div style="margin:4px 0;font-size:12px;">'
                      f'<strong>{word[0]}:</strong> {write_line()}</div>')

    # Word journal
    journal_html = (f'<div style="height:120px;border:2px dashed #B2DFDB;border-radius:8px;margin:8px 0;"></div>'
                    + write_line() + write_line())

    # Celebration
    celebration = (f'<div style="text-align:center;padding:16px;background:#FFF8E1;border:2px solid #FFD54F;border-radius:8px;margin:12px 0;">'
                   f'<strong style="font-size:16px;color:#FF7043;">Great Job This Week!</strong><br>'
                   f'<span style="font-size:12px;color:#555;">You practiced all 12 short vowel words and wrote great sentences!</span></div>')

    html = f"""<!DOCTYPE html>
    <html><head><meta charset="utf-8"><style>{CSS}</style></head><body>

    <div>
    {header("English Language Arts", "Week 1, Friday -- Review & Assessment")}
    {sectitle("Spelling Test")}
    {secnote("Have your grown-up say each word. Write it on the line.")}
    {test_items}
    </div>
    {page_break()}

    <div>
    {sectitle("Review Reading")}
    {secnote("Read the story and answer the questions.")}
    <div class="story-box">{review_story}</div>
    {review_q_html}
    {sectitle("Opposite Pairs")}
    {secnote("Write the opposite of each word.")}
    {opp_html}
    {sectitle("Sentence Builder")}
    {secnote("Rearrange the words to build a correct sentence.")}
    {builder_html}
    </div>
    {page_break()}

    <div>
    {sectitle("Show What You Know")}
    {secnote("Write each word neatly and use it in a sentence.")}
    {show_html}
    {sectitle("Word Journal")}
    {secnote("Draw or write about your favorite word from this week.")}
    {journal_html}
    {celebration}
    </div>

    </body></html>"""

    HTML(string=html).write_pdf(os.path.join(day_dir, "Week01_Friday_Review_Assessment.pdf"))
    print("[ok] Friday generated")


# =====================================================================
# MAIN
# =====================================================================

if __name__ == "__main__":
    print("Generating Week 1 PDFs...")
    # Phonetic audit (verifies words against database)
    try:
        from audit.run_audit import validate_before_generate
        validate_before_generate(__file__)
    except ImportError:
        print("  [warn] audit system unavailable — skipping phonetic check")
    except Exception as e:
        print(f"\n  AUDIT FAILED: {e}")
        exit(1)

    generate_monday()
    generate_tuesday()
    generate_wednesday()
    generate_thursday()
    generate_friday()
