#!/usr/bin/env python3
"""
Week 17: Measurement — Length & Comparing — REWRITTEN
Phase 3: Measurement, Time & Money
Standards: 2.MD.A.1 (measure with appropriate tools), 2.MD.A.2 (measure twice
with different units), 2.MD.A.3 (estimate lengths in inches, feet, cm, meters)

New Standard:
- Reduced drill (40% fewer problems)
- Estimation before measuring
- Multiple strategies encouraged (estimate-then-measure, compare-then-check)
- Better word problems (reasoning over keywords)
- Real challenges (open-ended thinking)
- Number talks (compare lengths WITHOUT measuring)
- Friday self-check with reflection
- Fact fluency warmup daily
- 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,
    ruler_inches, ruler_cm, measure_line, measure_line_cm,
)
from activity_builders import (
    build_ruler_measurement,
    build_challenge_box,
)

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

# Ruler scale: 1 inch = 48px, 1 cm = 24px


# ═══════════════════════════════════════════════════
# MONDAY — Measuring with an Inch Ruler
# ═══════════════════════════════════════════════════
def monday():
    # 1: Fluency warmup
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Solve in your head.</p>'\
         '<div class="mgrid c3">'
    for expr in ["7 + 5", "12 − 4", "9 + 6", "15 − 8"]:
        s1 += f'<div class="abox"><p>{expr} = {b("4em")}</p></div>'
    s1 += '</div></div>'

    # 2: Learn — how to use a ruler
    s2 = '<p class="note">Line up the <b>0 end</b> of the ruler with the start of the object. '\
         'Read the number where the object ends. That is the length!</p>'
    s2 += ruler_inches(6)
    s2 += '<div class="abox" style="margin-top:8px;">'\
          '<p><b>Watch out!</b> If the object does not start at 0, count the inches it covers instead of just reading the end number.</p>'\
          '</div>'

    # 3: Measure lines in inches (reduced from 8 to 4)
    s3 = build_ruler_measurement({
        "unit": "inches",
        "note": "Measure each line with your inch ruler. Line up the 0!",
        "lines": [
            {"length_px": 96, "label": "A."},
            {"length_px": 192, "label": "B."},
            {"length_px": 144, "label": "C."},
            {"length_px": 240, "label": "D."},
        ],
    })

    # 4: Number Talk — compare WITHOUT measuring
    s4 = '<div class="abox" style="background:#e3f2fd;">'\
         '<p><b>Number Talk</b> — Explain WITHOUT measuring.</p>'\
         '<div class="mgrid c2">'
    s4 += '<div class="abox"><p>Look at lines A and D above. Which is longer? How can you tell just by looking?</p>'\
          '<p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '<div class="abox"><p>A pencil is 7 inches. A crayon is 4 inches. About how many inches longer is the pencil? Explain how you know.</p>'\
          '<p style="font-size:11px;">My thinking: ' + bw() + '</p></div>'
    s4 += '</div></div>'

    # 5: Challenge — find and measure real objects
    s5 = '<div class="abox" style="background:#f3e5f5;">'\
         '<p><b>Challenge</b> — Find 2 real objects at home. Measure each with a ruler.</p>'\
         '<div class="mgrid c2">'
    for i in [1, 2]:
        s5 += f'<div class="abox"><p>Object {i}: ' + bw() + '</p>'\
              '<p>Length: ' + b("4em") + ' inches</p></div>'
    s5 += '</div><p style="font-size:11px; color:#666;">Which object was longer? ' + bw() + '</p></div>'

    return page(17, "Monday", "Measuring with an Inch Ruler",
        f'''{sec(1, "Warm-up: Mental Math", s1)}
{sec(2, "Learn: How to Use a Ruler", s2)}
{sec(3, "Measure in Inches", s3)}
{sec(4, "Number Talk: Compare Without Measuring", s4)}
{sec(5, "Challenge: Measure Real Objects", s5)}''')


# ═══════════════════════════════════════════════════
# TUESDAY — Estimating, then Measuring in Centimeters
# ═══════════════════════════════════════════════════
def tuesday():
    # 1: Fluency warmup
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Solve in your head.</p>'\
         '<div class="mgrid c3">'
    for expr in ["8 + 8", "14 − 7", "6 + 9", "13 − 5"]:
        s1 += f'<div class="abox"><p>{expr} = {b("4em")}</p></div>'
    s1 += '</div></div>'

    # 2: Learn — centimeters
    s2 = '<p class="note">A <b>centimeter (cm)</b> is smaller than an inch. Your fingertip is about 1 cm wide. '\
         'We use cm to measure small things carefully.</p>'
    s2 += ruler_cm(12)

    # 3: Estimate First! — estimate before measuring (orange box)
    s3 = '<div class="abox" style="background:#fff3e0;">'\
         '<p><b>Estimate First!</b> Look at each line. Write your estimate BEFORE you measure. Then measure with your cm ruler.</p>'\
         '<div class="mgrid c2">'
    for label, px in [("A.", 120), ("B.", 216), ("C.", 72), ("D.", 168)]:
        s3 += f'<div class="abox"><div style="display:flex; align-items:center; gap:6px;">'\
              f'<div class="measure-line" style="width:{px}px;"></div><span>{label}</span></div>'\
              f'<p>My estimate: {b("3em")} cm</p>'\
              f'<p>Measured: {b("3em")} cm</p></div>'
    s3 += '</div><p style="font-size:11px; color:#666;">Was your estimate close? A good estimate is within 2 cm!</p></div>'

    # 4: Which unit would you use? (reduced from 8 to 4)
    s4 = '<div class="abox">'\
         '<p class="note">Circle the best unit to measure each object: <b>cm</b>, <b>inches</b>, <b>feet</b>, or <b>meters</b>.</p>'\
         '<div class="mgrid c2">'
    for item in ["The length of an ant", "The height of a door", "The length of your shoe", "The length of a soccer field"]:
        s4 += f'<div class="abox"><p>{item}</p><p style="font-size:12px;">cm &nbsp;|&nbsp; inches &nbsp;|&nbsp; feet &nbsp;|&nbsp; meters</p></div>'
    s4 += '</div></div>'

    # 5: Word problem
    s5 = '<div class="wp">'\
         '<p class="note">Read carefully. Think about what is happening. Draw if it helps!</p>'\
         '<div class="abox"><p style="font-size:0.95em;">Maya\'s ribbon is 30 cm long. She cuts off a piece that is 12 cm '\
         'to wrap a present. How long is the ribbon that is left?</p>'\
         '<p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p>'\
         '<p>' + b("5em") + ' cm</p></div></div>'

    return page(17, "Tuesday", "Estimating & Measuring in Centimeters",
        f'''{sec(1, "Warm-up: Mental Math", s1)}
{sec(2, "Learn: Centimeters", s2)}
{sec(3, "Estimate First!", s3)}
{sec(4, "Choose the Best Unit", s4)}
{sec(5, "Word Problem", s5)}''')


# ═══════════════════════════════════════════════════
# WEDNESDAY — Measuring Twice: Inches AND Centimeters
# ═══════════════════════════════════════════════════
def wednesday():
    # 1: Fluency warmup
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Solve in your head.</p>'\
         '<div class="mgrid c3">'
    for expr in ["16 − 9", "7 + 7", "11 − 6", "8 + 5"]:
        s1 += f'<div class="abox"><p>{expr} = {b("4em")}</p></div>'
    s1 += '</div></div>'

    # 2: Measure the SAME line twice (2.MD.A.2) — reduced from 6 to 3
    s2 = '<p class="note">Measure each line <b>twice</b>: once in inches, once in centimeters.</p>'\
         '<div class="mgrid c1">'
    for label, px in [("A.", 96), ("B.", 192), ("C.", 144)]:
        s2 += f'<div class="abox"><div style="display:flex; align-items:center; gap:6px;">'\
              f'<div class="measure-line" style="width:{px}px;"></div><span>{label}</span></div>'\
              f'<p>Inches: {b("3em")} &nbsp;&nbsp; Centimeters: {b("3em")}</p></div>'
    s2 += '</div>'

    # 3: Number Talk — why are the numbers different?
    s3 = '<div class="abox" style="background:#e3f2fd;">'\
         '<p><b>Number Talk</b> — Explain WITHOUT measuring anything new.</p>'\
         '<p>When you measured line B, you got a <b>bigger number</b> in centimeters than in inches. '\
         'But the line did not change! Why is the cm number bigger?</p>'\
         '<p style="font-size:11px;">My thinking: ' + bw() + '</p>'\
         '<p style="font-size:11px; color:#666;">Hint: think about which unit is smaller.</p>'\
         '</div>'

    # 4: Comparing lengths — how much longer? (reduced from 6 to 4)
    s4 = '<div class="abox">'\
         '<p class="note">How much longer is the first object? Subtract to find out.</p>'\
         '<div class="mgrid c2">'
    for a, c, ua, ub, unit in [("A rope is 45 cm", "a stick is 28 cm", 45, 28, "cm"),
                               ("A table is 60 inches", "a chair is 34 inches", 60, 34, "inches"),
                               ("A snake is 52 cm", "a lizard is 19 cm", 52, 19, "cm"),
                               ("A slide is 96 inches", "a bench is 48 inches", 96, 48, "inches")]:
        s4 += f'<div class="abox"><p>{a} long, and {c} long.</p>'\
              f'<p>{ua} − {ub} = {b("4em")} {unit} longer</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>Draw a line below that you think is <b>exactly 4 inches</b> long — no ruler while you draw! '\
         'Then measure it. How close were you?</p>'\
         '<div style="min-height:50px; border-bottom:1px dashed #999;"></div>'\
         '<p>My line measured: ' + b("4em") + ' inches</p>'\
         '<p style="font-size:11px;">How far off was I? ' + bw() + '</p>'\
         '</div>'

    return page(17, "Wednesday", "Measuring Twice: Inches and Centimeters",
        f'''{sec(1, "Warm-up: Mental Math", s1)}
{sec(2, "Measure Twice: Two Units", s2)}
{sec(3, "Number Talk: Why Different Numbers?", s3)}
{sec(4, "How Much Longer?", s4)}
{sec(5, "Challenge: Create Your Own", s5)}''')


# ═══════════════════════════════════════════════════
# THURSDAY — Length Word Problems & Real World
# ═══════════════════════════════════════════════════
def thursday():
    # 1: Fluency warmup
    s1 = '<div class="abox" style="background:#e8f5e9;">'\
         '<p><b>2-min Fluency Warm-up</b> — Solve in your head.</p>'\
         '<div class="mgrid c3">'
    for expr in ["9 + 9", "17 − 8", "6 + 7", "12 − 3"]:
        s1 += f'<div class="abox"><p>{expr} = {b("4em")}</p></div>'
    s1 += '</div></div>'

    # 2: Estimate First! — real objects
    s2 = '<div class="abox" style="background:#fff3e0;">'\
         '<p><b>Estimate First!</b> Estimate each length BEFORE checking. Then measure or look it up with a grown-up.</p>'\
         '<div class="mgrid c2">'
    for item, unit in [("The width of this paper", "inches"), ("Your hand from wrist to fingertip", "cm"),
                       ("The height of your water cup", "cm"), ("The length of your foot", "inches")]:
        s2 += f'<div class="abox"><p>{item}</p><p>Estimate: {b("3em")} {unit}</p><p>Actual: {b("3em")} {unit}</p></div>'
    s2 += '</div></div>'

    # 3: Word problems — reasoning (reduced from 5 to 3)
    s3 = '<div class="wp">'\
         '<p class="note">Read carefully. Think about what is happening in the situation. Draw if it helps!</p>'\
         '<div class="mgrid c2">'
    problems = [
        ("Jake\'s paper chain is 38 cm long. He adds more links until it is 63 cm long. How many centimeters did he add?", "cm"),
        ("A garden row is 72 inches long. Dad plants flowers along 45 inches of it. How many inches of the row are still empty?", "inches"),
        ("Nia\'s jump was 34 inches. Her second jump was 19 inches farther. How far was her second jump?", "inches"),
    ]
    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: Two strategies — show two different ways
    s4 = '<div class="abox">'\
         '<p><b>Show two different ways</b> to solve: A string is 50 cm. You cut off 23 cm. How much string is left?</p>'\
         '<div class="mgrid c2">'\
         '<div class="abox"><p style="font-size:11px; color:#666;">Strategy 1 (subtract): ' + bw() + '</p></div>'\
         '<div class="abox"><p style="font-size:11px; color:#666;">Strategy 2 (count up from 23): ' + bw() + '</p></div>'\
         '</div><p>Answer: ' + b("4em") + ' cm</p></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 word problem about measuring something you love (a pet, a toy, a bike...). Use inches or cm. Then solve it.</p>'\
         '<p style="min-height:50px; border-bottom:1px solid #333;"></p>'\
         '<p style="min-height:26px; border-bottom:1px solid #333;"></p>'\
         '<p>Answer: ' + bl() + '</p>'\
         '</div>'

    return page(17, "Thursday", "Length Word Problems & Real World",
        f'''{sec(1, "Warm-up: Mental Math", s1)}
{sec(2, "Estimate First: Real Objects", s2)}
{sec(3, "Word Problems: Think About What Is Happening", s3)}
{sec(4, "Show Two Different Ways", 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> — Mental math. Go fast!</p>'\
         '<div class="mgrid c3">'
    for expr in ["13 − 6", "8 + 9", "15 − 7", "7 + 6"]:
        s1 += f'<div class="abox"><p>{expr} = {b("4em")}</p></div>'
    s1 += '</div></div>'

    # 2: Estimate First! review
    s2 = '<div class="abox" style="background:#fff3e0;">'\
         '<p><b>Estimate First!</b> Estimate each line in cm, then measure.</p>'\
         '<div class="mgrid c2">'
    for label, px in [("A.", 96), ("B.", 192)]:
        s2 += f'<div class="abox"><div style="display:flex; align-items:center; gap:6px;">'\
              f'<div class="measure-line" style="width:{px}px;"></div><span>{label}</span></div>'\
              f'<p>Estimate: {b("3em")} cm &nbsp; Measured: {b("3em")} cm</p></div>'
    s2 += '</div></div>'

    # 3: Mixed measurement review (reduced from 6 to 4)
    s3 = '<div class="abox">'\
         '<p class="note">Use any strategy you prefer.</p>'\
         '<div class="mgrid c2">'
    for q in ["A book is 9 inches tall. A box is 14 inches tall. How much taller is the box? " + b("3em") + " inches",
              "Which is the best unit to measure a hallway: cm or meters? " + b("5em"),
              "A worm is 8 cm. It grows 5 more cm. Now it is " + b("3em") + " cm.",
              "1 foot = 12 inches. A ruler is 1 foot. Two rulers end to end = " + b("3em") + " inches."]:
        s3 += f'<div class="abox"><p>{q}</p></div>'
    s3 += '</div></div>'

    # 4: Word problem review
    s4 = '<div class="wp">'\
         '<p class="note">Read carefully. Show your work.</p>'\
         '<div class="abox"><p style="font-size:0.95em;">Sam\'s tower of blocks is 47 cm tall. Leo\'s tower is 29 cm tall. '\
         'If Leo puts his tower on top of Sam\'s, how tall is the whole tower?</p>'\
         '<p style="font-size:11px;">Draw or write your thinking: ' + bw() + '</p>'\
         '<p>' + b("5em") + ' cm</p></div></div>'

    # 5: Self-check with emoji reflection
    s5 = '<div class="selfcheck">'\
         '<p><b>Self-Check: How do you feel about measuring length?</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>Measuring with a Ruler</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>Estimating Lengths</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>Comparing Lengths (How Much Longer?)</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 best estimate this week was:</b> ' + bl() + '</p>'\
         '</div>'

    return page(17, "Friday", "Week 17 Review & Self-Check",
        f'''{sec(1, "Warm-up: Mental Math", s1)}
{sec(2, "Estimate First!", s2)}
{sec(3, "Mixed Measurement Review", s3)}
{sec(4, "Word Problem", s4)}
{sec(5, "Self-Check & Reflection", s5)}''')


# ═══════════════════════════════════════════════════
# TEACHER GUIDE
# ═══════════════════════════════════════════════════
def teacher_guide():
    return tg_page_multi(
        "Week 17", "Measurement: Length & Comparing — Teacher Guide",

        tg_section_title("Monday: Measuring with an Inch Ruler") +
        tg_sec(1, "Warm-up", ["12, 8, 15, 7"]) +
        tg_sec(2, "Ruler Basics", ["Emphasize lining up the 0 end; common error is starting at 1"]) +
        tg_sec(3, "Measure in Inches", ["A=2 in, B=4 in, C=3 in, D=5 in"]) +
        tg_sec(4, "Number Talk", ["D is longer — it stretches farther; pencil is about 3 inches longer (7−4)"]) +
        tg_sec(5, "Challenge", ["Any real objects; check ruler technique, not exactness"]) +
        tg_note("Page break"),

        tg_section_title("Tuesday: Estimating & Measuring in Centimeters") +
        tg_sec(1, "Warm-up", ["16, 7, 15, 8"]) +
        tg_sec(2, "Centimeters", ["Fingertip ≈ 1 cm benchmark"]) +
        tg_sec(3, "Estimate First", ["A=5 cm, B=9 cm, C=3 cm, D=7 cm; praise estimates within 2 cm"]) +
        tg_sec(4, "Best Unit", ["ant=cm, door=feet (or meters), shoe=inches, soccer field=meters"]) +
        tg_sec(5, "Word Problem", ["30−12 = 18 cm"]) +
        tg_note("Page break"),

        tg_section_title("Wednesday: Measuring Twice") +
        tg_sec(1, "Warm-up", ["7, 14, 5, 13"]) +
        tg_sec(2, "Measure Twice", ["A: 2 in / 4 cm; B: 4 in / 8 cm; C: 3 in / 6 cm (printed scale)"]) +
        tg_sec(3, "Number Talk", ["Centimeters are smaller units, so it takes MORE of them to cover the same line"]) +
        tg_sec(4, "How Much Longer", ["17 cm, 26 inches, 33 cm, 48 inches"]) +
        tg_sec(5, "Create Your Own", ["Any line; celebrate estimates within 1 inch of 4"]) +
        tg_note("Page break"),

        tg_section_title("Thursday: Length Word Problems") +
        tg_sec(1, "Warm-up", ["18, 9, 13, 9"]) +
        tg_sec(2, "Estimate First (Real Objects)", ["Paper width ≈ 8.5 in; other answers vary — check reasonableness"]) +
        tg_sec(3, "Word Problems", ["63−38 = 25 cm added; 72−45 = 27 inches empty; 34+19 = 53 inches"]) +
        tg_sec(4, "Two Ways", ["50−23 = 27 cm; counting up: 23→30 is 7, 30→50 is 20, total 27"]) +
        tg_sec(5, "Create Own", ["Accept student problems with correct solution"]) +
        tg_note("Page break"),

        tg_section_title("Friday: Review & Self-Check") +
        tg_sec(1, "Warm-up", ["7, 17, 8, 13"]) +
        tg_sec(2, "Estimate First", ["A=4 cm, B=8 cm (printed scale)"]) +
        tg_sec(3, "Mixed Review", ["5 inches taller; meters; 13 cm; 24 inches"]) +
        tg_sec(4, "Word Problem", ["47+29 = 76 cm"]) +
        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", "Measuring with an Inch Ruler"),
        (tuesday, "Tuesday", "Estimating & Measuring in Centimeters"),
        (wednesday, "Wednesday", "Measuring Twice: Inches and Centimeters"),
        (thursday, "Thursday", "Length Word Problems & Real World"),
        (friday, "Friday", "Week 17 Review & Self-Check"),
    ]

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

    print("\nWeek 17 (rewritten to new standard) complete!")
