#!/usr/bin/env python3
"""
Week 10: Subtraction with Regrouping (NEW STANDARD)
Phase 2: Addition & Subtraction to 100
"""

import os
from weasyprint import HTML

from math_helpers import (
    page, page_multi, sec, b, bw,
    tg_page_multi, tg_sec, tg_grid_answers, tg_note, tg_section_title,
)
from activity_builders import (
    build_column_subtraction,
    build_regrouping_visual,
    build_number_bonds,
    build_write_tens_ones,
    build_tens_ones_chart,
    build_missing_addend,
    build_compare_numbers,
    build_two_step_problems,
)

BASE = "/home/vincent/Home_School/2nd_Grade/Math"
WEEK = os.path.join(BASE, "Week_10")

def ensure_week_dir():
    os.makedirs(WEEK, exist_ok=True)
    for f in os.listdir(WEEK):
        if f.endswith(".pdf"):
            os.remove(os.path.join(WEEK, f))

# ═══════════════════════════════════════════════════
# MONDAY — Introduction to Regrouping
# ═══════════════════════════════════════════════════
def monday():
    # 1: Estimation
    s1 = '<p class="note">Before you subtract, <b class="bw">estimate</b>! Will the answer be closer to 10, 30, or 50?</p>'
    s1 += '<div class="mgrid c2">'
    problems = [(53, 28), (64, 37), (72, 45), (81, 36)]
    for a, c in problems:
        s1 += f'<div class="abox"><p>{a} - {c} = </p><p>Estimate: <span class="bw">____</span></p></div>'
    s1 += '</div>'

    # 2: Visual Trading (Base-10)
    s2 = '<p class="note">When ones are too small, <b class="bw">regroup</b> 1 ten into 10 ones. Trade them!</p>'
    s2 += build_regrouping_visual({
        "problems": [(53, 28, "sub"), (64, 37, "sub")],
        "note": "Regroup 1 ten to make 10 ones so you can subtract."
    })

    # 3: Number Line
    s3 = '<p class="note">Use the number line. Jump back by tens, then by ones.</p>'
    s3 += '<div class="mgrid c2">'
    for a, t in [(53, 28), (64, 37)]:
        s3 += f'<div class="abox"><p><b class="highlight">{a} - {t}</b></p>'
        start_tick = (a // 10 - 1) * 10
        end_tick = start_tick + 80
        s3 += '<div style="position:relative; height:40px; margin:10px 0; border-bottom:2px solid #333;"></div>'
        s3 += f'<p style="font-size:0.8em; color:#666;">Jump back from {a} to {a-t}</p></div>'
    s3 += '</div>'

    # 4: Guided Example
    s4 = '<p class="note">Watch how we regroup in the tens column!</p>'
    s4 += '<div class="abox" style="background:#e8eaf6;">'
    s4 += '<p><b class="highlight">Example: 53 - 28</b></p>'
    s4 += '<p style="text-align:center; font-size:18px;">&nbsp;&nbsp;<sup class="regroup">1</sup></p>'
    s4 += '<p style="text-align:center; font-size:18px;">&nbsp;&nbsp;53</p>'
    s4 += '<p style="text-align:center; font-size:18px;">- 28</p>'
    s4 += '<p style="text-align:center; font-size:18px;">─────</p>'
    s4 += '<p style="text-align:center; font-size:18px;">&nbsp;&nbsp;25</p>'
    s4 += '<p style="font-size:12px;">Ones: 13 - 8 = 5 | Tens: 4 - 2 = 2 | Total: 25</p></div>'

    body = sec(1, "Estimate First", s1)
    body += sec(2, "Visual Trading", s2)
    body += sec(3, "Number Line", s3)
    body += sec(4, "Guided Example", s4)
    return page(10, "Monday", "Introduction to Regrouping", body)

# ═══════════════════════════════════════════════════
# TUESDAY — Skill Building
# ═══════════════════════════════════════════════════
def tuesday():
    # 1: Break Apart Strategy
    s1 = '<p class="note">Try <b class="bw">breaking apart</b>! Subtract tens first, then ones.</p>'
    s1 += '<div class="mgrid c1">'
    s1 += '<div class="abox"><p><b class="highlight">53 - 28</b></p>'
    s1 += '<p style="font-size:0.8em; color:#666;">Step 1: 53 - 20 = 33</p>'
    s1 += '<p style="font-size:0.8em; color:#666;">Step 2: 33 - 8 = 25</p></div>'
    s1 += '</div>'

    # 2: Column Subtraction
    s2 = build_column_subtraction({
        "problems": [(53, 28), (64, 37), (72, 45), (81, 36), (93, 47), (75, 38), (84, 37), (95, 48)],
        "digits": 2,
        "cols": 4,
        "note": "Don't forget to subtract the borrowed 1 from the tens!"
    })

    # 3: Mental Math
    s3 = '<p class="note">Quick! Solve these in your head.</p>'
    s3 += '<div class="mgrid c4">'
    for a, c in [(25, 12), (38, 15), (44, 22), (59, 30)]:
        s3 += f'<div class="abox"><p>{a} - {c} = {b("3em")}</p></div>'
    s3 += '</div>'

    body = sec(1, "Break Apart Strategy", s1)
    body += sec(2, "Column Subtraction", s2)
    body += sec(3, "Mental Math", s3)
    return page(10, "Tuesday", "Skill Building", body)

# ═══════════════════════════════════════════════════
# WEDNESDAY — Mixed Practice
# ═══════════════════════════════════════════════════
def wednesday():
    # 1: Two Ways Challenge
    s1 = '<p class="note">Solve the same problem two different ways (Column vs. Break Apart).</p>'
    s1 += '<div class="mgrid c1">'
    for a, c in [(53, 28), (74, 36)]:
        s1 += f'<div class="abox"><p><b class="highlight">{a} - {c}</b></p>'
        s1 += '<p style="font-size:0.8em;">Way 1 (Column):</p>' + b("4em")
        s1 += '<p style="font-size:0.8em; margin-top:10px;">Way 2 (Break Apart):</p>' + b("4em")
        s1 += '</div>'
    s1 += '</div>'

    # 2: Mixed Practice
    s2 = '<p class="note">Some need regrouping, some don\'t. Be careful!</p>'
    s2 += '<div class="mgrid c3">'
    for a, c in [(58, 23), (53, 28), (76, 34), (62, 45), (89, 27), (74, 21), (96, 48), (87, 35)]:
        s2 += f'<div class="abox"><p>{a} - {c} = {b("4em")}</p></div>'
    s2 += '</div>'

    # 3: Estimation vs Actual
    s3 = '<p class="note">Estimate the difference first, then solve.</p>'
    s3 += '<div class="mgrid c2">'
    for a, c in [(84, 37), (93, 48)]:
        s3 += f'<div class="abox"><p><b class="highlight">{a} - {c}</b></p>'
        s3 += '<p>Estimate: <span class="bw">____</span></p>'
        s3 += '<p>Actual: <span class="bw">____</span></p></div>'
    s3 += '</div>'

    # 4: Error Analysis
    s4 = '<p class="note">One of these has a regrouping error. Find it!</p>'
    s4 += '<div class="mgrid c2">'
    s4 += '<div class="abox"><p style="text-align:center;">53<br>- 28<br>---<br>35</p><p>✓ or ✗?</p></div>'
    s4 += '<div class="abox"><p style="text-align:center;">64<br>- 37<br>---<br>27</p><p>✓ or ✗?</p></div>'
    s4 += '</div>'

    body = sec(1, "Two Ways Challenge", s1)
    body += sec(2, "Mixed Practice", s2)
    body += sec(3, "Estimation vs Actual", s3)
    body += sec(4, "Error Analysis", s4)
    return page(10, "Wednesday", "Mixed Practice", body)

# ═══════════════════════════════════════════════════
# THURSDAY — Word Problems & Application
# ═══════════════════════════════════════════════════
def thursday():
    # 1: Word Problems
    s1 = '<p class="note">Read, circle numbers, and solve. Does your answer make sense?</p>'
    s1 += '<div class="mgrid c1">'
    problems = [
        ("Emma had 53 stickers. She gave 28 to her friend. How many left?", 53, 28, "stickers"),
        ("The library had 72 books. They lent out 35. How many remain?", 72, 35, "books"),
        ("Jake scored 84 points. Tom scored 47 points. What is the difference?", 84, 47, "points"),
        ("A farmer had 93 chickens. 48 were sold. How many left?", 93, 48, "chickens"),
    ]
    for text, a, c, unit in problems:
        s1 += f'<div class="abox"><p style="font-size:0.95em;">{text}</p>'
        s1 += '<p>' + b("6em") + f' {unit}</p></div>'
    s1 += '</div>'

    # 2: Two-Step Problems
    s2 = '<p class="note">Solve step by step. Watch for regrouping in both steps!</p>'
    s2 += build_two_step_problems({
        "problems": [
            {"text": "Sam had 85 stickers. He gave 37 to Tom. Then he gave 24 to Mom. How many are left?", "blanks": 2},
            {"text": "A box had 96 apples. 48 were sold. Then 15 were thrown away. How many are left?", "blanks": 2},
        ],
        "note": "Solve carefully!"
    })

    body = sec(1, "Word Problems", s1)
    body += sec(2, "Two-Step Problems", s2)
    return page(10, "Thursday", "Word Problems", body)

# ═══════════════════════════════════════════════════
# FRIDAY — Review & Self-Check
# ═══════════════════════════════════════════════════
def friday():
    # 1: Strategy Reflection
    s1 = '<p class="note">Which subtraction strategy did you like best this week?</p>'
    s1 += '<div class="mgrid c3">'
    for strat in ["Column Method", "Break Apart", "Number Line"]:
        s1 += f'<div class="abox"><p><b class="highlight">{strat}</b></p><p>My favorite was: <span class="bw">_______</span></p></div>'
    s1 += '</div>'

    # 2: Weekly Challenge
    s2 = '<p class="note">The Grand Challenge: Use any method you want!</p>'
    s2 += '<div class="mgrid c3">'
    for a, c in [(59, 48), (68, 39), (79, 28), (87, 46), (95, 38), (76, 59)]:
        s2 += f'<div class="abox"><p>{a} - {c} = {b("4em")}</p></div>'
    s2 += '</div>'

    # 3: Speed Drill
    s3 = '<p class="note">Speedy Math! How fast can you solve these?</p>'
    s3 += '<div class="mgrid c4">'
    for a, c in [(53, 28), (64, 37), (72, 45), (81, 36), (93, 47), (75, 38), (82, 37), (94, 48)]:
        s3 += f'<div class="abox"><p>{a} - {c} = {b("4em")}</p></div>'
    s3 += '</div>'

    body = sec(1, "Strategy Reflection", s1)
    body += sec(2, "Weekly Challenge", s2)
    body += sec(3, "Speed Drill", s3)
    return page(10, "Friday", "Week 10 Review", body)

# ═══════════════════════════════════════════════════
# TEACHER GUIDE
# ═══════════════════════════════════════════════════
def monday_tg():
    return "".join([
        tg_section_title("New Focus: Regrouping Concepts"),
        tg_note("The goal is to move from visual 'trading' to the abstract algorithm."),
        tg_section_title("Activity Answers"),
        tg_sec(1, "Estimates", ["~30", "~30", "~20", "~40"]),
        tg_sec(2, "Visual", ["25", "27"]),
        tg_sec(3, "Number Line", ["25", "27"]),
        tg_sec(4, "Example", ["25"])
    ])

def tuesday_tg():
    return "".join([
        tg_section_title("New Focus: Algorithm Fluency"),
        tg_note("Emphasize the 'borrowed' 1 in the tens column to prevent errors."),
        tg_section_title("Activity Answers"),
        tg_sec(1, "Break Apart", ["25"]),
        tg_sec(2, "Column", ["25", "27", "27", "45", "46", "37", "47", "47"]),
        tg_sec(3, "Mental", ["13", "23", "22", "29"])
    ])

def wednesday_tg():
    return "".join([
        tg_section_title("New Focus: Flexibility"),
        tg_note("Encourage using different methods to verify answers."),
        tg_section_title("Activity Answers"),
        tg_sec(1, "Two Ways", ["25", "38"]),
        tg_sec(2, "Mixed", ["35", "25", "42", "17", "62", "53", "49", "49"]),
        tg_sec(3, "Estimation", ["~40/25", "~50/45"]),
        tg_sec(4, "Error", ["✗", "✓"])
    ])

def thursday_tg():
    return "".join([
        tg_section_title("New Focus: Real-World Application"),
        tg_note("Focus on interpreting the 'difference' in word problems."),
        tg_section_title("Activity Answers"),
        tg_sec(1, "Word Problems", ["25 stickers", "37 books", "37 points", "45 chickens"]),
        tg_sec(2, "Two-Step", ["28 stickers", "69 apples"])
    ])

def friday_tg():
    return "".join([
        tg_section_title("Review Goals"),
        tg_note("Check for mastery of the regrouping algorithm."),
        tg_section_title("Activity Answers"),
        tg_sec(2, "Challenge", ["11", "29", "51", "41", "57", "17"]),
        tg_sec(3, "Speed Drill", ["25", "27", "27", "45", "46", "37", "45", "46"])
    ])

# ═══════════════════════════════════════════════════
# MAIN
# ═══════════════════════════════════════════════════
if __name__ == "__main__":
    ensure_week_dir()
    
    # Student worksheets
    HTML(string=monday()).write_pdf(os.path.join(WEEK, "Week_10_Monday.pdf"))
    HTML(string=tuesday()).write_pdf(os.path.join(WEEK, "Week_10_Tuesday.pdf"))
    HTML(string=wednesday()).write_pdf(os.path.join(WEEK, "Week_10_Wednesday.pdf"))
    HTML(string=thursday()).write_pdf(os.path.join(WEEK, "Week_10_Thursday.pdf"))
    HTML(string=friday()).write_pdf(os.path.join(WEEK, "Week_10_Friday.pdf"))
    
    # Teacher guide
    tg_parts = []
    tg_parts.append(monday_tg())
    tg_parts.append(tuesday_tg())
    tg_parts.append(wednesday_tg())
    tg_parts.append(thursday_tg())
    tg_parts.append(friday_tg())
    
    tg_body_clean = ""
    for part in tg_parts:
        if "<body" in part:
            clean = part.split("<body", 1)[1].rsplit("</body", 1)[0]
            tg_body_clean += clean
        else:
            tg_body_clean += part

    tg_html = tg_page_multi(10, "Week 10 Teacher Guide", tg_body_clean)
    HTML(string=tg_html).write_pdf(os.path.join(WEEK, "Week_10_Teacher_Guide.pdf"))
    
    print(f"Week 10 (NEW STANDARD) generated successfully in {WEEK}")