#!/usr/bin/env python3
"""
Tuesday Generator - Practice It (3 pages)

Usage:
    from tuesday import generate_tuesday
    generate_tuesday(week_dir=..., week_num=..., phonics_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,
                     word_names, paragraph_parts_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")
    phonics_label = kw["phonics_label"]
    words = kw["words"]
    learning_text = kw["learning_text"]
    vowel_examples = kw.get("vowel_examples", [])
    remember_boxes = kw.get("remember_boxes", [])
    scramble_words = kw.get("scramble_words", None)
    reading_text = kw["reading_text"]
    comp_questions = kw["comp_questions"]
    pattern_hunt_words = kw.get("pattern_hunt_words", None)
    pattern_hunt_instruction = kw.get("pattern_hunt_instruction", "Check each word that matches the pattern.")
    pattern_hunt_title = kw.get("pattern_hunt_title", "Pattern Hunt")
    swap_data = kw.get("swap_data", [])
    builder_prompts = kw.get("builder_prompts", [])
    # NEW: Vocabulary / paragraph structure support
    paragraph_example = kw.get("paragraph_example", None)  # (topic, details, conclusion)

    day_dir = os.path.join(week_dir, "Tuesday")
    os.makedirs(day_dir, exist_ok=True)
    WORD_NAMES = word_names(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)

    # Pattern Hunt
    hunt_list = pattern_hunt_words if pattern_hunt_words else WORD_NAMES
    hunt_html = ""
    for word in hunt_list:
        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>'

    # Remember boxes
    rem_html = ""
    for title, content in remember_boxes:
        rem_html += f'{remember_box(title, content)}'

    # Vowel examples - conditional 2 column table
    vu = ""
    if vowel_examples:
        mid = (len(vowel_examples) + 1) // 2
        left_items = "".join(f'<li>{item}</li>' for item in vowel_examples[:mid])
        right_items = "".join(f'<li>{item}</li>' for item in vowel_examples[mid:])
        vu = 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>'

    # Paragraph example - NEW for vocab weeks
    para_section = ""
    if paragraph_example:
        topic, details, conclusion = paragraph_example
        para_section = f"""{sectitle("Paragraph Parts")}
    {secnote("A paragraph has three parts: a topic sentence, detail sentences, and a concluding sentence.")}
    {paragraph_parts_box("What Makes a Paragraph?", "Every good paragraph has three parts:", [
        ("Topic", topic, "Introduces what the paragraph is about"),
        ("Detail", details, "Gives supporting information"),
        ("Conclusion", conclusion, "Wraps up the idea")
    ])}"""

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

    # Determine which remember box goes where
    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])

    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} -- Pattern Deep Dive")}
    {sectitle("Here's What We're Learning")}
    {secnote(learning_text)}
    {vu}
    {rem_page1}
    {sectitle("Word Scramble Challenge")}
    {secnote("Unscramble the letters to spell a word from this week.")}
    {scramble_html}
    {para_section}
    {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(pattern_hunt_title)}
    {secnote(pattern_hunt_instruction)}
    {hunt_html}
    </div>
    {page_break()}

    <div>
    {rem_page3}
    {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")
