#!/usr/bin/env python3
"""
Tuesday Generator - Word Parts & Meaning Phase (Practice It, 3 pages)

Usage:
    from tuesday_wp import generate_tuesday
    generate_tuesday(week_dir=..., week_num=..., topic_label=..., words=..., ...)
"""
import os, sys, random
sys.path.insert(0, os.path.dirname(__file__))
from helpers import CSS, header, sectitle, secnote, write_line, page_break, remember_box
from weasyprint import HTML


def generate_tuesday(**kw):
    week_dir = kw["week_dir"]
    week_num = kw["week_num"]
    day_name = kw.get("day_name", "Tuesday")
    topic_label = kw["topic_label"]
    words = kw["words"]
    learning_text = kw["learning_text"]
    word_part_examples = kw["word_part_examples"]  # e.g. prefix/suffix examples
    remember_boxes = kw.get("remember_boxes", [])
    scramble_words = kw.get("scramble_words", None)
    reading_text = kw["reading_text"]
    comp_questions = kw["comp_questions"]
    word_part_hunt = kw.get("word_part_hunt", None)  # dict: {"match": [...], "decoy": [...]}
    word_part_hunt_instruction = kw.get("word_part_hunt_instruction", "Check each word that contains the target word part.")
    word_part_hunt_title = kw.get("word_part_hunt_title", "Word Part Hunt")
    swap_data = kw.get("swap_data", [])
    builder_prompts = kw.get("builder_prompts", [])
    # New: Identify the word part activity
    identify_data = kw.get("identify_data", [])  # (word, instruction) tuples

    day_dir = os.path.join(week_dir, "Tuesday")
    os.makedirs(day_dir, exist_ok=True)
    WORD_NAMES = [w[0] for w in words]

    # Word Scramble - 2 column table
    scramble_list = scramble_words if scramble_words else WORD_NAMES
    scramble_rows = ""
    for i in range(0, len(scramble_list), 2):
        scramble_rows += '<tr>'
        for j in range(i, min(i+2, len(scramble_list))):
            word = scramble_list[j]
            scrambled = list(word)
            random.Random(hash(word) % 1000).shuffle(scrambled)
            if "".join(scrambled) == word:
                scrambled[0], scrambled[-1] = scrambled[-1], scrambled[0]
            scramble_rows += f'<td style="padding:4px 8px;vertical-align:top;"><span style="font-family:monospace;font-size:16px;font-weight:bold;color:#FF7043;letter-spacing:2px;">{" ".join(scrambled)}</span><div style="margin-top:4px;">{write_line()}</div></td>'
        scramble_rows += '</tr>'
    scramble_html = f'<table style="width:100%;border-collapse:separate;border-spacing:4px;">{scramble_rows}</table>'

    # Comprehension questions
    comp_html = "".join(f'<div style="margin-bottom:8px;"><strong style="font-size:12px;">{q}</strong><br>{write_line()}</div>' for q in comp_questions)

    # Word Part Hunt
    hunt_match = word_part_hunt.get("match", WORD_NAMES) if word_part_hunt else WORD_NAMES
    hunt_decoy = word_part_hunt.get("decoy", []) if word_part_hunt else []
    all_hunt = list(hunt_match) + list(hunt_decoy)
    random.Random(77).shuffle(all_hunt)
    hunt_html = ""
    for word in all_hunt:
        hunt_html += f'<div style="display:inline-block;width:30%;margin-bottom:4px;padding:4px 8px;background:#E0F2F1;border-radius:4px;border-left:3px solid #26A69A;font-size:12px;"><span style="display:inline-block;width:14px;height:14px;border:1.5px solid #80CBC4;border-radius:3px;margin-right:4px;vertical-align:middle;"></span> <span style="color:#FF7043;font-weight:bold;">{word}</span></div>'

    # Word Swap
    swap_html = ""
    for orig, (w1o, w1s), (w2o, w2s) in swap_data:
        highlighted = orig.replace(w1o, f"<strong>{w1o}</strong>").replace(w2o, f"<strong>{w2o}</strong>")
        swap_html += f'<div style="margin-bottom:10px;padding:6px 8px;background:#FFF3E0;border-radius:5px;border:1px solid #FFB74D;"><div style="font-size:10.5px;font-weight:bold;color:#FF7043;margin-bottom:3px;">Original:</div><div style="font-size:12px;font-style:italic;margin-bottom:4px;">{highlighted}</div><div style="font-size:10.5px;font-weight:bold;color:#FF7043;margin-bottom:3px;">Now write using <strong>{w1s}</strong> and <strong>{w2s}</strong>:</div>{write_line()}</div>'

    # Sentence Builder
    builder_html = ""
    for prompt, keyword in builder_prompts:
        builder_html += f'<div style="margin-bottom:10px;padding:6px 8px;background:#FFF3E0;border-radius:5px;border:1px solid #FFB74D;"><div style="font-size:11px;color:#888;font-style:italic;margin-bottom:3px;">{prompt} (use: <strong style="color:#26A69A;font-style:normal;">{keyword}</strong>)</div>{write_line()}</div>'

    # Identify word parts activity
    identify_html = ""
    if identify_data:
        id_items = ""
        for word, instruction in identify_data:
            id_items += f'<div style="margin:6px 0;font-size:12px;"><span style="font-size:11px;font-weight:bold;color:#26A69A;">{word}:</span> {instruction}<br>{write_line()}</div>'
        identify_html = f'{sectitle("Identify the Word Part")}{secnote("Look at each word and answer the question.")}<div style="font-size:12px;margin:6px 0;">{id_items}</div>'

    # Word part examples - 2 column table
    mid = (len(word_part_examples) + 1) // 2
    left_items = "".join(f'<li>{item}</li>' for item in word_part_examples[:mid])
    right_items = "".join(f'<li>{item}</li>' for item in word_part_examples[mid:])
    ve = f'<table style="width:100%;border-collapse:separate;border-spacing:4px;"><tr>' \
         f'<td style="vertical-align;top;width:50%"><ul style="font-size:12px;margin:4px 0 4px 0;padding-left:16px;">{left_items}</ul></td>' \
         f'<td style="vertical-align;top;width:50%"><ul style="font-size:12px;margin:4px 0 4px 0;padding-left:16px;">{right_items}</ul></td>' \
         f'</tr></table>'

    # Remember boxes
    rem_page1 = ""
    rem_page3 = ""
    if len(remember_boxes) >= 1:
        rem_page1 = remember_box(remember_boxes[0][0], remember_boxes[0][1])
    if len(remember_boxes) >= 2:
        rem_page3 = remember_box(remember_boxes[1][0], remember_boxes[1][1])

    safe_label = topic_label.replace(' ', '_')
    pdf_name = f"Week0{week_num}_{day_name}_{safe_label}.pdf"

    html = f"""<!DOCTYPE html>
    <html><head><meta charset="utf-8"><style>{CSS}</style></head><body>

    <div>
    {header("English Language Arts", f"Week {week_num}, {day_name} -- {topic_label}")}
    {sectitle("Here's What We're Learning")}
    {secnote(learning_text)}
    {ve}
    {rem_page1}
    {sectitle("Word Scramble Challenge")}
    {secnote("Unscramble the letters to spell a word from this week.")}
    {scramble_html}
    {page_break()}
    <hr class="divider">
    {sectitle("Reading Comprehension")}
    {secnote("Read the story. Notice each spelling word in bold.")}
    <div class="story-box">{reading_text}</div>
    <hr class="divider">
    {sectitle("Comprehension Questions")}
    {secnote("Answer each question in a complete sentence.")}
    {comp_html}
    <hr class="divider">
    {sectitle(word_part_hunt_title)}
    {secnote(word_part_hunt_instruction)}
    {hunt_html}
    </div>
    {page_break()}

    <div>
    {rem_page3}
    {identify_html}
    {sectitle("Word Swap Challenge")}
    {secnote("Read the original sentence, then write your own using the new words.")}
    {swap_html}
    {sectitle("Sentence Builder")}
    {secnote("Write a complete sentence using each topic.")}
    {builder_html}
    </div>

    </body></html>"""

    HTML(string=html).write_pdf(os.path.join(day_dir, pdf_name))
    print(f"[ok] Week {week_num} Tuesday generated")