#!/usr/bin/env python3
"""
Week 7: Adding Within 100 (No Regrouping) — REWRITTEN
Phase 2: Addition & Subtraction to 100

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_column_addition,
    build_missing_addend,
)

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


# ═══════════════════════════════════════════════════
# MONDAY — Adding Tens (Mental Math)
# ═══════════════════════════════════════════════════
def monday():
    # 1: Add 10 to any number (reduced from 6 to 4)
    s1 = '<p class="note">When you add 10, only the <b>tens digit</b> changes. The ones stay the same.</p>'
    s1 += '<div class="mgrid c3">'
    for n in [23, 45, 67, 12]:
        s1 += f'<div class="abox"><p>{n} + 10 = {b("5em")}</p></div>'
    s1 += '</div>'
    
    # 2: Add multiples of 10 (reduced from 6 to 4)
    s2 = '<p class="note">Add the tens. Keep the ones.</p>'
    s2 += '<div class="mgrid c3">'
    for a, t in [(34, 20), (56, 30), (78, 10), (42, 50)]:
        s2 += f'<div class="abox"><p>{a} + {t} = {b("5em")}</p></div>'
    s2 += '</div>'
    
    # 3: Number line jumps (reduced from 4 to 2)
    s3 = '<p class="note">Use the number line. Mark jumps of 10 from the first number.</p>'
    s3 += '<div class="mgrid c2">'
    for a, t in [(25, 30), (47, 40)]:
        s3 += f'<div class="abox"><p style="font-size:1.1em;"><b>{a} + {t} = {b("5em")}</b></p>'
        start_tick = (a // 10) * 10
        end_tick = start_tick + 60
        s3 += '<div style="position:relative; height:50px; margin-top:20px;">'
        s3 += '<div style="position:absolute; left:0; right:0; top:25px; height:3px; background:#333;"></div>'
        for tick in range(start_tick, end_tick + 10, 10):
            left_pct = ((tick - start_tick) / 60) * 100
            s3 += f'<div style="position:absolute; left:{left_pct}%; top:20px; height:10px; width:2px; background:#333;"></div>'
            s3 += f'<div style="position:absolute; left:{left_pct}%; top:32px; transform:translateX(-50%); font-size:0.85em;">{tick}</div>'
        s3 += '</div>'
        s3 += f'<p style="font-size:0.85em; color:#666; margin-top:10px;">Mark jumps of 10 starting at {a}</p>'
        s3 += '</div>'
    s3 += '</div>'
    
    # 4: NEW — Number Talk: Which sum is bigger? Explain without calculating.
    s4 = '<div class="abox" style="background:#e3f2fd;">'
    s4 += '<p><b>Number Talk</b> — Which sum is bigger? Explain WITHOUT calculating.</p>'
    s4 += '<div class="mgrid c2">'
    s4 += '<div class="abox"><p>34 + 20  or  34 + 30</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '<div class="abox"><p>56 + 10  or  56 + 40</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '</div></div>'
    
    # 5: Challenge — Add three numbers (reduced from 4 to 2)
    s5 = '<div class="abox" style="background:#f3e5f5;">'
    s5 += '<p><b>Challenge</b> — Add all the tens first, then all the ones.</p>'
    s5 += '<div class="mgrid c2">'
    for a, c, e in [(20, 30, 45), (10, 50, 23)]:
        s5 += f'<div class="abox"><p>{a} + {c} + {e} = {b("6em")}</p></div>'
    s5 += '</div></div>'
    
    return page(7, "Monday", "Adding Tens (Mental Math)",
        f'''{sec(1, "Add 10", s1)}
{sec(2, "Add Multiples of 10", s2)}
{sec(3, "Number Line Jumps", s3)}
{sec(4, "Number Talk: Which is Bigger?", s4)}
{sec(5, "Challenge: Three Numbers", s5)}''')


# ═══════════════════════════════════════════════════
# TUESDAY — Adding 2-Digit Numbers (Horizontal)
# ═══════════════════════════════════════════════════
def tuesday():
    # 1: Add ones first, then tens (reduced from 6 to 4)
    s1 = '<p class="note">Add the ones, then add the tens. Write the total.</p>'
    s1 += '<div class="mgrid c3">'
    problems = [(23, 45), (34, 54), (42, 36), (53, 24)]
    for a, c in problems:
        s1 += f'<div class="abox"><p>{a} + {c} = {b("5em")}</p></div>'
    s1 += '</div>'
    
    # 2: NEW — Estimation: About how much?
    s2 = '<div class="abox" style="background:#fff3e0;">'
    s2 += '<p><b>Estimate First!</b> About how much?</p>'
    s2 += '<div class="mgrid c2">'
    for a, c in [(34, 56), (61, 28), (42, 37)]:
        at, ao = a // 10, a % 10
        ct, co = c // 10, c % 10
        s2 += f'<div class="abox"><p><b>{a} + {c}</b></p>'
        s2 += f'<p>Round to tens: {at*10} + {ct*10} = {(at+ct)*10}</p>'
        s2 += f'<p>About: ' + b('4em') + '</p>'
        s2 += f'<p>Actual: ' + b('4em') + '</p></div>'
    s2 += '</div></div>'
    
    # 3: Step-by-step addition (reduced from 3 to 2)
    s3 = '<p class="note">Show your work: add ones, add tens, combine.</p>'
    s3 += '<div class="mgrid c2">'
    for a, c in [(24, 35), (43, 56)]:
        ao, at = a % 10, a // 10
        co, ct = c % 10, c // 10
        s3 += f'<div class="abox"><p><b>{a} + {c}</b></p>'
        s3 += f'<p>Ones: {ao} + {co} = ' + b("4em") + '</p>'
        s3 += f'<p>Tens: {at} + {ct} = ' + b("4em") + '0</p>'
        s3 += '<p><b>Total: </b>' + b("5em") + '</p></div>'
    s3 += '</div>'
    
    # 4: Multiple strategies encouraged
    s4 = '<div class="abox">'
    s4 += '<p class="note">Use ANY strategy you prefer. Try a different one for each problem.</p>'
    s4 += '<div class="mgrid c2">'
    for a, c in [(35, 42), (64, 23), (51, 38), (72, 16)]:
        s4 += f'<div class="abox"><p><b>{a} + {c} = </b>{b("5em")}</p>'
        s4 += '<p style="font-size:11px; color:#666;">Strategy I used: ' + bw() + '</p></div>'
    s4 += '</div></div>'
    
    # 5: NEW — Better word problems (reasoning, not keywords)
    s5 = '<div class="wp">'
    s5 += '<p class="note">Read carefully. Think about what is happening in the situation.</p>'
    s5 += '<div class="mgrid c2">'
    s5 += '<div class="abox"><p>Sarah has 23 red marbles and 34 blue marbles. She wants to put them all in one jar. How many marbles will be in the jar?</p><p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p><p>Answer: ' + b("4em") + ' marbles</p></div>'
    s5 += '<div class="abox"><p>The library had 45 books on the top shelf and 32 books on the bottom shelf. A student wants to know the total books on both shelves. How many?</p><p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p><p>Answer: ' + b("4em") + ' books</p></div>'
    s5 += '</div></div>'
    
    return page(7, "Tuesday", "Adding 2-Digit Numbers",
        f'''{sec(1, "Add Ones, Then Tens", s1)}
{sec(2, "Estimate First!", s2)}
{sec(3, "Step-by-Step Addition", s3)}
{sec(4, "Try Different Strategies", s4)}
{sec(5, "Word Problems", s5)}''')


# ═══════════════════════════════════════════════════
# WEDNESDAY — Column Addition (No Regrouping)
# ═══════════════════════════════════════════════════
def wednesday():
    # 1: Column addition introduction (reduced from 6 to 4)
    s1 = '<p class="note">Line up the numbers. Add ones column, then tens column.</p>'
    s1 = build_column_addition({
        "problems": [(23, 45), (34, 54), (42, 36), (53, 24)],
        "digits": 2,
        "note": "Line up the columns. Add ones first, then tens."
    })
    
    # 2: More column practice (reduced from 6 to 4)
    s2 = build_column_addition({
        "problems": [(35, 42), (51, 38), (72, 16), (45, 24)],
        "digits": 2,
        "note": "Keep your columns straight!"
    })
    
    # 3: Three addends (reduced from 3 to 2)
    s3 = '<p class="note">Add the ones column first, then the tens column.</p>'
    s3 += '<div class="mgrid c2">'
    for a, c, e in [(23, 34, 42), (45, 21, 33)]:
        s3 += f'<div class="abox" style="text-align:center;">'
        s3 += f'<p style="font-size:1.3em; letter-spacing:3px;">  {a}</p>'
        s3 += f'<p style="font-size:1.3em; letter-spacing:3px;">+ {c}</p>'
        s3 += f'<p style="font-size:1.3em; letter-spacing:3px;">+ {e}</p>'
        s3 += '<hr style="border:2px solid #333;">'
        s3 += f'<p style="font-size:1.3em; letter-spacing:3px;">  {b("4em")}</p>'
        s3 += '</div>'
    s3 += '</div>'
    
    # 4: Find the error (reduced from 3 to 2)
    s4 = '<div class="abox">'
    s4 += '<p class="note">One of these is wrong. Find it, explain the error, and fix it.</p>'
    s4 += '<div class="mgrid c2">'
    # One wrong: 37+42 should be 79, not 69
    s4 += '<div class="abox"><p style="text-align:center;">  23</p><p style="text-align:center;">+ 45</p><hr><p style="text-align:center;">  68</p><p>✓ or ✗?</p><p style="font-size:11px;">If wrong, fix: ' + b("4em") + '</p></div>'
    s4 += '<div class="abox"><p style="text-align:center;">  37</p><p style="text-align:center;">+ 42</p><hr><p style="text-align:center;">  69</p><p>✓ or ✗?</p><p style="font-size:11px;">If wrong, fix: ' + b("4em") + '</p></div>'
    s4 += '</div></div>'
    
    # 5: Challenge — Create a column addition
    s5 = '<div class="abox" style="background:#f3e5f5;">'
    s5 += '<p><b>Create Your Own</b></p>'
    s5 += '<p>Make a column addition problem where the answer is 87. Write it and solve it.</p>'
    s5 += '<p style="text-align:center; font-size:1.3em; letter-spacing:3px;">  ' + b("3em") + '</p>'
    s5 += '<p style="text-align:center; font-size:1.3em; letter-spacing:3px;">+ ' + b("3em") + '</p>'
    s5 += '<hr style="border:2px solid #333;">'
    s5 += '<p style="text-align:center; font-size:1.3em; letter-spacing:3px;">  87</p>'
    s5 += '</div>'
    
    return page(7, "Wednesday", "Column Addition",
        f'''{sec(1, "Column Addition", s1)}
{sec(2, "More Practice", s2)}
{sec(3, "Three Addends", s3)}
{sec(4, "Find the Error", s4)}
{sec(5, "Challenge: Create Your Own", s5)}''')


# ═══════════════════════════════════════════════════
# THURSDAY — Word Problems & Real World
# ═══════════════════════════════════════════════════
def thursday():
    # 1: Better word problems (reduced from 4 to 3)
    s1 = '<div class="wp">'
    s1 += '<p class="note">Read carefully. Think about what is happening.</p>'
    s1 += '<div class="mgrid c2">'
    problems = [
        ("Emma collected 34 shells on Monday and 42 shells on Tuesday. She wants to make a display with all her shells. How many shells does she have?", 34, 42, "shells"),
        ("The library has 56 fiction books and 32 non-fiction books. A teacher wants to know the total for her class. How many books?", 56, 32, "books"),
        ("A farmer has 63 chickens and 24 ducks. He wants to count all his birds. How many birds?", 63, 24, "birds"),
    ]
    for text, a, c, unit in problems:
        s1 += f'<div class="abox"><p style="font-size:0.95em;">{text}</p>'
        s1 += '<p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p>'
        s1 += '<p>' + b("6em") + f' {unit}</p></div>'
    s1 += '</div></div>'
    
    # 2: Compare two problems (reduced from 2 to 1)
    s2 = '<div class="abox">'
    s2 += '<p class="note">Solve both. Which sum is bigger? Explain WITHOUT calculating first.</p>'
    s2 += '<div class="mgrid c1">'
    s2 += '<div class="abox"><p>A: 34 + 45 = ' + b("5em") + '</p>'
    s2 += '<p>B: 52 + 23 = ' + b("5em") + '</p>'
    s2 += '<p>Before calculating, which do you think is bigger? <span class="bw">A</span> or <span class="bw">B</span></p>'
    s2 += '<p>My thinking: ' + bw() + '</p>'
    s2 += '<p>After calculating, which is actually bigger? <span class="bw">A</span> or <span class="bw">B</span></p></div>'
    s2 += '</div></div>'
    
    # 3: Two-step problems (reduced from 2 to 1)
    s3 = '<div class="abox">'
    s3 += '<p class="note">Solve step by step. Write each answer.</p>'
    s3 += '<div class="mgrid c1">'
    s3 += '<div class="abox"><p>Sarah has 23 stickers. Tom gives her 34. Then Mom gives her 20 more. How many does she have now?</p>'
    s3 += '<p>Step 1: ' + b("6em") + '</p>'
    s3 += '<p>Step 2: ' + b("6em") + '</p>'
    s3 += '<p>Total: ' + b("6em") + ' stickers</p></div>'
    s3 += '</div></div>'
    
    # 4: Create your own (kept)
    s4 = '<div class="abox" style="background:#f3e5f5;">'
    s4 += '<p><b>Create Your Own Word Problem</b></p>'
    s4 += '<p>Write an addition word problem about something you like (sports, animals, games, etc.). Then solve it.</p>'
    s4 += '<p style="min-height:50px; border-bottom:1px solid #333;"></p>'
    s4 += '<p>Answer: ' + bl() + '</p>'
    s4 += '</div>'
    
    return page(7, "Thursday", "Addition Word Problems",
        f'''{sec(1, "Word Problems", s1)}
{sec(2, "Compare Sums", s2)}
{sec(3, "Two-Step Problem", s3)}
{sec(4, "Create Your Own", s4)}''')


# ═══════════════════════════════════════════════════
# FRIDAY — Review & Self-Check
# ═══════════════════════════════════════════════════
def friday():
    # 1: Mental math warm-up (reduced from 8 to 6)
    s1 = '<p class="note">Solve in your head. Go fast!</p>'
    s1 += '<div class="mgrid c3">'
    for a, t in [(20, 30), (40, 50), (70, 20), (30, 40), (50, 40), (60, 30)]:
        s1 += f'<div class="abox"><p>{a} + {t} = {b("4em")}</p></div>'
    s1 += '</div>'
    
    # 2: Column addition review (reduced from 6 to 4)
    s2 = build_column_addition({
        "problems": [(34, 45), (43, 56), (54, 35), (26, 63)],
        "digits": 2,
        "note": "Review: Column addition (no regrouping)."
    })
    
    # 3: Mixed horizontal (reduced from 6 to 4)
    s3 = '<p class="note">Use any strategy you prefer.</p>'
    s3 += '<div class="mgrid c3">'
    for a, c in [(47, 52), (74, 25), (32, 43), (63, 26)]:
        s3 += f'<div class="abox"><p>{a} + {c} = {b("5em")}</p></div>'
    s3 += '</div>'
    
    # 4: Word problem review (reduced from 3 to 2)
    s4 = '<div class="wp">'
    s4 += '<p class="note">Read carefully. Show your work.</p>'
    s4 += '<div class="mgrid c2">'
    problems = [
        ("A class has 24 boys and 25 girls. The teacher wants to know total students. How many?", 24, 25, "students"),
        ("Jake read 43 pages on Monday and 36 pages on Tuesday. How many pages total?", 43, 36, "pages"),
    ]
    for text, a, c, unit in problems:
        s4 += f'<div class="abox"><p style="font-size:0.95em;">{text}</p>'
        s4 += '<p>' + b("6em") + f' {unit}</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 adding 2-digit numbers?</b></p>'
    s5 += '<div style="display:flex; gap:20px; flex-wrap:wrap;">'
    s5 += '<div style="background:#e8f5e9; padding:10px; border-radius:5px; flex:1; min-width:150px;">'
    s5 += '<p><b>Mental Math (Adding Tens)</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>Column Addition</b></p>'
    s5 += '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'
    s5 += '</div>'
    s5 += '<div style="background:#fff3e0; padding:10px; border-radius:5px; flex:1; min-width:150px;">'
    s5 += '<p><b>Word Problems</b></p>'
    s5 += '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'
    s5 += '</div>'
    s5 += '</div>'
    s5 += '<p style="margin-top:10px;"><b>My favorite strategy for adding 2-digit numbers:</b> ' + bl() + '</p>'
    s5 += '<p><b>One thing I want to practice more:</b> ' + bl() + '</p>'
    s5 += '</div>'
    
    return page(7, "Friday", "Week 7 Review & Self-Check",
        f'''{sec(1, "Mental Math Warm-up", s1)}
{sec(2, "Column Addition Review", s2)}
{sec(3, "Mixed Practice", s3)}
{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 7", "Adding Within 100 (No Regrouping) — Teacher Guide",
        
        # Monday
        tg_section_title("Monday: Adding Tens (Mental Math)") +
        tg_sec(1, "Add 10", ["33, 55, 77, 22"]) +
        tg_sec(2, "Multiples of 10", ["54, 86, 88, 92"]) +
        tg_sec(3, "Number Line", ["55, 87"]) +
        tg_sec(4, "Number Talk", ["34+30 is bigger (adds 3 tens vs 2 tens)", "56+40 is bigger (adds 4 tens vs 1 ten)"]) +
        tg_sec(5, "Challenge", ["95, 83"]) +
        tg_note("Page break"),
        
        # Tuesday
        tg_section_title("Tuesday: Adding 2-Digit Numbers") +
        tg_sec(1, "Add Ones Then Tens", ["68, 88, 78, 77"]) +
        tg_sec(2, "Estimation", ["About 80, actual 90 / About 80, actual 89 / About 70, actual 79"]) +
        tg_sec(3, "Step-by-Step", ["59, 99"]) +
        tg_sec(4, "Strategies", ["77, 87, 89, 88"]) +
        tg_sec(5, "Word Problems", ["57 marbles, 77 books"]) +
        tg_note("Page break"),
        
        # Wednesday
        tg_section_title("Wednesday: Column Addition") +
        tg_sec(1, "Column Addition", ["68, 88, 78, 77"]) +
        tg_sec(2, "More Practice", ["77, 89, 88, 69"]) +
        tg_sec(3, "Three Addends", ["99, 99"]) +
        tg_sec(4, "Find Error", ["68 is correct ✓, 69 is wrong ✗ (should be 79)"]) +
        tg_sec(5, "Create Own", ["Various: 40+47, 50+37, 60+27, etc."]) +
        tg_note("Page break"),
        
        # Thursday
        tg_section_title("Thursday: Word Problems") +
        tg_sec(1, "Word Problems", ["76 shells, 88 books, 87 birds"]) +
        tg_sec(2, "Compare", ["A=79, B=75, A is bigger"]) +
        tg_sec(3, "Two-Step", ["57, 77, 77 stickers"]) +
        tg_sec(4, "Create Own", ["Accept student-created problems"]) +
        tg_note("Page break"),
        
        # Friday
        tg_section_title("Friday: Review & Self-Check") +
        tg_sec(1, "Mental Math", ["50, 90, 90, 70, 90, 90"]) +
        tg_sec(2, "Column Review", ["79, 99, 89, 89"]) +
        tg_sec(3, "Mixed", ["99, 99, 75, 89"]) +
        tg_sec(4, "Word Problems", ["49 students, 79 pages"]) +
        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", "Adding Tens (Mental Math)"),
        (tuesday, "Tuesday", "Adding 2-Digit Numbers"),
        (wednesday, "Wednesday", "Column Addition"),
        (thursday, "Thursday", "Addition Word Problems"),
        (friday, "Friday", "Week 7 Review & Self-Check"),
    ]
    
    # Generate student worksheets
    for lesson_func, day, title in days:
        html = lesson_func()
        fname = f"Week_7_{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_7_Teacher_Guide.html")
    with open(path, "w") as f:
        f.write(html)
    pdf_path = os.path.join(WEEK, "Week_7_Teacher_Guide.pdf")
    HTML(filename=path).write_pdf(pdf_path)
    print(f"Generated: {pdf_path}")
    
    print("\nWeek 7 (rewritten to new standard) complete!")
