#!/usr/bin/env python3
"""
JFL TTD v1.4 — Adds Mike the Plumber task list to FIREHOUSE zone
New items per Joe's ROB ACTION email (Apr 7):
  - 539 heater
  - SC AC  
  - 15 New St condenser move
  - 15 New St Jules & D room AC
  - Firehouse estimate
  - Firehouse 2005 system — confirm still good?
"""

from docx import Document
from docx.shared import Pt, RGBColor, Inches, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from datetime import datetime

today = datetime.now().strftime("%A, %B %d, %Y")

doc = Document()

# ── Page setup: Landscape ──────────────────────────────────────────────────
section = doc.sections[0]
section.page_width  = Inches(11)
section.page_height = Inches(8.5)
section.left_margin = Inches(0.5)
section.right_margin = Inches(0.5)
section.top_margin = Inches(0.4)
section.bottom_margin = Inches(0.4)

# ── Helpers ────────────────────────────────────────────────────────────────

def set_cell_bg(cell, hex_color):
    tc = cell._tc
    tcPr = tc.find(qn('w:tcPr'))
    if tcPr is None:
        tcPr = OxmlElement('w:tcPr')
        tc.insert(0, tcPr)
    shd = OxmlElement('w:shd')
    shd.set(qn('w:val'), 'clear')
    shd.set(qn('w:color'), 'auto')
    shd.set(qn('w:fill'), hex_color)
    tcPr.append(shd)

def set_cell_top_border(cell, color="auto", sz="12"):
    tc = cell._tc
    tcPr = tc.find(qn('w:tcPr'))
    if tcPr is None:
        tcPr = OxmlElement('w:tcPr')
        tc.insert(0, tcPr)
    tcBorders = OxmlElement('w:tcBorders')
    top = OxmlElement('w:top')
    top.set(qn('w:val'), 'single')
    top.set(qn('w:sz'), sz)
    top.set(qn('w:space'), '0')
    top.set(qn('w:color'), color)
    tcBorders.append(top)
    tcPr.append(tcBorders)

def add_bookmark(paragraph, bookmark_name, bookmark_id):
    run = paragraph.runs[0] if paragraph.runs else paragraph.add_run()
    tag = run._r
    bookmarkStart = OxmlElement('w:bookmarkStart')
    bookmarkStart.set(qn('w:id'), str(bookmark_id))
    bookmarkStart.set(qn('w:name'), bookmark_name)
    tag.addprevious(bookmarkStart)
    bookmarkEnd = OxmlElement('w:bookmarkEnd')
    bookmarkEnd.set(qn('w:id'), str(bookmark_id))
    tag.addnext(bookmarkEnd)

def add_internal_hyperlink(paragraph, bookmark_name, link_text, font_size=9, color="0563C1"):
    hyperlink = OxmlElement('w:hyperlink')
    hyperlink.set(qn('w:anchor'), bookmark_name)
    new_run = OxmlElement('w:r')
    rPr = OxmlElement('w:rPr')
    color_el = OxmlElement('w:color')
    color_el.set(qn('w:val'), color)
    rPr.append(color_el)
    u = OxmlElement('w:u')
    u.set(qn('w:val'), 'single')
    rPr.append(u)
    sz = OxmlElement('w:sz')
    sz.set(qn('w:val'), str(font_size * 2))
    rPr.append(sz)
    new_run.append(rPr)
    t = OxmlElement('w:t')
    t.text = link_text
    new_run.append(t)
    hyperlink.append(new_run)
    paragraph._p.append(hyperlink)
    return hyperlink

def add_para(cell, text, bold=False, size=10, color=None, align=None, strike=False, space_before=0, space_after=2):
    para = cell.add_paragraph()
    para.paragraph_format.space_before = Pt(space_before)
    para.paragraph_format.space_after = Pt(space_after)
    if align:
        para.alignment = align
    run = para.add_run(text)
    run.bold = bold
    run.font.size = Pt(size)
    run.font.strike = strike
    if color:
        run.font.color.rgb = RGBColor.from_string(color)
    return para

# ── Zone data (v1.4) ──────────────────────────────────────────────────────
zones = [
    {
        "emoji": "🔥", "title": "ON FIRE THIS WEEK",
        "bg": "FFF3CD", "border": "FF6B00",
        "items": [
            ("▶", "Call Brad Studio 513 — CAD file for firehouse"),
            ("▶", "Truist letter → Jonathan Cohen (Joe sends as himself)"),
            ("▶", "JLKL transfer — cover PMK check"),
            ("▶", "Architect meeting Wed April 8 @ 10:15 AM"),
            ("▶", "April 30 portfolio restructure — 29 stocks ready?"),
            ("□", "Text Gabe McCabe — 15 min late, New St plan"),
        ]
    },
    {
        "emoji": "🏗️", "title": "FIREHOUSE — 18 New St",
        "bg": "E8F4FD", "border": "2196F3",
        "items": [
            ("▶", "magicplan scan — measure all rooms with iPhone"),
            ("□", "Send floor plans to Ruut24/CAD service"),
            ("□", "Confirm Brad McArthur CAD file (Studio 513)"),
            ("□", "Driveway: cobblestone + grey stone + bluestone"),
            ("□", "HVAC plan: furnace 1F, heat pump 2F, hot water basement"),
            ("□", "Gabe McCabe — New St plans coordination"),
            ("□", "Framer estimates pending"),
            ("□", "Zoning cert → Phil Reed"),
            ("▶", "Mike the Plumber — 539 heater (schedule/estimate)"),
            ("▶", "Mike the Plumber — SC AC (schedule/estimate)"),
            ("▶", "Mike the Plumber — 15 New St condenser move"),
            ("▶", "Mike the Plumber — 15 New St Jules & D room AC"),
            ("▶", "Mike the Plumber — Firehouse full estimate"),
            ("□", "Mike the Plumber — Firehouse 2005 system still good?"),
        ]
    },
    {
        "emoji": "🪵", "title": "TLC / SURFBOX",
        "bg": "F1F8E9", "border": "558B2F",
        "items": [
            ("▶", "Compensation letter → Robert MacArthur"),
            ("▶", "W-2 salary restructure — call MacArthur"),
            ("▶", "Surfbox social media — April 30 go-live"),
            ("□", "Amanda — Epicor credit card surcharge module"),
            ("□", "Edwin elevation to junior manager"),
            ("□", "Neal & Denise — priority call list"),
            ("□", "Judy — staffing/overhead review"),
            ("□", "California Closets Marlton — (609) 655-1899"),
            ("□", "Corner Market 275 W 9th Ship Bottom — decision"),
        ]
    },
    {
        "emoji": "💰", "title": "INVESTING — JFL&KL FUND",
        "bg": "FFF8E1", "border": "F9A825",
        "items": [
            ("▶", "April 30 — Execute 29-stock portfolio"),
            ("▶", "Truist → Self-directed conversion confirm"),
            ("□", "Roth conversion — restructure LLC to W-2 first"),
            ("□", "Fidelity account — confirm Wells Fargo transfer"),
            ("□", "MOSE dashboard — Phase 2 (DCF + Graham Number)"),
            ("□", "Super investor 13F tracker running — check weekly"),
            ("□", "S&P exit: 6591.90 | Dow exit: 46429.49"),
            ("□", "MA, GOOGL, AXP — 3-way convergence BUY ZONE"),
        ]
    },
    {
        "emoji": "🏠", "title": "PERSONAL / FAMILY",
        "bg": "FCE4EC", "border": "E91E63",
        "items": [
            ("▶", "360 King hotel receipt — expense?"),
            ("□", "Keli — new diamond ring (NYC Diamond District next trip)"),
            ("□", "Get Marriott Visa back from daughter (April 13)"),
            ("□", "Rob voice clone — talk to Renee first"),
            ("□", "Juliana — summer job for confidence building"),
            ("□", "Bella — set up her own OpenClaw + AI education"),
            ("□", "Matty (Goodwill Fund) — investment updates?"),
            ("□", "Gio — $225 cash check for driveway work"),
        ]
    },
    {
        "emoji": "🚀", "title": "PROJECTS / NEW VENTURES",
        "bg": "EDE7F6", "border": "673AB7",
        "items": [
            ("▶", "World Cup Pool — Venmo handle, PayPal, domain needed"),
            ("▶", "Lobster Press — waiting for first PRESS email"),
            ("▶", "ReBolt — prototype path (Protolabs $500-1500)"),
            ("□", "T1D App — next step after OpenClaw stable"),
            ("□", "Charleston RE — IOP beach + downtown investment"),
            ("□", "GetFloorplan.com — upload firehouse plans for 3D"),
            ("□", "Local LLM (Qwen) — connect to Outlook/Epicor"),
            ("□", "Mission Control — rebuild with live data"),
        ]
    },
]

# ── Page 1: Header ─────────────────────────────────────────────────────────
header_para = doc.add_paragraph()
header_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
header_para.paragraph_format.space_before = Pt(0)
header_para.paragraph_format.space_after = Pt(2)
run = header_para.add_run(f"JFL TTD  v1.4    |    {today}")
run.bold = True
run.font.size = Pt(13)
run.font.color.rgb = RGBColor(0x1A, 0x1A, 0x2E)

subtitle_para = doc.add_paragraph()
subtitle_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
subtitle_para.paragraph_format.space_before = Pt(0)
subtitle_para.paragraph_format.space_after = Pt(4)
run2 = subtitle_para.add_run("▶ = urgent/in-progress    □ = pen checkbox    |    Tell Rob what's DONE and what to ADD    |    ")
run2.font.size = Pt(8)
run2.font.color.rgb = RGBColor(0x66, 0x66, 0x66)
add_internal_hyperlink(subtitle_para, "completed_log", "📋 View Completed Items Log →", font_size=8, color="0563C1")

# ── Page 1: 2×3 Table ─────────────────────────────────────────────────────
table = doc.add_table(rows=2, cols=3)
table.style = 'Table Grid'

col_width = Inches(3.2)
for row in table.rows:
    for cell in row.cells:
        cell.width = col_width

zone_idx = 0
for row_i in range(2):
    for col_i in range(3):
        z = zones[zone_idx]
        zone_idx += 1
        cell = table.cell(row_i, col_i)

        for p in cell.paragraphs:
            p._element.getparent().remove(p._element)

        set_cell_bg(cell, z["bg"])
        set_cell_top_border(cell, z["border"], "18")

        header_p = cell.add_paragraph()
        header_p.paragraph_format.space_before = Pt(4)
        header_p.paragraph_format.space_after = Pt(3)
        h_run = header_p.add_run(f"{z['emoji']}  {z['title']}")
        h_run.bold = True
        h_run.font.size = Pt(10)
        h_run.font.color.rgb = RGBColor(0x1A, 0x1A, 0x2E)

        for marker, text in z["items"]:
            item_p = cell.add_paragraph()
            item_p.paragraph_format.space_before = Pt(0)
            item_p.paragraph_format.space_after = Pt(2)
            item_p.paragraph_format.left_indent = Pt(4)

            marker_run = item_p.add_run(marker + "  ")
            marker_run.font.size = Pt(9)
            if marker == "▶":
                marker_run.font.color.rgb = RGBColor(0xFF, 0x6B, 0x00)
                marker_run.bold = True
            else:
                marker_run.font.color.rgb = RGBColor(0x44, 0x44, 0x44)

            text_run = item_p.add_run(text)
            text_run.font.size = Pt(9)
            if marker == "▶":
                text_run.bold = True
                text_run.font.color.rgb = RGBColor(0x1A, 0x1A, 0x1A)
            else:
                text_run.font.color.rgb = RGBColor(0x33, 0x33, 0x33)

# ── Page break ─────────────────────────────────────────────────────────────
from docx.enum.text import WD_BREAK_TYPE
page_break = doc.add_paragraph()
run_pb = page_break.add_run()
run_pb.add_break(WD_BREAK_TYPE.PAGE)
page_break.paragraph_format.space_before = Pt(0)
page_break.paragraph_format.space_after = Pt(0)

# ── Page 2: Completed Items Log ────────────────────────────────────────────
log_title_para = doc.add_paragraph()
log_title_para.paragraph_format.space_before = Pt(6)
log_title_para.paragraph_format.space_after = Pt(2)
t_run = log_title_para.add_run("✅  COMPLETED ITEMS LOG")
t_run.bold = True
t_run.font.size = Pt(14)
t_run.font.color.rgb = RGBColor(0x1A, 0x1A, 0x2E)
add_bookmark(log_title_para, "completed_log", 1)

sub_para = doc.add_paragraph()
sub_para.paragraph_format.space_before = Pt(0)
sub_para.paragraph_format.space_after = Pt(8)
s_run = sub_para.add_run(
    "Items you mark DONE are logged here with strikethrough — a reference and idea spark for future planning.\n"
    "This page is NOT printed with your daily TTD. Browse it anytime via the link on page 1."
)
s_run.font.size = Pt(9)
s_run.font.color.rgb = RGBColor(0x55, 0x55, 0x55)
s_run.italic = True

log_table = doc.add_table(rows=1, cols=3)
log_table.style = 'Table Grid'

hrow = log_table.rows[0]
for cell, label in zip(hrow.cells, ["Date Completed", "Zone", "Item"]):
    set_cell_bg(cell, "1A1A2E")
    for p in cell.paragraphs:
        p._element.getparent().remove(p._element)
    hp = cell.add_paragraph()
    hr = hp.add_run(label)
    hr.bold = True
    hr.font.size = Pt(10)
    hr.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)

sample_completed = [
    ("Apr 5, 2026", "🔥 ON FIRE", "Called Jonathan Cohen re: Truist account setup"),
    ("Apr 6, 2026", "🏗️ FIREHOUSE", "Ordered magicplan pro subscription"),
    ("Apr 7, 2026", "💰 INVESTING", "Reviewed 13F filings — Pabrai Q4 positions logged"),
]

for date_str, zone_str, item_str in sample_completed:
    row = log_table.add_row()
    for cell, text in zip(row.cells, [date_str, zone_str, item_str]):
        for p in cell.paragraphs:
            p._element.getparent().remove(p._element)
        cp = cell.add_paragraph()
        cr = cp.add_run(text)
        cr.font.size = Pt(9)
        cr.font.strike = True
        cr.font.color.rgb = RGBColor(0x88, 0x88, 0x88)

for _ in range(12):
    row = log_table.add_row()
    for cell in row.cells:
        for p in cell.paragraphs:
            p._element.getparent().remove(p._element)
        bp = cell.add_paragraph()
        br = bp.add_run("")
        br.font.size = Pt(9)

footer_note = doc.add_paragraph()
footer_note.paragraph_format.space_before = Pt(12)
footer_note.alignment = WD_ALIGN_PARAGRAPH.CENTER
fn_run = footer_note.add_run("JFL TTD v1.4  |  Completed log — not for daily printing  |  Rob 🦞")
fn_run.font.size = Pt(8)
fn_run.italic = True
fn_run.font.color.rgb = RGBColor(0xAA, 0xAA, 0xAA)

doc.save("/Users/joemac/.openclaw/workspace/projects/jfl-ttd-v1.4.docx")
print("✅ Saved jfl-ttd-v1.4.docx")
