#!/usr/bin/env python3
"""
Wednesday Generator - Word Parts & Meaning Phase (Connect It, 4 pages)

Usage:
    from wednesday_wp import generate_wednesday
    generate_wednesday(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, word_bank, fill_blank_with_line, page_break, remember_box
from weasyprint import HTML


def generate_wednesday(**kw):
    week_dir = kw["week_dir"]
    week_num = kw["week_num"]
    day_name = kw.get("day_name", "Wednesday")
    topic_label = kw["topic_label"]
    words = kw["words"]
    learning_text = kw["learning_text"]
    learning_skills = kw.get("learning_skills", [])
    reading_passage = kw["reading_passage"]
    vocab_question = kw["vocab_question"]
    syn_ant_words = kw["syn_ant_words"]
    word_web_center = kw["word_web_center"]
    word_web_instruction = kw.get("word_web_instruction", "Write 4 words connected to the center word.")
    sentence_sort_data = kw.get("sentence_sort_data", [])
    correct_sentences = kw.get("correct_sentences", [])
    fill_data = kw.get("fill_data", [])
    context_clue = kw.get("context_clue", "")
    # New: Word family builder activity
    word_families = kw.get("word_families", [])  # [(base_word, [related_words]), ...]

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

    # Synonyms & Antonyms
    syn_html = ""
    for w in syn_ant_words:
        syn_html += f'<div style="display:inline-block;width:30%;margin:4px;padding:6px 8px;background:#E0F2F1;border-radius:6px;border:1.5px solid #80CBC4;break-inside:avoid;"><div style="font-weight:bold;color:#26A69A;font-size:12px;margin-bottom:4px;">{w}</div><div style="font-size:10.5px;">Synonym: _____________</div><div style="font-size:10.5px;">Antonym: _____________</div>{write_line()}</div>'

    # Word Web
    ww_html = (f'<div style="text-align:center;margin:8px 0;">'\
               f'<div style="display:inline-block;padding:8px 16px;background:#26A69A;color:white;border-radius:20px;font-weight:bold;font-size:13px;">'\
               f'{word_web_center}</div>'\
               f'<div style="margin-top:12px;">'\
               f'<table style="width:100%;border-collapse:separate;border-spacing:4px;">'\
               f'<tr><td style="text-align:center;"><div style="height:36px;border:2px dashed #B2DFDB;border-radius:8px;"></div></td>'\
               f'<td style="text-align:center;"><div style="height:36px;border:2px dashed #B2DFDB;border-radius:8px;"></div></td></tr>'\
               f'<tr><td style="text-align:center;"><div style="height:36px;border:2px dashed #B2DFDB;border-radius:8px;"></div></td>'\
               f'<td style="text-align:center;"><div style="height:36px;border:2px dashed #B2DFDB;border-radius:8px;"></div></td></tr>'\
               f'</table></div></div>')

    # Sentence Sort
    sort_html = ""
    for idx, sentence in enumerate(sentence_sort_data, 1):
        word_list = sentence.split()
        shuffled = list(word_list)
        random.Random(42 + idx).shuffle(shuffled)
        tags = "".join(f'<span style="display:inline-block;background:#FFF3E0;border:1px solid #FFB74D;padding:2px 8px;margin:2px;border-radius:3px;font-size:11px;">{w}</span>' for w in shuffled)
        sort_html += f'<div style="margin:8px 0;padding:6px 8px;background:#FAFAFA;border:1.5px solid #B2DFDB;border-radius:6px;"><div style="font-size:11px;font-weight:bold;color:#FF7043;margin-bottom:4px;">Sentence {idx}:</div><div style="margin-bottom:4px;">{tags}</div><div style="font-size:10px;color:#888;margin-bottom:4px;">Your answer:</div>{write_line()}</div>'

    # Correct the Sentences
    correct_html = ""
    for s in correct_sentences:
        correct_html += f'<div style="margin:6px 0;font-size:12px;"><span style="color:#E53935;text-decoration:line-through;">{s}</span><br>{write_line()}</div>'

    # Fill in the Blank
    fill_answers = [a for _, a in fill_data]
    fb_bank = word_bank(fill_answers, seed=340)
    fb_items = "".join(fill_blank_with_line(s) for s, _ in fill_data)

    # Word Families activity
    families_html = ""
    if word_families:
        fam_items = ""
        for base_word, related in word_families:
            fam_items += f'<div style="margin:8px 0;padding:6px 8px;background:#E8F5E9;border-radius:6px;border:1.5px solid #A5D6A7;"><div style="font-size:12px;font-weight:bold;color:#26A69A;margin-bottom:4px;">Base word: {base_word}</div><div style="font-size:11px;">Add prefixes/suffixes to make new words:</div>'
            for rw in related:
                fam_items += f'<div style="margin:3px 0 3px 8px;font-size:11px;">&bull; {rw} &rarr; {write_line()}</div>'
            fam_items += '</div>'
        families_html = f'{sectitle("Word Family Builder")}{secnote("Start with the base word, then add word parts to create new words.")}{fam_items}'

    # Learning skills
    skills_html = '<ul style="font-size:12px;margin:4px 0 8px 0;">'
    for s in learning_skills:
        skills_html += f'<li>{s}</li>'
    skills_html += '</ul>'

    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} -- Word Work &amp; Application")}
    {sectitle("Here's What We're Learning")}
    {secnote(learning_text)}
    {skills_html}
    {sectitle("Reading Passage")}
    {secnote("Read the passage. Notice each spelling word in bold.")}
    <div class="story-box">{reading_passage}</div>
    {sectitle("Vocabulary Question")}
    {secnote("Choose the correct answer.")}
    <div class="fb-item"><p>{vocab_question}</p><div style="font-size:12px;">Answer: _______________</div></div>
    {page_break()}
    {sectitle("Synonyms & Antonyms")}
    {secnote("Think of a word that means the SAME thing and a word that means the OPPOSITE.")}
    {syn_html}
    </div>

    <div>
    {sectitle("Word Web")}
    {secnote(word_web_instruction)}
    {ww_html}
    {sectitle("Sentence Sort")}
    {secnote("Unscramble the words to form a correct sentence.")}
    {sort_html}
    {sectitle("Correct the Sentences")}
    {secnote("Each sentence has a capital letter or punctuation mistake. Rewrite it correctly.")}
    {correct_html}
    {sectitle("Fill in the Blank")}
    {secnote("Choose the correct word from the bank.")}
    {fb_bank}
    {fb_items}
    {page_break()}
    {families_html}
    </div>

    <div>
    {sectitle("Context Clues")}
    {secnote("Use the sentence to figure out the word meaning.")}
    <div class="fb-item"><p>{context_clue}</p><div style="font-size:12px;">Answer: _______________</div></div>
    </div>

    </body></html>"""

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