#!/usr/bin/env python3
"""
Week 19: Money — Adding & Making Change
Phase 3: Measurement, Time & Money
Standards: 2.MD.C.8 (solve word problems involving money, $ and ¢ symbols)

New Standard:
- Reduced drill (40% fewer problems)
- Estimation before calculating (about how much together? enough money?)
- Multiple strategies encouraged (count up to make change vs. subtract)
- Better word problems (real store transactions, reasoning over keywords)
- Real challenges (open-ended thinking — plan a purchase)
- Number talks (compare totals & change without calculating)
- Friday self-check with reflection
- Fact fluency warmup daily (coin values, make-a-dollar facts)
- Word problems every day
"""

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,
    coin_svg, col_add, col_sub,
)
from activity_builders import (
    build_money_adding,
)

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


# ═══════════════════════════════════════════════════
# MONDAY — Adding Two Money Amounts
# ═══════════════════════════════════════════════════
def monday():
    # 1: Fluency warmup — coin value facts (review from Week 18)
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Quick coin facts.</p>'\
         '<div class="mgrid c3">'
    for q in ["2 quarters = ___¢", "3 dimes = ___¢", "4 nickels = ___¢", "quarter + dime = ___¢"]:
        s1 += f'<div class="abox"><p>{q}</p></div>'
    s1 += '</div></div>'

    # 2: Adding two prices — guided intro
    s2 = '<p class="note">Adding money works just like adding numbers! 25¢ + 30¢: add the cents like 25 + 30 = 55, so 55¢. '\
         'If your total reaches 100¢, that\'s $1.00!</p>'
    s2 += '<div class="mgrid c2">'
    s2 += '<div class="abox"><p><b>Example:</b> A pencil costs 25¢ and an eraser costs 30¢.</p><p>25¢ + 30¢ = <b>55¢</b> together.</p></div>'
    s2 += '<div class="abox"><p><b>Example:</b> A sticker costs 60¢ and a card costs 40¢.</p><p>60¢ + 40¢ = 100¢ = <b>$1.00</b>!</p></div>'
    s2 += '</div>'

    # 3: Add the prices (reduced from 8 to 4)
    s3 = '<p class="note">Add each pair of prices.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(25, 30), (15, 40), (35, 25), (45, 20)]:
        s3 += f'<div class="abox"><p>{a}¢ + {c}¢ = {b("4em")}¢</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>A: 25¢ + 25¢ &nbsp; B: 25¢ + 35¢</p><p>Which total is bigger? How do you know without adding?</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '<div class="abox"><p>Toy A costs 49¢. Toy B costs 51¢. About how much do they cost together — is it about $1? Why?</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '</div></div>'

    # 5: Word problem
    s5 = '<div class="wp">'\
         '<p class="note">Read carefully. Think about what is happening.</p>'\
         '<div class="abox"><p style="font-size:0.95em;">At the school store, Nora buys a bookmark for 35¢ and a pencil grip for 25¢. '\
         'How much does she spend in all? Show your thinking.</p>'\
         '<p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p>'\
         '<p>Total: ' + b("4em") + '¢</p></div></div>'

    return page(19, "Monday", "Adding Money Amounts",
        f'''{sec(1, "Warm-up: Coin Facts", s1)}
{sec(2, "Adding Prices Together", s2)}
{sec(3, "Add the Prices", s3)}
{sec(4, "Number Talk: Compare Totals", s4)}
{sec(5, "Word Problem", s5)}''')


# ═══════════════════════════════════════════════════
# TUESDAY — Estimation + Column Adding with Money
# ═══════════════════════════════════════════════════
def tuesday():
    # 1: Fluency warmup — make a dollar
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — How much more to make $1.00?</p>'\
         '<div class="mgrid c3">'
    for n in [75, 50, 90, 25]:
        s1 += f'<div class="abox"><p>{n}¢ + {b("3em")}¢ = $1</p></div>'
    s1 += '</div></div>'

    # 2: Estimate First! — enough money?
    s2 = '<div class="abox" style="background:#fff3e0;">'\
         '<p><b>Estimate First!</b> Round each price to the nearest ten. Estimate the total, then add exactly.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(38, 21), (47, 32), (19, 43), (52, 28)]:
        at = (a + 5) // 10 * 10
        ct = (c + 5) // 10 * 10
        s2 += f'<div class="abox"><p><b>{a}¢ + {c}¢</b></p>'\
              f'<p>Round: {at}¢ + {ct}¢</p>'\
              f'<p>Estimate: {b("4em")}¢</p>'\
              f'<p>Actual: {b("4em")}¢</p></div>'
    s2 += '</div></div>'

    # 3: Column addition with money (reduced from 6 to 4)
    s3 = '<p class="note">Line up the cents and add — just like column addition!</p>'
    s3 += '<div class="mgrid c2">'
    for a, c in [(38, 21), (47, 32), (19, 43), (52, 28)]:
        s3 += f'<div class="abox">{col_add(a, c)}<p style="text-align:center; font-size:11px;">answer in ¢</p></div>'
    s3 += '</div>'

    # 4: Two items from the store (reduced from 4 to 2)
    s4 = '<div class="abox">'\
         '<p class="note">Store prices: apple 30¢ &nbsp;|&nbsp; juice 45¢ &nbsp;|&nbsp; cookie 25¢ &nbsp;|&nbsp; muffin 55¢</p>'\
         '<div class="mgrid c2">'
    combos = [("an apple and a juice", "30¢ + 45¢"), ("a cookie and a muffin", "25¢ + 55¢")]
    for what, expr in combos:
        s4 += f'<div class="abox"><p>How much for {what}?</p><p>{expr} = {b("4em")}¢</p></div>'
    s4 += '</div></div>'

    # 5: Word problem
    s5 = '<div class="wp">'\
         '<p class="note">Read carefully. Think about what is happening.</p>'\
         '<div class="abox"><p style="font-size:0.95em;">Eli has 80¢. He wants to buy a juice (45¢) and a cookie (25¢). '\
         'Estimate first: does he have enough? Then add exactly to check.</p>'\
         '<p style="font-size:11px;">Estimate: ' + bw() + '</p>'\
         '<p>Exact total: ' + b("4em") + '¢ &nbsp; Enough? ' + b("3em") + '</p></div></div>'

    return page(19, "Tuesday", "Estimating and Adding Money",
        f'''{sec(1, "Warm-up: Make a Dollar", s1)}
{sec(2, "Estimate First!", s2)}
{sec(3, "Column Adding with Cents", s3)}
{sec(4, "Shopping for Two Items", s4)}
{sec(5, "Word Problem", s5)}''')


# ═══════════════════════════════════════════════════
# WEDNESDAY — Making Change (Count Up!)
# ═══════════════════════════════════════════════════
def wednesday():
    # 1: Fluency warmup
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Jump to the next ten.</p>'\
         '<div class="mgrid c3">'
    for n in [37, 62, 85, 41]:
        s1 += f'<div class="abox"><p>{n} + {b("3em")} = {((n // 10) + 1) * 10}</p></div>'
    s1 += '</div></div>'

    # 2: What is change? — guided, with count-up strategy
    s2 = '<p class="note"><b>Change</b> is the money you get back when you pay more than the price. '\
         '<b>Strategy: count UP</b> from the price to what you paid.</p>'\
         '<div class="abox"><p><b>Example:</b> A toy costs 35¢. You pay with 2 quarters (50¢).</p>'\
         '<p>Count up: 35¢ → 40¢ (that\'s 5¢) → 50¢ (that\'s 10¢ more). Change = 5 + 10 = <b>15¢</b>.</p></div>'

    # 3: Make change (reduced from 8 to 4)
    s3 = '<p class="note">Count up from the price to the amount paid. Write the change.</p>'\
         '<div class="mgrid c2">'
    for price, paid in [(40, 50), (65, 75), (30, 50), (55, 100)]:
        paid_label = "$1.00" if paid == 100 else f"{paid}¢"
        s3 += f'<div class="abox"><p>Price: {price}¢ &nbsp; Paid: {paid_label}</p>'\
              f'<p>Change: {b("4em")}¢</p></div>'
    s3 += '</div>'

    # 4: Two Ways — change by counting up AND subtracting
    s4 = '<div class="abox">'\
         '<p class="note"><b>Two Ways</b> — Find the change two different ways. Do they match?</p>'\
         '<div class="mgrid c2">'
    for price, paid in [(45, 60), (25, 50)]:
        s4 += f'<div class="abox"><p><b>Price {price}¢, paid {paid}¢</b></p>'\
              f'<p style="font-size:11px;">Strategy 1 — count up: ' + bw() + '</p>'\
              f'<p style="font-size:11px;">Strategy 2 — subtract {paid} − {price}: ' + b("4em") + '</p>'\
              f'<p>Change: {b("4em")}¢</p></div>'
    s4 += '</div></div>'

    # 5: Challenge — Create Your Own
    s5 = '<div class="abox" style="background:#f3e5f5;">'\
         '<p><b>Create Your Own</b></p>'\
         '<p>Invent an item for your own store. Give it a price under 50¢. A customer pays with 2 quarters. '\
         'Draw your item, write the price, and figure out the change.</p>'\
         '<p style="min-height:60px; border:1px dashed #999; border-radius:4px; padding:6px; font-size:11px; color:#999;">Draw your item here</p>'\
         '<p>Price: ' + b("3em") + '¢ &nbsp; Paid: 50¢ &nbsp; Change: ' + b("3em") + '¢</p>'\
         '<p style="font-size:11px; color:#666;">Strategy I used: ' + bw() + '</p>'\
         '</div>'

    return page(19, "Wednesday", "Making Change",
        f'''{sec(1, "Warm-up: Next Ten", s1)}
{sec(2, "What Is Change? Count Up!", s2)}
{sec(3, "Make the Change", s3)}
{sec(4, "Two Ways to Find Change", s4)}
{sec(5, "Challenge: Create Your Own", s5)}''')


# ═══════════════════════════════════════════════════
# THURSDAY — Store Transactions (Word Problems)
# ═══════════════════════════════════════════════════
def thursday():
    # 1: Fluency warmup
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Change from a quarter (25¢).</p>'\
         '<div class="mgrid c3">'
    for price in [20, 15, 10, 5]:
        s1 += f'<div class="abox"><p>Price {price}¢ → change {b("3em")}¢</p></div>'
    s1 += '</div></div>'

    # 2: Better word problems — real transactions (reduced from 5 to 3)
    s2 = '<div class="wp">'\
         '<p class="note">Read carefully. Think about what is happening in the situation. Draw coins if it helps!</p>'\
         '<div class="mgrid c2">'
    problems = [
        "Maya buys a hair clip for 40¢ and a ring for 35¢ at the craft fair. She pays with a $1 bill. How much does she spend, and how much change does she get?",
        "Owen has 3 quarters. He buys a bouncy ball for 55¢. Does he have enough? If yes, how much change should he get?",
        "Two friends each buy a 30¢ snack. They pay together with 3 quarters. Is that enough money? Explain.",
    ]
    for text 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>Answer: ' + bw() + '</p></div>'
    s2 += '</div></div>'

    # 3: Two-step transaction
    s3 = '<div class="abox">'\
         '<p class="note">Solve step by step. Write each answer as you go.</p>'\
         '<div class="abox"><p style="font-size:0.95em;">Ivy starts with 90¢. She buys a sticker for 25¢. '\
         'Then she buys a lollipop for 30¢. How much money does Ivy have left?</p>'\
         '<p>Step 1: 90¢ − 25¢ = ' + b("4em") + '¢</p>'\
         '<p>Step 2: ' + b("4em") + '¢ − 30¢ = ' + b("4em") + '¢</p>'\
         '<p><b>Ivy has ' + b("4em") + '¢ left.</b></p></div></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>A toy costs 48¢. Jen pays 50¢, Kim pays $1. Who gets MORE change? How do you know without figuring out either amount?</p><p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '<div class="abox"><p>Two items cost 45¢ and 45¢. Will a $1 bill be enough? Reason without adding exactly.</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 a store word problem where someone buys something and gets change. 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>Answer: ' + bl() + '</p>'\
         '</div>'

    return page(19, "Thursday", "Store Transactions",
        f'''{sec(1, "Warm-up: Change from a Quarter", s1)}
{sec(2, "Word Problems: Think About What Is Happening", s2)}
{sec(3, "Two-Step Transaction", s3)}
{sec(4, "Number Talk: Reasoning About Change", 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> — Money facts. Go fast!</p>'\
         '<div class="mgrid c3">'
    for q in ["50¢ + 50¢ = $___", "75¢ + 25¢ = $___", "60¢ + 20¢ = ___¢", "30¢ + 30¢ = ___¢"]:
        s1 += f'<div class="abox"><p>{q}</p></div>'
    s1 += '</div></div>'

    # 2: Estimate First! — review
    s2 = '<div class="abox" style="background:#fff3e0;">'\
         '<p><b>Estimate First!</b> Round to tens, estimate the total, then add exactly.</p>'\
         '<div class="mgrid c2">'
    for a, c in [(29, 42), (53, 18), (36, 37), (41, 24)]:
        at = (a + 5) // 10 * 10
        ct = (c + 5) // 10 * 10
        s2 += f'<div class="abox"><p><b>{a}¢ + {c}¢</b></p>'\
              f'<p>Estimate ({at} + {ct}): {b("4em")}¢</p>'\
              f'<p>Actual: {b("4em")}¢</p></div>'
    s2 += '</div></div>'

    # 3: Mixed money review — add and make change (reduced from 8 to 4)
    s3 = '<p class="note">Use any strategy you prefer — count up or subtract.</p>'\
         '<div class="mgrid c2">'
    s3 += f'<div class="abox"><p>35¢ + 45¢ = {b("4em")}¢</p></div>'
    s3 += f'<div class="abox"><p>Price 60¢, paid 75¢. Change: {b("4em")}¢</p></div>'
    s3 += f'<div class="abox"><p>20¢ + 55¢ = {b("4em")}¢</p></div>'
    s3 += f'<div class="abox"><p>Price 45¢, paid $1.00. Change: {b("4em")}¢</p></div>'
    s3 += '</div>'

    # 4: Word problem review
    s4 = '<div class="wp">'\
         '<p class="note">Read carefully. Show your thinking.</p>'\
         '<div class="mgrid c2">'
    problems = [
        "Ben buys a granola bar for 55¢ and pays with 3 quarters. How much change does he get?",
        "Ella has 50¢. Pencils cost 20¢ each. Can she buy two pencils? How much will she have left?",
    ]
    for text in problems:
        s4 += f'<div class="abox"><p style="font-size:0.95em;">{text}</p>'\
              '<p style="font-size:11px;">My thinking: ' + bw() + '</p>'\
              '<p>Answer: ' + bw() + '</p></div>'
    s4 += '</div></div>'

    # 5: Self-check with emoji reflection
    s5 = '<div class="selfcheck">'\
         '<p><b>Self-Check: How do you feel about adding money and making change?</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>Adding Money Amounts</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 Change (Count Up)</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>Store Word Problems</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 making change:</b> ' + bl() + '</p>'\
         '</div>'

    return page(19, "Friday", "Week 19 Review & Self-Check",
        f'''{sec(1, "Warm-up: Money Facts", s1)}
{sec(2, "Estimate First!", s2)}
{sec(3, "Add & Make Change Review", s3)}
{sec(4, "Word Problems", s4)}
{sec(5, "Self-Check & Reflection", s5)}''')


# ═══════════════════════════════════════════════════
# TEACHER GUIDE
# ═══════════════════════════════════════════════════
def teacher_guide():
    return tg_page_multi(
        "Week 19", "Money: Adding & Change — Teacher Guide",

        tg_section_title("Monday: Adding Money Amounts") +
        tg_sec(1, "Warm-up coin facts", ["50¢, 30¢, 20¢, 35¢"]) +
        tg_sec(2, "Adding Prices (guided)", ["Read together"]) +
        tg_sec(3, "Add the Prices", ["55¢, 55¢, 60¢, 65¢"]) +
        tg_sec(4, "Number Talk", ["B is bigger — same first addend, 35 > 25", "Yes, about $1 — 49 is almost 50 and 51 is just over 50"]) +
        tg_sec(5, "Word Problem", ["35 + 25 = 60¢"]) +
        tg_note("Page break"),

        tg_section_title("Tuesday: Estimating and Adding Money") +
        tg_sec(1, "Warm-up make $1", ["25¢, 50¢, 10¢, 75¢"]) +
        tg_sec(2, "Estimate First", ["Est 60, actual 59 / Est 80, actual 79 / Est 60, actual 62 / Est 80, actual 80"]) +
        tg_sec(3, "Column Adding", ["59, 79, 62, 80"]) +
        tg_sec(4, "Shopping", ["75¢, 80¢"]) +
        tg_sec(5, "Word Problem", ["45+25=70¢ — yes, 80¢ is enough (10¢ left)"]) +
        tg_note("Page break"),

        tg_section_title("Wednesday: Making Change") +
        tg_sec(1, "Warm-up next ten", ["3, 8, 5, 9"]) +
        tg_sec(2, "Count Up (guided)", ["Model counting up on a number line"]) +
        tg_sec(3, "Make Change", ["10¢, 10¢, 20¢, 45¢"]) +
        tg_sec(4, "Two Ways", ["45→60: change 15¢ both ways", "25→50: change 25¢ both ways"]) +
        tg_sec(5, "Create Own", ["Accept any price <50¢ with correct change from 50¢"]) +
        tg_note("Page break"),

        tg_section_title("Thursday: Store Transactions") +
        tg_sec(1, "Warm-up change from 25¢", ["5¢, 10¢, 15¢, 20¢"]) +
        tg_sec(2, "Word Problems", ["Spends 75¢, change 25¢ from $1", "75¢ ≥ 55¢ yes; change 20¢", "Snacks 60¢, paid 75¢ — yes, enough (15¢ left)"]) +
        tg_sec(3, "Two-Step", ["Step 1: 90−25=65¢; Step 2: 65−30=35¢ left"]) +
        tg_sec(4, "Number Talk", ["Kim — she paid more for the same price", "Yes — 45 is less than 50, and 50+50=100, so 45+45 < $1"]) +
        tg_sec(5, "Create Own", ["Accept student-created transaction problems"]) +
        tg_note("Page break"),

        tg_section_title("Friday: Review & Self-Check") +
        tg_sec(1, "Warm-up", ["$1.00, $1.00, 80¢, 60¢"]) +
        tg_sec(2, "Estimate First", ["Est 70, actual 71 / Est 70, actual 71 / Est 80, actual 73 / Est 60, actual 65"]) +
        tg_sec(3, "Add & Change Review", ["80¢; 15¢; 75¢; 55¢"]) +
        tg_sec(4, "Word Problems", ["75−55=20¢ change", "Yes — 2 pencils = 40¢, 10¢ left"]) +
        tg_sec(5, "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", "Adding Money Amounts"),
        (tuesday, "Tuesday", "Estimating and Adding Money"),
        (wednesday, "Wednesday", "Making Change"),
        (thursday, "Thursday", "Store Transactions"),
        (friday, "Friday", "Week 19 Review & Self-Check"),
    ]

    for lesson_func, day, title in days:
        html = lesson_func()
        fname = f"Week_19_{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_19_Teacher_Guide.html")
    with open(path, "w") as f:
        f.write(html)
    pdf_path = os.path.join(WEEK, "Week_19_Teacher_Guide.pdf")
    HTML(filename=path).write_pdf(pdf_path)
    print(f"Generated: {pdf_path}")

    print("\nWeek 19 (Money: Adding & Change, new standard) complete!")
