#!/usr/bin/env python3
"""
Week 5: Subtraction Facts to 20 — REWRITTEN
Phase 1: Number Sense & Operations

New Standard:
- Reduced drill (40% fewer problems)
- Added estimation activities
- Multiple strategies encouraged
- Better word problems (reasoning over keywords)
- Real challenges (open-ended thinking)
- Number talks (compare without calculating)
- Friday self-check with reflection
"""

import os
import glob
from weasyprint import HTML

from math_helpers import (
    CSS, TEACHER_CSS,
    page, page_multi, hdr, sec, b, bw, bl,
    tg_page, tg_page_multi, tg_sec, tg_note, tg_section_title,
)
from activity_builders import (
    build_subtraction_facts,
    build_subtraction_word_problems,
    build_fact_families_subtraction,
    build_fact_families,
    build_challenge_box,
)

BASE = os.path.expanduser("~/Home_School/2nd_Grade/Math")
WEEK = os.path.join(BASE, "Week_5")


# ═══════════════════════════════════════════════════
# MONDAY — Subtraction Facts from 10
# ═══════════════════════════════════════════════════
def monday():
    # 1: Subtraction is the opposite (concept introduction)
    s1 = '<div class="abox" style="background:#fff3e0;">'
    s1 += '<p><b>Subtraction is the Opposite of Addition</b></p>'
    s1 += '<p>3 + 7 = 10</p>'
    s1 += '<p>10 − 3 = 7  |  10 − 7 = 3</p>'
    s1 += '<p>One fact family — same 3 numbers!</p>'
    s1 += '</div>'
    
    # 2: Subtract from 10 (reduced from 9 to 6)
    s2 = build_subtraction_facts({
        "facts": [(10, 3), (10, 7), (10, 6), (10, 4), (10, 9), (10, 5)],
        "note": "Fill in the answer.",
        "cols": 3,
    })
    
    # 3: NEW — Estimate: About how much left?
    s3 = '<div class="abox" style="background:#e8f5e9;">'
    s3 += '<p><b>Estimate First!</b> About how many are left? Circle your guess.</p>'
    s3 += '<p>10 − 8: About 1  |  About 5  |  About 8</p>'
    s3 += '<p>Now calculate: 10 − 8 = ' + b('5em') + '</p>'
    s3 += '<p>10 − 2: About 1  |  About 5  |  About 8</p>'
    s3 += '<p>Now calculate: 10 − 2 = ' + b('5em') + '</p>'
    s3 += '</div>'
    
    # 4: Use addition to help subtract (reduced from 4 to 3)
    s4 = '<div class="abox">'
    s4 += '<p class="note">Use addition facts to help you subtract.</p>'
    s4 += '<p>10 − 5: 5 + ' + b('5em') + ' = 10, so 10 − 5 = ' + b('5em') + '</p>'
    s4 += '<p>10 − 4: 4 + ' + b('5em') + ' = 10, so 10 − 4 = ' + b('5em') + '</p>'
    s4 += '<p>10 − 8: 8 + ' + b('5em') + ' = 10, so 10 − 8 = ' + b('5em') + '</p>'
    s4 += '</div>'
    
    # 5: Challenge — Missing numbers (reduced from 6 to 4)
    s5 = '<div class="abox" style="background:#f3e5f5;">'
    s5 += '<p><b>Challenge: Find the Missing Number</b></p>'
    s5 += '<div class="mgrid c2">'
    s5 += '<div class="abox"><p>' + b('5em') + ' − 3 = 7</p></div>'
    s5 += '<div class="abox"><p>10 − ' + b('5em') + ' = 4</p></div>'
    s5 += '<div class="abox"><p>' + b('5em') + ' − 6 = 4</p></div>'
    s5 += '<div class="abox"><p>10 − ' + b('5em') + ' = 9</p></div>'
    s5 += '</div></div>'
    
    return page(5, "Monday", "Subtraction Facts — From 10",
        f'''{sec(1, "Subtraction is the Opposite", s1)}
{sec(2, "Subtract from 10", s2, pb=True)}
{sec(3, "Estimate First!", s3)}
{sec(4, "Use Addition to Help", s4)}
{sec(5, "Challenge: Missing Numbers", s5)}''')


# ═══════════════════════════════════════════════════
# TUESDAY — Subtracting 11-20
# ═══════════════════════════════════════════════════
def tuesday():
    # 1: Quick review subtract from 10 (reduced from 9 to 6)
    s1 = build_subtraction_facts({
        "facts": [(10, 4), (10, 7), (10, 2), (10, 5), (10, 8), (10, 3)],
        "note": "Quick review: subtract from 10.",
        "cols": 3,
    })
    
    # 2: Strategy introduction
    s2 = '<div class="abox" style="background:#fff3e0;">'
    s2 += '<p><b>Subtracting from Numbers 11-20</b></p>'
    s2 += '<p>Strategy: Make 10 first!</p>'
    s2 += '<p>13 − 5: Think "13 − 3 = 10, then 10 − 2 = 8"</p>'
    s2 += '</div>'
    
    # 3: Practice with strategies (reduced from 9 to 6)
    s3 = build_subtraction_facts({
        "facts": [(13, 5), (14, 6), (12, 4), (15, 7), (11, 3), (16, 8)],
        "note": "Use any strategy you like.",
        "cols": 3,
    })
    
    # 4: NEW — Multiple strategies encouraged
    s4 = '<div class="abox" style="background:#e8f5e9;">'
    s4 += '<p><b>Show Two Different Ways</b></p>'
    s4 += '<div class="mgrid c2">'
    s4 += '<div class="abox"><p style="font-size:16px; font-weight:700;">15 − 7</p>'
    s4 += '<p>Way 1 (make 10): 15 − ' + b('4em') + ' = 10, 10 − ' + b('4em') + ' = ' + b('4em') + '</p>'
    s4 += '<p>Way 2 (addition): 7 + ' + b('4em') + ' = 15, so 15 − 7 = ' + b('4em') + '</p></div>'
    s4 += '<div class="abox"><p style="font-size:16px; font-weight:700;">17 − 9</p>'
    s4 += '<p>Way 1 (make 10): 17 − ' + b('4em') + ' = 10, 10 − ' + b('4em') + ' = ' + b('4em') + '</p>'
    s4 += '<p>Way 2 (addition): 9 + ' + b('4em') + ' = 17, so 17 − 9 = ' + b('4em') + '</p></div>'
    s4 += '</div></div>'
    
    # 5: Challenge — Explain your thinking
    s5 = '<div class="abox" style="background:#f3e5f5;">'
    s5 += '<p><b>Explain Your Thinking</b></p>'
    s5 += '<p>How would you solve 16 − 8? Write or draw your strategy.</p>'
    s5 += '<div style="min-height:50px; border:1px dashed #ccc;"></div>'
    s5 += '</div>'
    
    return page(5, "Tuesday", "Subtracting 11-20",
        f'''{sec(1, "Review: Subtract from 10", s1, pb=True)}
{sec(2, "Strategy: Make 10 First", s2)}
{sec(3, "Practice Problems", s3, pb=True)}
{sec(4, "Show Two Different Ways", s4)}
{sec(5, "Challenge: Explain Your Thinking", s5)}''')


# ═══════════════════════════════════════════════════
# WEDNESDAY — Mixed Subtraction Practice
# ═══════════════════════════════════════════════════
def wednesday():
    # 1: Quick review (reduced from 9 to 6)
    s1 = build_subtraction_facts({
        "facts": [(10, 5), (10, 8), (10, 3), (10, 7), (10, 4), (10, 9)],
        "note": "Quick review.",
        "cols": 3,
    })
    
    # 2: Subtract from 11-20 (reduced from 8 to 6)
    s2 = build_subtraction_facts({
        "facts": [(12, 5), (13, 6), (14, 7), (15, 8), (16, 9), (17, 10)],
        "note": "Subtract from 11-20.",
        "cols": 2,
    })
    
    # 3: NEW — Number Talk: Which is larger? Explain without calculating.
    s3 = '<div class="abox" style="background:#e3f2fd;">'
    s3 += '<p><b>Number Talk</b> — Which is larger? Explain WITHOUT calculating.</p>'
    s3 += '<div class="mgrid c2">'
    s3 += '<div class="abox"><p>15 − 7  or  15 − 3</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s3 += '<div class="abox"><p>18 − 9  or  17 − 9</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s3 += '</div></div>'
    
    # 4: Word problems (reasoning, not keywords) — reduced from 2 to 2 but better quality
    s4 = '<div class="wp">'
    s4 += '<p class="note">Read carefully. Think about what is happening in the situation.</p>'
    s4 += '<div class="mgrid c2">'
    s4 += '<div class="abox"><p>Tom had 15 stickers. He gave 7 to his friend. How many does he have left?</p><p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p><p>Answer: ' + b('5em') + '</p></div>'
    s4 += '<div class="abox"><p>There were 18 cookies on the plate. Sarah ate 9. How many are left?</p><p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p><p>Answer: ' + b('5em') + '</p></div>'
    s4 += '</div></div>'
    
    # 5: Challenge — Open-ended
    s5 = '<div class="abox" style="background:#f3e5f5;">'
    s5 += '<p><b>Challenge Problems</b></p>'
    s5 += '<p>1. 20 − 13 = ' + b('5em') + '</p>'
    s5 += '<p>2. 19 − 12 = ' + b('5em') + '</p>'
    s5 += '<p>3. <b>Create your own word problem</b> using subtraction from 11-20: ' + bl() + '</p>'
    s5 += '</div>'
    
    return page(5, "Wednesday", "Mixed Subtraction Practice",
        f'''{sec(1, "Quick Review", s1, pb=True)}
{sec(2, "Subtract from 11-20", s2)}
{sec(3, "Number Talk: Which is Larger?", s3, pb=True)}
{sec(4, "Word Problems", s4)}
{sec(5, "Challenge Problems", s5)}''')


# ═══════════════════════════════════════════════════
# THURSDAY — Fact Families
# ═══════════════════════════════════════════════════
def thursday():
    # 1: What is a fact family (concept)
    s1 = '<div class="abox" style="background:#fff3e0;">'
    s1 += '<p><b>Fact Families</b></p>'
    s1 += '<p>3, 7, 10 make a family:</p>'
    s1 += '<p>3 + 7 = 10  |  7 + 3 = 10  |  10 − 3 = 7  |  10 − 7 = 3</p>'
    s1 += '</div>'
    
    # 2: Complete fact families (reduced from 4 to 3)
    s2 = build_fact_families({
        "families": [[4, 6, 10], [5, 5, 10], [3, 8, 11]],
        "note": "Complete each fact family.",
        "show_triangle": True,
        "include_subtraction": True,
    })
    
    # 3: Related subtraction facts (reduced from 4 to 3)
    s3 = build_fact_families_subtraction({
        "families": [[5, 6, 11], [7, 8, 15], [4, 9, 13]],
        "note": "Write the related subtraction fact.",
        "cols": 2,
    })
    
    # 4: Find missing number (reduced from 4 to 3)
    s4 = '<div class="abox">'
    s4 += '<p><b>Find the Missing Number in Each Family</b></p>'
    s4 += '<div class="mgrid c2">'
    s4 += '<div class="abox"><p>' + b('5em') + ', 7, 12 (7 + 5 = 12, 12 − 7 = 5)</p></div>'
    s4 += '<div class="abox"><p>6, ' + b('5em') + ', 15 (6 + 9 = 15, 15 − 6 = 9)</p></div>'
    s4 += '<div class="abox"><p>8, 4, ' + b('5em') + ' (8 + 4 = 12, 12 − 8 = 4)</p></div>'
    s4 += '</div></div>'
    
    # 5: Challenge — Create your own fact family
    s5 = '<div class="abox" style="background:#f3e5f5;">'
    s5 += '<p><b>Create Your Own Fact Family</b></p>'
    s5 += '<p>Pick three numbers that make a fact family: ' + b('5em') + ', ' + b('5em') + ', ' + b('5em') + '</p>'
    s5 += '<p>Write all four facts:</p>'
    s5 += '<p>1. ' + bl() + '</p>'
    s5 += '<p>2. ' + bl() + '</p>'
    s5 += '<p>3. ' + bl() + '</p>'
    s5 += '<p>4. ' + bl() + '</p>'
    s5 += '</div>'
    
    return page(5, "Thursday", "Fact Families",
        f'''{sec(1, "What is a Fact Family?", s1, pb=True)}
{sec(2, "Complete Fact Families", s2)}
{sec(3, "Related Subtraction Facts", s3, pb=True)}
{sec(4, "Find the Missing Number", s4)}
{sec(5, "Challenge: Create Your Own", s5)}''')


# ═══════════════════════════════════════════════════
# FRIDAY — Week 5 Review & Self-Check
# ═══════════════════════════════════════════════════
def friday():
    # 1: Subtract from 10 (reduced from 9 to 6)
    s1 = build_subtraction_facts({
        "facts": [(10, 4), (10, 7), (10, 2), (10, 5), (10, 8), (10, 3)],
        "note": "Quick facts: subtract from 10.",
        "cols": 3,
    })
    
    # 2: Subtract from 11-20 (reduced from 9 to 6)
    s2 = build_subtraction_facts({
        "facts": [(13, 5), (14, 6), (15, 7), (16, 8), (17, 9), (18, 10)],
        "note": "Subtract from 11-20.",
        "cols": 3,
    })
    
    # 3: Solve any way (reduced from 9 to 6)
    s3 = build_subtraction_facts({
        "facts": [(15, 8), (16, 9), (17, 10), (18, 11), (19, 12), (14, 7)],
        "note": "Solve using any strategy.",
        "cols": 3,
    })
    
    # 4: Word problems (reduced from 2 to 2 but better quality)
    s4 = '<div class="wp">'
    s4 += '<p class="note">Read carefully. Think about what is happening.</p>'
    s4 += '<div class="mgrid c2">'
    s4 += '<div class="abox"><p>Tom had 17 marbles. He lost 8. How many does he have left?</p><p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p><p>Answer: ' + b('5em') + '</p></div>'
    s4 += '<div class="abox"><p>There were 19 apples. Sarah picked 12. How many are left on the tree?</p><p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p><p>Answer: ' + b('5em') + '</p></div>'
    s4 += '</div></div>'
    
    # 5: NEW — Self-Check with reflection
    s5 = '<div class="selfcheck">'
    s5 += '<p><b>Self-Check: How do you feel about subtraction?</b></p>'
    s5 += '<div style="display:flex; gap:20px; flex-wrap:wrap;">'
    s5 += '<div style="background:#fff3e0; padding:10px; border-radius:5px; flex:1; min-width:150px;">'
    s5 += '<p><b>Subtract from 10</b></p>'
    s5 += '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'
    s5 += '</div>'
    s5 += '<div style="background:#e8f5e9; padding:10px; border-radius:5px; flex:1; min-width:150px;">'
    s5 += '<p><b>Subtract 11-20</b></p>'
    s5 += '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'
    s5 += '</div>'
    s5 += '<div style="background:#e3f2fd; padding:10px; border-radius:5px; flex:1; min-width:150px;">'
    s5 += '<p><b>Fact Families</b></p>'
    s5 += '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'
    s5 += '</div>'
    s5 += '</div>'
    s5 += '<p style="margin-top:10px;"><b>One thing I learned this week:</b> ' + bl() + '</p>'
    s5 += '</div>'
    
    return page(5, "Friday", "Week 5 Review & Self-Check",
        f'''{sec(1, "Subtract from 10", s1, pb=True)}
{sec(2, "Subtract from 11-20", s2)}
{sec(3, "Solve Any Way", s3, pb=True)}
{sec(4, "Word Problems", s4)}
{sec(5, "Self-Check & Reflection", s5)}''')


# ═══════════════════════════════════════════════════
# TEACHER GUIDE — Combined for all days
# ═══════════════════════════════════════════════════
def teacher_guide():
    """Generate combined teacher guide for all 5 days."""
    return tg_page_multi(
        "Week 5", "Subtraction Facts to 20 — Teacher Guide",
        
        # Monday
        tg_section_title("Monday: Subtraction Facts — From 10") +
        tg_sec(1, "Subtraction is the Opposite", ["3+7=10, 10-3=7, 10-7=3"]) +
        tg_sec(2, "Subtract from 10", ["7", "3", "4", "6", "1", "5"]) +
        tg_sec(3, "Estimate First", ["Circle About 1 (closest to actual), actual=2", "Circle About 8, actual=8"]) +
        tg_sec(4, "Use Addition to Help", ["5+5=10, 10-5=5", "4+6=10, 10-4=6", "8+2=10, 10-8=2"]) +
        tg_sec(5, "Missing Numbers", ["10", "6", "10", "1"]) +
        tg_note("Page break"),
        
        # Tuesday
        tg_section_title("Tuesday: Subtracting 11-20") +
        tg_sec(1, "Review Subtract from 10", ["6", "3", "8", "5", "2", "7"]) +
        tg_sec(2, "Strategy: Make 10 First", ["13-3=10, 10-2=8"]) +
        tg_sec(3, "Practice Problems", ["8", "8", "8", "8", "8", "8"]) +
        tg_sec(4, "Show Two Ways", ["15-5=10, 10-2=8 OR 7+8=15", "17-7=10, 10-2=8 OR 9+8=17"]) +
        tg_sec(5, "Explain Thinking", ["Accept any valid strategy explanation"]) +
        tg_note("Page break"),
        
        # Wednesday
        tg_section_title("Wednesday: Mixed Subtraction Practice") +
        tg_sec(1, "Quick Review", ["5", "2", "7", "3", "6", "1"]) +
        tg_sec(2, "Subtract from 11-20", ["7", "7", "7", "7", "7", "7"]) +
        tg_sec(3, "Number Talk", ["15-3 is larger (subtracting less)", "18-9 is larger (starting with more)"]) +
        tg_sec(4, "Word Problems", ["15-7=8", "18-9=9"]) +
        tg_sec(5, "Challenge", ["7", "7", "Accept any valid student word problem"]) +
        tg_note("Page break"),
        
        # Thursday
        tg_section_title("Thursday: Fact Families") +
        tg_sec(1, "What is a Fact Family?", ["3+7=10, 7+3=10, 10-3=7, 10-7=3"]) +
        tg_sec(2, "Complete Fact Families", ["4+6=10, 6+4=10, 10-4=6, 10-6=4", "5+5=10, 10-5=5", "3+8=11, 8+3=11, 11-3=8, 11-8=3"]) +
        tg_sec(3, "Related Subtraction", ["11-5=6, 11-6=5", "15-7=8, 15-8=7", "13-4=9, 13-9=4"]) +
        tg_sec(4, "Missing Numbers", ["5", "9", "12"]) +
        tg_sec(5, "Create Your Own", ["Accept any valid fact family"]) +
        tg_note("Page break"),
        
        # Friday
        tg_section_title("Friday: Week 5 Review & Self-Check") +
        tg_sec(1, "Subtract from 10", ["6", "3", "8", "5", "2", "7"]) +
        tg_sec(2, "Subtract from 11-20", ["8", "8", "8", "8", "8", "8"]) +
        tg_sec(3, "Solve Any Way", ["7", "7", "7", "7", "7", "7"]) +
        tg_sec(4, "Word Problems", ["17-8=9", "19-12=7"]) +
        tg_sec(5, "Self-Check", ["Accept student self-assessment and reflection"])
    )


# ═══════════════════════════════════════════════════
# GENERATE
# ═══════════════════════════════════════════════════
if __name__ == "__main__":
    # Clean old files
    for f in glob.glob(os.path.join(WEEK, "*.pdf")):
        os.remove(f)
    for f in glob.glob(os.path.join(WEEK, "*.html")):
        os.remove(f)
    
    days = [
        (monday, "Monday", "Subtraction Facts — From 10"),
        (tuesday, "Tuesday", "Subtracting 11-20"),
        (wednesday, "Wednesday", "Mixed Subtraction Practice"),
        (thursday, "Thursday", "Fact Families"),
        (friday, "Friday", "Week 5 Review & Self-Check"),
    ]
    
    # Generate student worksheets
    for lesson_func, day, title in days:
        html = lesson_func()
        fname = f"Week_5_{day}"
        path = os.path.join(WEEK, f"{fname}.html")
        with open(path, "w") as f:
            f.write(html)
        pdf_path = os.path.join(WEEK, f"{fname}.pdf")
        HTML(filename=path).write_pdf(pdf_path)
        print(f"Generated: {pdf_path}")
    
    # Generate combined teacher guide
    html = teacher_guide()
    path = os.path.join(WEEK, "Week_5_Teacher_Guide.html")
    with open(path, "w") as f:
        f.write(html)
    pdf_path = os.path.join(WEEK, "Week_5_Teacher_Guide.pdf")
    HTML(filename=path).write_pdf(pdf_path)
    print(f"Generated: {pdf_path}")
    
    print("\nWeek 5 (rewritten) complete!")
