#!/usr/bin/env python3
"""
Week 4: Addition Facts to 20
Phase 1: Number Sense & Operations

Curriculum: Fluency drills; number bonds; making 10 strategy
Standard: 2.OA.B.2 — Fluently add within 20 using mental strategies.

New Standard (7 principles):
1. Reduced drill (4-6 problems per section, "reduced from" noted)
2. Estimation before calculating (more/less than 10 or 15 — Tue, Fri)
3. Multiple strategies ("show two different ways" — Mon, Wed)
4. Better word problems (reasoning over keywords — Wed, Thu, Fri)
5. Create Your Own open-ended challenge (Wed, Thu)
6. Number Talks — explain WITHOUT calculating (Mon, Thu)
7. Friday self-check with emoji + "One thing I learned"
"""

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_multi, tg_sec, tg_note, tg_section_title,
)
from activity_builders import (
    build_number_bonds,
    build_make_10_strategy,
    build_pairs_to_make,
    build_missing_addend,
    build_challenge_box,
)

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


# ═══════════════════════════════════════════════════
# MONDAY — Number Bonds
# ═══════════════════════════════════════════════════
def monday():
    # 1: Fluency warmup — pairs that make 10
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — What makes 10?</p>'\
         '<div class="mgrid c4">'
    for a in [7, 4, 9, 2]:
        s1 += f'<div class="abox"><p>{a} + {b("3em")} = 10</p></div>'
    s1 += '</div></div>'

    # 2: Number bonds of 10 (visual)
    s2 = build_number_bonds({
        "whole": 10,
        "pairs": [(6, None), (3, None), (8, None), (5, None)],
        "note": "A number bond shows the WHOLE and its two PARTS. Fill in the missing part of 10.",
    })

    # 3: Number bonds to teen numbers (reduced from 8 to 4)
    s3 = '<p class="note">Now the whole is bigger than 10. What is the missing part?</p>'\
         '<div class="mgrid c2">'
    for whole, part in [(14, 9), (13, 8), (15, 7), (12, 6)]:
        s3 += f'<div class="abox" style="text-align:center;">'\
              f'<p style="font-size:1.2em;"><b>{whole}</b></p>'\
              f'<p>{part} and {b("3em")}</p>'\
              f'<p style="font-size:11px; color:#666;">{part} + {b("2em")} = {whole}</p></div>'
    s3 += '</div>'

    # 4: Number Talk — explain WITHOUT calculating
    s4 = '<div class="abox" style="background:#e3f2fd;">'\
         '<p><b>Number Talk</b> — Explain WITHOUT calculating.</p>'\
         '<div class="mgrid c2">'
    s4 += '<div class="abox"><p>Which sum is bigger?</p><p>9 + 6  or  9 + 7</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '<div class="abox"><p>Which sum is bigger?</p><p>8 + 5  or  9 + 5</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '</div></div>'

    # 5: Challenge — show two different ways
    s5 = '<div class="abox" style="background:#f3e5f5;">'\
         '<p><b>Challenge</b> — Show two different ways to solve each fact.</p>'\
         '<p style="font-size:11px; color:#666;">Try: (1) a number bond, (2) counting on, or (3) making 10.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(8, 7), (9, 6)]:
        s5 += f'<div class="abox"><p><b>{a} + {c} = </b>{b("4em")}</p>'\
              '<p style="font-size:11px; color:#666;">Strategy 1: ' + bw() + '</p>'\
              '<p style="font-size:11px; color:#666;">Strategy 2: ' + bw() + '</p></div>'
    s5 += '</div></div>'

    return page(4, "Monday", "Number Bonds",
        f'''{sec(1, "Warm-up: Make 10", s1)}
{sec(2, "Number Bonds of 10", s2)}
{sec(3, "Number Bonds to 20", s3)}
{sec(4, "Number Talk: Which Sum is Bigger?", s4)}
{sec(5, "Challenge: Show Two Different Ways", s5)}''')


# ═══════════════════════════════════════════════════
# TUESDAY — Making 10 Strategy
# ═══════════════════════════════════════════════════
def tuesday():
    # 1: Fluency warmup — 10 plus a number
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — 10 plus a number is easy!</p>'\
         '<div class="mgrid c4">'
    for a in [3, 6, 8, 5]:
        s1 += f'<div class="abox"><p>10 + {a} = {b("3em")}</p></div>'
    s1 += '</div></div>'

    # 2: Make-a-10 strategy (guided, reduced from 6 to 4)
    s2 = build_make_10_strategy({
        "problems": [(9, 4), (8, 6), (9, 7), (8, 5)],
        "show_steps": True,
        "note": "Make a 10 first! Break apart the second number: give some to make 10, then add the rest.",
    })

    # 3: Estimate First — more or less than 10?
    s3 = '<div class="abox" style="background:#fff3e0;">'\
         '<p><b>Estimate First!</b> BEFORE solving, circle: is the sum MORE or LESS than 10? Then solve.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(7, 6), (4, 3), (8, 9), (5, 4)]:
        s3 += f'<div class="abox"><p><b>{a} + {c}</b></p>'\
              '<p>more than 10  /  less than 10</p>'\
              f'<p>Actual: {b("3em")}</p></div>'
    s3 += '</div></div>'

    # 4: Unknowns in equations — missing addends
    s4 = build_missing_addend({
        "problems": [(6, 15), (7, 13), (9, 17), (6, 14)],
        "note": "Find the missing number. Think: what goes with this part to make the whole?",
    })

    # 5: Step-by-step make-10 (write every step)
    s5 = '<p class="note">Write each step of the make-10 strategy.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(7, 8), (9, 6)]:
        need = 10 - a
        rest = c - need
        s5 += f'<div class="abox"><p><b>{a} + {c}</b></p>'\
              f'<p>{a} + {need} = ' + b("3em") + '</p>'\
              f'<p>10 + {rest} = ' + b("3em") + '</p>'\
              '<p><b>Answer: </b>' + b("4em") + '</p></div>'
    s5 += '</div>'

    return page(4, "Tuesday", "Making 10 Strategy",
        f'''{sec(1, "Warm-up: 10 Plus a Number", s1)}
{sec(2, "Make a 10 to Add", s2)}
{sec(3, "Estimate First!", s3)}
{sec(4, "Find the Missing Number", s4)}
{sec(5, "Step-by-Step Make-10", s5)}''')


# ═══════════════════════════════════════════════════
# WEDNESDAY — Doubles, Near Doubles & Mixed Facts
# ═══════════════════════════════════════════════════
def wednesday():
    # 1: Fluency warmup — doubles
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Doubles! Say them fast.</p>'\
         '<div class="mgrid c4">'
    for a in [6, 7, 8, 9]:
        s1 += f'<div class="abox"><p>{a} + {a} = {b("3em")}</p></div>'
    s1 += '</div></div>'

    # 2: Near doubles (reduced from 6 to 4)
    s2 = '<p class="note">A near double is a double plus 1. Example: 6 + 7 = 6 + 6 + 1 = 13.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(6, 7), (7, 8), (8, 9), (5, 6)]:
        s2 += f'<div class="abox"><p><b>{a} + {c} = </b>{b("3em")}</p>'\
              f'<p style="font-size:11px; color:#666;">Double: {a} + {a} = {b("2em")}, then + 1 = {b("2em")}</p></div>'
    s2 += '</div>'

    # 3: Word problems — reasoning about situations
    s3 = '<div class="wp">'\
         '<p class="note">Read carefully. Think about what is happening. Draw if it helps!</p>'\
         '<div class="mgrid c2">'
    problems = [
        ("Maya found 8 shells at the beach in the morning. After lunch she found 7 more shells near the rocks. How many shells did Maya find in all?", "shells"),
        ("There were 9 birds sitting on the fence. Then 5 more birds landed next to them. How many birds are on the fence now?", "birds"),
    ]
    for text, unit in problems:
        s3 += f'<div class="abox"><p style="font-size:0.95em;">{text}</p>'\
              '<p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p>'\
              '<p>' + b("5em") + f' {unit}</p></div>'
    s3 += '</div></div>'

    # 4: Find the error
    s4 = '<div class="abox">'\
         '<p class="note">One of these has a mistake. Find it, explain the error, and fix it.</p>'\
         '<div class="mgrid c2">'
    s4 += '<div class="abox"><p style="text-align:center; font-size:1.2em;">9 + 6 = 14</p><p>✓ or ✗?</p><p style="font-size:11px;">Explain: ' + bw() + '</p><p style="font-size:11px;">Correct answer: ' + b("3em") + '</p></div>'
    s4 += '<div class="abox"><p style="text-align:center; font-size:1.2em;">7 + 7 = 14</p><p>✓ or ✗?</p><p style="font-size:11px;">Explain: ' + bw() + '</p><p style="font-size:11px;">Correct answer: ' + b("3em") + '</p></div>'
    s4 += '</div></div>'

    # 5: Challenge — Create your own fact
    s5 = '<div class="abox" style="background:#f3e5f5;">'\
         '<p><b>Create Your Own</b></p>'\
         '<p>Make an addition fact with a sum between 11 and 20. Solve it two different ways.</p>'\
         '<p style="text-align:center; font-size:1.3em;">' + b("3em") + ' + ' + b("3em") + ' = ' + b("3em") + '</p>'\
         '<p style="font-size:11px; color:#666;">Way 1 (make 10 or doubles): ' + bw() + '</p>'\
         '<p style="font-size:11px; color:#666;">Way 2 (a different strategy): ' + bw() + '</p>'\
         '</div>'

    return page(4, "Wednesday", "Doubles & Near Doubles",
        f'''{sec(1, "Warm-up: Doubles", s1)}
{sec(2, "Near Doubles", s2)}
{sec(3, "Word Problems", s3)}
{sec(4, "Find the Error", s4)}
{sec(5, "Challenge: Create Your Own", s5)}''')


# ═══════════════════════════════════════════════════
# THURSDAY — Word Problems with Facts to 20
# ═══════════════════════════════════════════════════
def thursday():
    # 1: Fluency warmup — mixed facts
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Solve in your head.</p>'\
         '<div class="mgrid c4">'
    for expr in ["9 + 8", "6 + 5", "7 + 4", "8 + 8"]:
        s1 += f'<div class="abox"><p>{expr} = {b("3em")}</p></div>'
    s1 += '</div></div>'

    # 2: Better word problems — add-to, missing-addend, change-unknown (reduced from 5 to 3)
    s2 = '<div class="wp">'\
         '<p class="note">Read carefully. Think about what is happening in the story. Draw if it helps!</p>'\
         '<div class="mgrid c2">'
    problems = [
        ("Leo had 7 toy cars. For his birthday, his grandma gave him 9 more. How many toy cars does Leo have now?", "cars"),
        ("Ava needs 15 beads to finish her bracelet. She has 8 beads so far. How many more beads does Ava need?", "beads"),
        ("There were 6 frogs on a log. More frogs jumped on. Now there are 14 frogs. How many frogs jumped on?", "frogs"),
    ]
    for text, unit in problems:
        s2 += f'<div class="abox"><p style="font-size:0.95em;">{text}</p>'\
              '<p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p>'\
              '<p>' + b("5em") + f' {unit}</p></div>'
    s2 += '</div></div>'

    # 3: Two-step word problem
    s3 = '<div class="abox">'\
         '<p class="note">Solve step by step. Write each answer as you go.</p>'\
         '<div class="abox"><p>Sam picked 8 apples in the morning and 6 apples in the afternoon. Then he gave 5 apples to his grandma. How many apples does Sam have left?</p>'\
         '<p>Step 1: ' + b("6em") + '</p>'\
         '<p>Step 2: ' + b("6em") + '</p>'\
         '<p><b>Answer: </b>' + b("4em") + ' apples</p></div></div>'

    # 4: Number Talk — compare WITHOUT calculating
    s4 = '<div class="abox" style="background:#e3f2fd;">'\
         '<p><b>Number Talk</b> — Explain WITHOUT calculating.</p>'\
         '<div class="mgrid c2">'
    s4 += '<div class="abox"><p>A: 8 + 7</p><p>B: 7 + 8</p><p>Same or different? Why?</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '<div class="abox"><p>A: 9 + 5</p><p>B: 10 + 4</p><p>Same or different? Why?</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '</div></div>'

    # 5: Create your own word problem
    s5 = '<div class="abox" style="background:#f3e5f5;">'\
         '<p><b>Create Your Own Word Problem</b></p>'\
         '<p>Write an addition word problem about something you like (animals, sports, snacks, games). The sum must be 20 or less. Then solve it.</p>'\
         '<p style="min-height:60px; border-bottom:1px solid #333;"></p>'\
         '<p style="min-height:30px; border-bottom:1px solid #333;"></p>'\
         '<p style="font-size:11px;">My thinking: ' + bw() + '</p>'\
         '<p>Answer: ' + bl() + '</p>'\
         '</div>'

    return page(4, "Thursday", "Word Problems with Facts to 20",
        f'''{sec(1, "Warm-up: Mixed Facts", s1)}
{sec(2, "Word Problems: Think About What Is Happening", s2)}
{sec(3, "Two-Step Problem", s3)}
{sec(4, "Number Talk: Same or Different?", s4)}
{sec(5, "Challenge: Create Your Own", s5)}''')


# ═══════════════════════════════════════════════════
# FRIDAY — Review & Self-Check
# ═══════════════════════════════════════════════════
def friday():
    # 1: Fluency warmup
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Go fast!</p>'\
         '<div class="mgrid c4">'
    for expr in ["9 + 4", "8 + 8", "7 + 6", "10 + 7"]:
        s1 += f'<div class="abox"><p>{expr} = {b("3em")}</p></div>'
    s1 += '</div></div>'

    # 2: Estimate First — more or less than 15?
    s2 = '<div class="abox" style="background:#fff3e0;">'\
         '<p><b>Estimate First!</b> BEFORE solving, circle: is the sum MORE or LESS than 15? Then solve.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(9, 7), (6, 6), (8, 9), (7, 5)]:
        s2 += f'<div class="abox"><p><b>{a} + {c}</b></p>'\
              '<p>more than 15  /  less than 15</p>'\
              f'<p>Actual: {b("3em")}</p></div>'
    s2 += '</div></div>'

    # 3: Mixed fluency review (reduced from 10 to 6)
    s3 = '<p class="note">Use any strategy you like: make 10, doubles, counting on.</p>'\
         '<div class="mgrid c3">'
    for a, c in [(9, 6), (8, 4), (7, 7), (5, 9), (8, 6), (9, 9)]:
        s3 += f'<div class="abox"><p>{a} + {c} = {b("4em")}</p></div>'
    s3 += '</div>'

    # 4: Word problem review
    s4 = '<div class="wp">'\
         '<p class="note">Read carefully. Show your work.</p>'\
         '<div class="mgrid c2">'
    problems = [
        ("The class read 9 books in the first week and 8 books in the second week. How many books did the class read in all?", "books"),
        ("Nina scored 14 points in the game. She scored 6 points in the first half. How many points did she score in the second half?", "points"),
    ]
    for text, unit in problems:
        s4 += f'<div class="abox"><p style="font-size:0.95em;">{text}</p>'\
              '<p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p>'\
              '<p>' + b("5em") + f' {unit}</p></div>'
    s4 += '</div></div>'

    # 5: Number bonds review
    s5a = '<p class="note">Fill in the missing part.</p>'\
          '<div class="mgrid c3">'
    for whole, part in [(16, 9), (14, 8), (13, 7)]:
        s5a += f'<div class="abox" style="text-align:center;"><p><b>{whole}</b></p><p>{part} and {b("3em")}</p></div>'
    s5a += '</div>'

    # 6: Self-check with emoji reflection
    s5b = '<div class="selfcheck">'\
          '<p><b>Self-Check: How do you feel about addition facts to 20?</b></p>'\
          '<div style="display:flex; gap:20px; flex-wrap:wrap;">'\
          '<div style="background:#fff3e0; padding:10px; border-radius:5px; flex:1; min-width:150px;">'\
          '<p><b>Number Bonds</b></p>'\
          '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'\
          '</div>'\
          '<div style="background:#e3f2fd; padding:10px; border-radius:5px; flex:1; min-width:150px;">'\
          '<p><b>Making 10 to Add</b></p>'\
          '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'\
          '</div>'\
          '<div style="background:#f3e5f5; padding:10px; border-radius:5px; flex:1; min-width:150px;">'\
          '<p><b>Doubles & Near Doubles</b></p>'\
          '<p>😊 I got it!  |  😐 Getting there  |  😟 Need help</p>'\
          '</div>'\
          '</div>'\
          '<p style="margin-top:10px;"><b>One thing I learned this week:</b> ' + bl() + '</p>'\
          '<p><b>One thing I want to practice more:</b> ' + bl() + '</p>'\
          '<p><b>My favorite strategy for adding:</b> ' + bl() + '</p>'\
          '</div>'

    return page(4, "Friday", "Week 4 Review & Self-Check",
        f'''{sec(1, "Warm-up: Mixed Facts", s1)}
{sec(2, "Estimate First!", s2)}
{sec(3, "Fluency Review", s3)}
{sec(4, "Word Problems", s4)}
{sec(5, "Number Bonds Review", s5a)}
{sec(6, "Self-Check & Reflection", s5b)}''')


# ═══════════════════════════════════════════════════
# TEACHER GUIDE — Combined for all days
# ═══════════════════════════════════════════════════
def teacher_guide():
    """Generate combined teacher guide for all 5 days."""
    return tg_page_multi(
        "Week 4", "Addition Facts to 20 — Teacher Guide",

        # Monday
        tg_section_title("Monday: Number Bonds") +
        tg_sec(1, "Warm-up: Make 10", ["7+3, 4+6, 9+1, 2+8"]) +
        tg_sec(2, "Number Bonds of 10", ["6 and 4, 3 and 7, 8 and 2, 5 and 5"]) +
        tg_sec(3, "Number Bonds to 20", ["14: 9 and 5; 13: 8 and 5; 15: 7 and 8; 12: 6 and 6"]) +
        tg_sec(4, "Number Talk", ["9+7 is bigger (adding more to the same 9)", "9+5 is bigger (bigger first addend, same 5)"]) +
        tg_sec(5, "Challenge Two Ways", ["8+7=15, 9+6=15 — accept any two valid strategies (make 10, near doubles, counting on)"]) +
        tg_note("Page break"),

        # Tuesday
        tg_section_title("Tuesday: Making 10 Strategy") +
        tg_sec(1, "Warm-up: 10 Plus", ["13, 16, 18, 15"]) +
        tg_sec(2, "Make a 10", ["9+4: 9+1=10, 10+3=13 | 8+6: 8+2=10, 10+4=14 | 9+7: 9+1=10, 10+6=16 | 8+5: 8+2=10, 10+3=13"]) +
        tg_sec(3, "Estimate First", ["7+6: more (13), 4+3: less (7), 8+9: more (17), 5+4: less (9)"]) +
        tg_sec(4, "Missing Numbers", ["9+6=15, 6+7=13, 8+9=17, 8+6=14"]) +
        tg_sec(5, "Step-by-Step Make-10", ["7+8: 7+3=10, 10+5=15, answer 15 | 9+6: 9+1=10, 10+5=15, answer 15"]) +
        tg_note("Page break"),

        # Wednesday
        tg_section_title("Wednesday: Doubles & Near Doubles") +
        tg_sec(1, "Warm-up: Doubles", ["12, 14, 16, 18"]) +
        tg_sec(2, "Near Doubles", ["6+7=13 (12+1), 7+8=15 (14+1), 8+9=17 (16+1), 5+6=11 (10+1)"]) +
        tg_sec(3, "Word Problems", ["15 shells (8+7), 14 birds (9+5)"]) +
        tg_sec(4, "Find the Error", ["9+6=14 is WRONG — should be 15 (9+1=10, 10+5=15)", "7+7=14 is CORRECT"]) +
        tg_sec(5, "Create Own", ["Accept any fact with sum 11-20 solved two valid ways"]) +
        tg_note("Page break"),

        # Thursday
        tg_section_title("Thursday: Word Problems with Facts to 20") +
        tg_sec(1, "Warm-up", ["17, 11, 11, 16"]) +
        tg_sec(2, "Word Problems", ["16 cars (7+9)", "7 beads (8+7=15, so 15−8=7)", "8 frogs (6+8=14, so 14−6=8)"]) +
        tg_sec(3, "Two-Step", ["Step 1: 8+6=14, Step 2: 14−5=9 apples"]) +
        tg_sec(4, "Number Talk", ["Same — 8+7=7+8 (order doesn't change the sum; both 15)", "Same — move 1 from 5 to 9: 9+5=10+4 (both 14)"]) +
        tg_sec(5, "Create Own", ["Accept student-created addition problems with sum ≤ 20"]) +
        tg_note("Page break"),

        # Friday
        tg_section_title("Friday: Review & Self-Check") +
        tg_sec(1, "Warm-up", ["13, 16, 13, 17"]) +
        tg_sec(2, "Estimate First", ["9+7: more (16), 6+6: less (12), 8+9: more (17), 7+5: less (12)"]) +
        tg_sec(3, "Fluency Review", ["15, 12, 14, 14, 14, 18"]) +
        tg_sec(4, "Word Problems", ["17 books (9+8)", "8 points (6+8=14, so 14−6=8)"]) +
        tg_sec(5, "Number Bonds Review", ["16: 9 and 7; 14: 8 and 6; 13: 7 and 6"]) +
        tg_sec(6, "Self-Check", ["Accept student self-assessment and reflection"])
    )


# ═══════════════════════════════════════════════════
# GENERATE
# ═══════════════════════════════════════════════════
if __name__ == "__main__":
    os.makedirs(WEEK, exist_ok=True)
    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", "Number Bonds"),
        (tuesday, "Tuesday", "Making 10 Strategy"),
        (wednesday, "Wednesday", "Doubles & Near Doubles"),
        (thursday, "Thursday", "Word Problems with Facts to 20"),
        (friday, "Friday", "Week 4 Review & Self-Check"),
    ]

    for lesson_func, day, title in days:
        html = lesson_func()
        fname = f"Week_4_{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}")

    html = teacher_guide()
    path = os.path.join(WEEK, "Week_4_Teacher_Guide.html")
    with open(path, "w") as f:
        f.write(html)
    pdf_path = os.path.join(WEEK, "Week_4_Teacher_Guide.pdf")
    HTML(filename=path).write_pdf(pdf_path)
    print(f"Generated: {pdf_path}")

    print("\nWeek 4 (Addition Facts to 20) complete!")