#!/usr/bin/env python3
"""Morning Joe's Rundown — Word doc builder for April 5, 2026"""

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

# ── Color palette ────────────────────────────────────────────
NAVY   = RGBColor(0x00, 0x27, 0x5A)   # navy blue headings
GOLD   = RGBColor(0xC9, 0xA0, 0x2C)   # gold accent
WHITE  = RGBColor(0xFF, 0xFF, 0xFF)
DARK   = RGBColor(0x1A, 0x1A, 0x2E)
GRAY   = RGBColor(0x55, 0x55, 0x55)

TODAY  = "Sunday, April 5, 2026"
FNAME  = "/Users/joemac/.openclaw/workspace/projects/daily/Morning_Joes_Rundown_2026-04-05.docx"

# ── Helper: add page number field ───────────────────────────
def add_page_number(run):
    fld = OxmlElement('w:fldChar')
    fld.set(qn('w:fldCharType'), 'begin')
    run._r.append(fld)
    instr = OxmlElement('w:instrText')
    instr.text = 'PAGE'
    run._r.append(instr)
    fld2 = OxmlElement('w:fldChar')
    fld2.set(qn('w:fldCharType'), 'end')
    run._r.append(fld2)

def add_numpages(run):
    fld = OxmlElement('w:fldChar')
    fld.set(qn('w:fldCharType'), 'begin')
    run._r.append(fld)
    instr = OxmlElement('w:instrText')
    instr.text = 'NUMPAGES'
    run._r.append(instr)
    fld2 = OxmlElement('w:fldChar')
    fld2.set(qn('w:fldCharType'), 'end')
    run._r.append(fld2)

# ── Helper: add shaded row to table ─────────────────────────
def shade_cell(cell, hex_color):
    tc = cell._tc
    tcPr = tc.get_or_add_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)

doc = Document()

# ── Margins ──────────────────────────────────────────────────
for section in doc.sections:
    section.top_margin    = Cm(1.8)
    section.bottom_margin = Cm(1.8)
    section.left_margin   = Cm(2.0)
    section.right_margin  = Cm(2.0)
    # Footer with page number
    footer = section.footer
    fp = footer.paragraphs[0]
    fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run_l = fp.add_run("Morning Joe's Rundown  |  April 5, 2026  |  CONFIDENTIAL      Page ")
    run_l.font.size = Pt(8)
    run_l.font.color.rgb = GRAY
    pn = fp.add_run()
    add_page_number(pn)
    pn.font.size = Pt(8)
    pn.font.color.rgb = GRAY
    r2 = fp.add_run(" of ")
    r2.font.size = Pt(8)
    r2.font.color.rgb = GRAY
    np = fp.add_run()
    add_numpages(np)
    np.font.size = Pt(8)
    np.font.color.rgb = GRAY

# ── Default style ────────────────────────────────────────────
style = doc.styles['Normal']
style.font.name = 'Calibri'
style.font.size = Pt(10)

# ═══════════════════════════════════════════════════════════════
# HEADER BLOCK
# ═══════════════════════════════════════════════════════════════
# Navy banner paragraph
hdr = doc.add_paragraph()
hdr.alignment = WD_ALIGN_PARAGRAPH.CENTER
hdr_run = hdr.add_run("🦞  MORNING JOE'S RUNDOWN")
hdr_run.font.name = 'Calibri'
hdr_run.font.size = Pt(22)
hdr_run.font.bold = True
hdr_run.font.color.rgb = NAVY

sub = doc.add_paragraph()
sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
sub_run = sub.add_run(f"Sunday, April 5, 2026  |  Prepared by Rob Lobster 🦞  |  CONFIDENTIAL")
sub_run.font.name = 'Calibri'
sub_run.font.size = Pt(10)
sub_run.font.italic = True
sub_run.font.color.rgb = GOLD

doc.add_paragraph()  # spacer

# ───────────────────────────────────────────────────────────────
def section_heading(label):
    p = doc.add_paragraph()
    run = p.add_run(f"  {label}  ")
    run.font.name = 'Calibri'
    run.font.size = Pt(13)
    run.font.bold = True
    run.font.color.rgb = WHITE
    # Shade the paragraph background
    pPr = p._p.get_or_add_pPr()
    shd = OxmlElement('w:shd')
    shd.set(qn('w:val'), 'clear')
    shd.set(qn('w:color'), 'auto')
    shd.set(qn('w:fill'), '00275A')
    pPr.append(shd)
    p.paragraph_format.space_before = Pt(8)
    p.paragraph_format.space_after  = Pt(4)
    return p

def bullet(text, indent=0):
    p = doc.add_paragraph(style='List Bullet')
    p.paragraph_format.left_indent = Inches(0.25 + indent * 0.2)
    p.paragraph_format.space_after = Pt(2)
    run = p.add_run(text)
    run.font.name = 'Calibri'
    run.font.size = Pt(10)
    return p

def checkbox(text):
    p = doc.add_paragraph()
    p.paragraph_format.left_indent = Inches(0.25)
    p.paragraph_format.space_after = Pt(2)
    run = p.add_run(f"[ ]  {text}")
    run.font.name = 'Calibri'
    run.font.size = Pt(10)
    return p

def body(text, bold_label=None):
    p = doc.add_paragraph()
    p.paragraph_format.space_after = Pt(3)
    if bold_label:
        rl = p.add_run(f"{bold_label}  ")
        rl.font.bold = True
        rl.font.color.rgb = NAVY
        rl.font.name = 'Calibri'
        rl.font.size = Pt(10)
    r = p.add_run(text)
    r.font.name = 'Calibri'
    r.font.size = Pt(10)
    return p

def gold_label(text):
    p = doc.add_paragraph()
    p.paragraph_format.space_after = Pt(1)
    r = p.add_run(text)
    r.font.name = 'Calibri'
    r.font.size = Pt(10)
    r.font.bold = True
    r.font.color.rgb = GOLD
    return p

# ═══════════════════════════════════════════════════════════════
# SECTION 1 — WEATHER
# ═══════════════════════════════════════════════════════════════
section_heading("§1  WEATHER  ☁️")

weather_data = [
    ("Ship Bottom, NJ",    "60°F / Overcast → Rain by afternoon (~3PM). High 55°F. Wind SSW 21 mph, gusts 40 mph. Evening fog. Clears by 9 PM.", "⚠️ Rain incoming — afternoon"),
    ("Tuckerton, NJ",      "62°F / Sunny now → Patchy rain midday, moderate rain by 3PM. High 68°F. Wind SSW 19 mph, gusts 32 mph.", "⚠️ Rain 12–3 PM window — yard heads-up"),
    ("Chesterfield, NJ",   "57°F / Partly cloudy → Rain 12–3 PM. High 65°F. Wind SSW 15 mph. Clears by 9 PM.", "⚠️ Light rain at firehouse this PM"),
    ("Columbia, SC (Bella)","69°F / Partly cloudy → Patchy rain afternoon. High 83°F. Warm & humid.", "☀️ Good morning for Bella"),
    ("Tuscaloosa, AL (Jules)","60°F / Overcast → Clears by noon. High 71°F. Light rain early.", "🌤 Jules: clears up nicely this afternoon"),
    ("Austin, TX (Danielle)","57°F / Overcast → Sunny by noon. High 75°F. NNE winds 12 mph.", "☀️ Nice afternoon in Austin — Danielle good"),
]

tbl = doc.add_table(rows=1, cols=3)
tbl.style = 'Table Grid'
tbl.autofit = False
tbl.columns[0].width = Inches(1.6)
tbl.columns[1].width = Inches(3.4)
tbl.columns[2].width = Inches(2.1)

hdr_cells = tbl.rows[0].cells
for i, h in enumerate(['Location', 'Conditions & Forecast', 'Note']):
    shade_cell(hdr_cells[i], '00275A')
    r = hdr_cells[i].paragraphs[0].add_run(h)
    r.font.bold = True
    r.font.color.rgb = WHITE
    r.font.size = Pt(9)
    r.font.name = 'Calibri'

for loc, cond, note in weather_data:
    row = tbl.add_row().cells
    row[0].text = loc
    row[1].text = cond
    row[2].text = note
    for c in row:
        for para in c.paragraphs:
            for run in para.runs:
                run.font.name = 'Calibri'
                run.font.size = Pt(9)

doc.add_paragraph()

# ═══════════════════════════════════════════════════════════════
# SECTION 2 — MARKETS & INVESTMENTS
# ═══════════════════════════════════════════════════════════════
section_heading("§2  MARKETS & INVESTMENTS  📈")

body("", bold_label="EXIT BASELINES (March 25, 2026):")
body("S&P 500 exit: 6,591.90  |  Dow exit: 46,429.49")

body("", bold_label="FRIDAY APR 4 CLOSE:")
body("S&P 500:  6,582.69  |  Δ vs. exit: −9.21 pts (−0.14%) → BELOW baseline ✅ (defensive move paying off)")
body("Dow Jones: 46,504.67  |  Δ vs. exit: +75.18 pts (+0.16%) → Slightly above baseline")
body("Nasdaq: 21,879.18 (+0.18%)")

body("", bold_label="TREND CONTEXT:")
body("Markets choppy near flat vs. exit. Iran war concerns dampened gains Fri. S&P still below your exit point — the defensive March 25 move looks justified. You're in treasuries, dry powder preserved. April 30 restructuring remains on track.")

body("", bold_label="NOTABLE MOVES (Apr 3–4):")
bullet("LLY (Eli Lilly): +~3%+ after FDA approved its GLP-1 PILL (oral) for weight loss — watch for portfolio inclusion Apr 30")
bullet("HON (Honeywell): +10%+ over recent weeks — strong industrial portfolio, possible watchlist add")
bullet("Watchlist stocks: No confirmed 3%+ single-day moves on your specific 29-stock portfolio targets (markets were near flat Fri)")

body("", bold_label="13F / SUPER INVESTOR UPDATES:")
bullet("No new major 13F filings reported this week (next filing cycle ~mid-May 2026 for Q1). Monitor SA Premium for alerts.")

body("", bold_label="EARNINGS THIS WEEK (Apr 6–11):")
bullet("No major earnings expected this week for core watchlist. Earnings season heats up mid-April — JPM, WFC, BAC report Apr 14–15.")
bullet("APRIL 30 — Your big execution day is 25 days away. Confirm list of 19 buys + 7 sells with MacArthur.")

doc.add_paragraph()

# ═══════════════════════════════════════════════════════════════
# SECTION 3 — COMMODITY PRICES
# ═══════════════════════════════════════════════════════════════
section_heading("§3  COMMODITY PRICES  🪵")

tbl2 = doc.add_table(rows=1, cols=3)
tbl2.style = 'Table Grid'
hdr2 = tbl2.rows[0].cells
for i, h in enumerate(['Commodity', 'Price / Level', 'Signal']):
    shade_cell(hdr2[i], '00275A')
    r = hdr2[i].paragraphs[0].add_run(h)
    r.font.bold = True
    r.font.color.rgb = WHITE
    r.font.size = Pt(9)
    r.font.name = 'Calibri'

commodities = [
    ("Lumber Futures (CME)", "~$596/mbf  (Jan high: $614.5)", "⬇️ Retreating from 3-mo high — restocking faded, housing data weak"),
    ("Framing Lumber", "Elevated vs. late 2025; seasonal uptick Q1 common", "📊 Monitor — Canadian duties ~45% still in place"),
    ("Plywood / CDX", "Trending lower per NAHB latest data", "⬇️ Price advantage window — buy ahead if needed"),
    ("OSB / Sheathing", "Soft; excess supply from slowed housing starts", "➡️ Flat-to-down near term"),
    ("Steel / Rebar", "Tariff uncertainty = elevated; watch Apr policy", "⚠️ Infrastructure demand keeps floor elevated"),
    ("Fuel / Diesel", "Slightly elevated on Iran war premium", "⚠️ Monitor Surfbox delivery cost impact"),
]

for com, price, sig in commodities:
    row = tbl2.add_row().cells
    row[0].text = com
    row[1].text = price
    row[2].text = sig
    for c in row:
        for para in c.paragraphs:
            for run in para.runs:
                run.font.name = 'Calibri'
                run.font.size = Pt(9)

body("\n⚡ TLC SIGNAL: Lumber futures at $596 — modestly soft. Opportunity to lock in Q2 inventory at favorable pricing before spring construction demand peaks. Review open POs with Paul/Edwin.")
doc.add_paragraph()

# ═══════════════════════════════════════════════════════════════
# SECTION 4 — LOCAL NEWS & ZONING
# ═══════════════════════════════════════════════════════════════
section_heading("§4  LOCAL NEWS & ZONING  🏗️")

bullet("LBI / Ocean County: No major zoning or planning board decisions confirmed this week. Next Ocean County Planning Board meeting — check planning.co.ocean.nj.us for April calendar.")
bullet("Ship Bottom: Corner Market deal (275 W 9th St) — no new permits flagged. 50/50 partnership evaluation ongoing.")
bullet("Chesterfield Township: Firehouse (18 New St, Block 300, Lot 12) — in NJ Redevelopment Plan. Architect meeting with Brad scheduled WEDNESDAY April 8 at 10:15 AM.")
bullet("Tuckerton TLC Zoning: Zoning Certificate of Compliance (Block 46, Lots 7 & 9, B-2) — drafted, pending submission to Phil Reed. Surfbox accessory use framing in place.")
bullet("NJ Construction Industry: Spring season underway — contractor traffic should pick up through April. Tariffs on Canadian lumber (45% combined duties) keeping pricing elevated vs. pre-2024 norms.")
bullet("NJ Shore Real Estate: Market active — Keli's offices (Ship Bottom + Crosswicks) entering peak season. Recommend checking MLS activity.")

doc.add_paragraph()

# ═══════════════════════════════════════════════════════════════
# SECTION 5 — TODAY'S SCHEDULE
# ═══════════════════════════════════════════════════════════════
section_heading("§5  TODAY'S SCHEDULE  📅")

gold_label("TODAY — Sunday, April 5")
bullet("No hard-scheduled cron reminders for today specifically")
bullet("Rain expected this PM — indoor/planning day opportunity")
bullet("Review April 30 portfolio restructuring plan (25 days out)")
bullet("Surfbox social media program — April 30 go-live target approaching")

gold_label("COMING UP THIS WEEK:")
bullet("MON Apr 6 — 7:30 AM ET: Transfer money into JLKL to cover PMK check (cron reminder set)")
bullet("MON Apr 6 — 8:00 AM ET: Text Gabe McCabe — 15 min late, discuss New Street plan (cron reminder set)")
bullet("MON Apr 6 — 8:00 AM: Daily Mission Tasks cron fires")
bullet("WED Apr 8 — 10:15 AM: Brad (architect) meeting at firehouse, 18 New St Crosswicks (cron reminder set)")
bullet("MON Apr 6 — 9:00 AM: Switch back to Claude Sonnet (cron set for Monday)")
bullet("APR 7: Steelers voluntary workouts begin (NFL offseason)")
bullet("APR 23: NFL Draft begins")
bullet("APR 30: 🔴 MAJOR — Portfolio restructuring day. 7 sells, 19 buys → 29-stock portfolio")
bullet("APR 30: Surfbox social media program go-live target")
bullet("ONGOING: Easter family trip to Charleston — Danielle, Bella, Jules, Joe + Keli")

doc.add_paragraph()

# ═══════════════════════════════════════════════════════════════
# SECTION 6 — ACTION CARD
# ═══════════════════════════════════════════════════════════════
section_heading("§6  ACTION CARD  ✅")

gold_label("💻 Mac / Tech")
checkbox("Claim $200 Anthropic usage credit — claude.ai/settings/usage (Daily Mission cron rejected yesterday)")
checkbox("Review OpenClaw cron job errors (Daily Mission Tasks threw LLM rejection error)")
checkbox("Set up Bella's OpenClaw + AI education (ongoing)")

gold_label("📞 Calls to Make")
checkbox("Text Gabe McCabe — Monday AM, 15 min late, New Street plan")
checkbox("Call/text Paul Devaney — yard update, any staffing issues")
checkbox("Follow up with Robert MacArthur (CPA) — April 30 portfolio tax strategy, Roth conversion")
checkbox("Call Ray O'Connor re: colorant industry opportunity (meeting at Charleston Easter)")
checkbox("Check in with Neal & Denise — outside sales pipeline (Amon, Pagnotta targets)")

gold_label("🏚 Firehouse (18 New St, Crosswicks)")
checkbox("WEDNESDAY: Architect meeting with Brad, 10:15 AM — bring floor plan markups")
checkbox("Decide: maintain or cancel NJ Redevelopment Plan (luxury SFR vs. multi-lot)")
checkbox("Continue Firehouse marketing to developers/architects (central/south NJ, Princeton, Philly)")
checkbox("HVAC plan finalize: furnace (1st), heat pump (2nd), gas radiator (basement)")
checkbox("Historic tax credit research — National Register of Historic Places implications")

gold_label("🏗 TLC / Surfbox")
checkbox("Review open POs — lock in Q2 lumber pricing while futures soft (~$596/mbf)")
checkbox("Epicor Min/Max inventory system — status check with Amanda")
checkbox("Credit card surcharge module — Amanda update?")
checkbox("Surfbox social media: one video per store per week — April 30 go-live APPROACHING")
checkbox("Staffing/overhead reduction — Judy review")
checkbox("Edwin junior manager elevation — finalize")
checkbox("Concrete drain install — target before Easter?")
checkbox("Equipment: used diesel dually forklift + low forklift for Tuckerton Yard")
checkbox("California Closets partnership — status?")

gold_label("🏠 Properties")
checkbox("Corner Market (275 W 9th, Ship Bottom) — 50/50 partnership decision")
checkbox("Zoning Certificate of Compliance — submit to Phil Reed (Block 46, Lots 7 & 9)")
checkbox("Brother Matt property — fair buyout conversation")
checkbox("Chesterfield parcels (Block 301, Lots 10 & 12) — property tax challenge status")
checkbox("Gio driveway work — $225 cash check to Joe's parents still owed")

gold_label("👨‍👩‍👧 Family / Personal")
checkbox("Easter Charleston family trip — confirm logistics, everyone coordinated")
checkbox("Jules (Alabama) — confidence-building plan; waitressing summer job idea")
checkbox("Bella (USC Columbia) — varsity soccer tryout fall; pivot to AI/CS minor")
checkbox("Danielle (Austin) — check in; she's near where Rob passed away 🦞")
checkbox("Keli — anniversary was April 3 🎉 Hope it was great. Make sure she feels appreciated.")
checkbox("GLP-1 / weight research — 1,500 cal/day high-protein, target 185-195 lbs")
checkbox("Mom (84 in Sept) + Dad (87 in Oct) — parent check-in")

gold_label("🎒 Errands")
checkbox("Gio check — $225 cash/check to parents")

gold_label("📆 Coming Up This Week")
checkbox("Mon 4/6: Transfer JLKL $ for PMK check")
checkbox("Mon 4/6: Text Gabe McCabe (New St)")
checkbox("Wed 4/8: Architect Brad — 10:15 AM Firehouse")
checkbox("Apr 30: Portfolio restructuring — 29-stock JFL&KL FUND launch 🚀")

doc.add_paragraph()

# ═══════════════════════════════════════════════════════════════
# SECTION 7 — SPORTS
# ═══════════════════════════════════════════════════════════════
section_heading("§7  SPORTS  🏆")

sports_data = [
    ("Yankees ⚾",     "In-season (MLB). No score found for Apr 4 — possible off day or game in progress.", "Season record: ~6-1 home | Full scoreboard at espn.com/mlb"),
    ("Phillies ⚾",    "Apr 4: Phillies 2, Rockies 1 (PHI win — Justin Crawford walk-off). Phillies record 4-3 away.", "Phillies doing work early!"),
    ("Knicks 🏀",      "Apr 4 (Fri night): Knicks 136, Bulls 96 💥 BLOWOUT. OG Anunoby 31 pts. Brunson 17 pts / 10 ast. +47 pt lead.", "Knicks rolling — 2nd straight W"),
    ("Steelers 🏈",    "OFFSEASON. New HC Mike McCarthy. Traded for WR Michael Pittman Jr. from Colts. Voluntary workouts begin Apr 7. Draft Apr 23.", "No game — offseason news"),
    ("USMNT ⚽",       "No match Apr 3-4. Next major fixture TBD — check ussoccer.com.", "Offseason / no fixture"),
    ("Liverpool FC ⚽", "Apr 4: Man City 4-0 Liverpool (FA Cup QF). Brutal loss — knocked out of FA Cup. Salah had a pen saved.", "Ouch. Mo Salah shadow of himself per Guardian."),
]

tbl3 = doc.add_table(rows=1, cols=3)
tbl3.style = 'Table Grid'
hdr3 = tbl3.rows[0].cells
for i, h in enumerate(['Team', 'Result / Status', 'Note']):
    shade_cell(hdr3[i], '00275A')
    r = hdr3[i].paragraphs[0].add_run(h)
    r.font.bold = True
    r.font.color.rgb = WHITE
    r.font.size = Pt(9)
    r.font.name = 'Calibri'

for team, result, note in sports_data:
    row = tbl3.add_row().cells
    row[0].text = team
    row[1].text = result
    row[2].text = note
    for c in row:
        for para in c.paragraphs:
            for run in para.runs:
                run.font.name = 'Calibri'
                run.font.size = Pt(9)

doc.add_paragraph()

# ═══════════════════════════════════════════════════════════════
# SECTION 8 — TOKEN SPEND
# ═══════════════════════════════════════════════════════════════
section_heading("§8  TOKEN SPEND  💰")

body("", bold_label="YESTERDAY (Apr 4) ESTIMATED:")
body("Daily Mission Tasks cron: FAILED (LLM rejection — Anthropic usage credit limit hit). Minimal spend.")
body("Morning Rundown cron (Apr 4): Errored. Low spend.")
body("Rob Gmail cron: Running every 2 min — approx 720 checks/day × ~$0.002 avg = ~$1.44/day on Gmail checks alone.")
body("Other session turns: Estimated ~$2–5 for conversational turns.")
body("Estimated Apr 4 total: ~$4–6")

body("", bold_label="⚠️ ACTION NEEDED:")
bullet("Claim $200 Anthropic credit at claude.ai/settings/usage — Daily Mission cron is failing due to usage limit")
bullet("Consider reducing Gmail cron frequency (currently every 2 min = very aggressive)")

body("", bold_label="MONTHLY RUNNING TOTAL (Apr 2026):")
body("Apr 1–5 estimate: ~$15–25 (based on cron frequency + session activity)")
body("Note: Exact billing visible at claude.ai/settings/usage — check after claiming credit.")

doc.add_paragraph()

# ── Sign-off ────────────────────────────────────────────────
sign = doc.add_paragraph()
sign.alignment = WD_ALIGN_PARAGRAPH.CENTER
r1 = sign.add_run("── Rob Lobster 🦞  |  Make good decisions today, Joe.  |  ")
r1.font.italic = True
r1.font.color.rgb = NAVY
r1.font.size = Pt(10)
r1.font.name = 'Calibri'
r2 = sign.add_run("\"Here Comes the Sun\" ☀️")
r2.font.italic = True
r2.font.color.rgb = GOLD
r2.font.size = Pt(10)
r2.font.name = 'Calibri'

doc.save(FNAME)
print(f"SAVED: {FNAME}")
