#!/usr/bin/env python3
"""
Build Idea Factory Day 1 Report — professional Word document
"""

from docx import Document
from docx.shared import Pt, RGBColor, Inches, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
import copy

# ── Colors ──────────────────────────────────────────────────────────────────
NAVY  = RGBColor(0x00, 0x2B, 0x5C)
GOLD  = RGBColor(0xC5, 0x9E, 0x3C)
WHITE = RGBColor(0xFF, 0xFF, 0xFF)
BLACK = RGBColor(0x00, 0x00, 0x00)
LIGHT_GOLD_BG = RGBColor(0xFF, 0xF9, 0xED)   # highlight for 5/5 ideas
DARK_GREEN_ACCENT = RGBColor(0x1A, 0x6B, 0x2A)  # star color

def set_cell_bg(cell, hex_color):
    """Set table cell background 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)

def add_paragraph_border(paragraph, top=None, bottom=None):
    """Add borders to a paragraph."""
    pPr = paragraph._p.get_or_add_pPr()
    pBdr = OxmlElement('w:pBdr')
    if bottom:
        bd = OxmlElement('w:bottom')
        bd.set(qn('w:val'), 'single')
        bd.set(qn('w:sz'), '6')
        bd.set(qn('w:space'), '1')
        bd.set(qn('w:color'), 'C59E3C')
        pBdr.append(bd)
    pPr.append(pBdr)

def stars(score):
    """Return star string for score."""
    filled = '★' * score
    empty  = '☆' * (5 - score)
    return filled + empty

# ── Raw idea data ─────────────────────────────────────────────────────────
IDEAS = [
    (1,  "PERMIT RANGER",            "AI preps all permit docs; trained human runners attend physical inspections and municipal offices.",
     "Per-permit flat fee ($150–$500) + contractor subscriptions",
     "Licensed municipal relationships + local regulatory knowledge in proprietary AI workflows",
     5),
    (2,  "SITE BOSS",                "AI-Augmented Site Supervisors available on-demand via app — Uber for job-site oversight.",
     "Day-rate billing ($600–$1,200/day) + 20% platform fee",
     "Certified supervisor network (12–18 months to build) + insurance/bonding barriers",
     4),
    (3,  "LAST MILE LUMBER",         "Premium fractional lumber delivery — AI routing and cut lists, humans deliver with precision to constrained sites.",
     "Per-delivery premium fee + contractor subscriptions; 40–60% material margin + $75–$150 delivery",
     "Proprietary inventory AI + TLC supplier relationships + first-mover in premium fractional delivery",
     5),
    (4,  "STORAGE CONCIERGE",        "Full-service AI-catalogued storage: say 'bring me my red bike' — it arrives next day.",
     "Monthly pod fee ($150–$400) + retrieval fee ($35–$75/trip) + white-glove packing",
     "Physical pod infrastructure + proprietary inventory AI creates switching costs once items are catalogued",
     5),
    (5,  "ELDER LINK",               "AI dispatches and coordinates elder care — human caregivers focus 100% on physical care, zero paperwork.",
     "Monthly care plan ($2,500–$6,000) + family dashboard sub ($49/mo)",
     "Elder care regulatory licensing + proprietary AI care documentation reduces liability",
     2),
    (6,  "TRADES ACADEMY LIVE",      "6-week trades training: AI handles theory/testing, humans run intensive hands-on labs.",
     "Program tuition ($4,000–$8,000/cohort) + employer placement fees + curriculum licensing",
     "Industry certifications + employer partnerships + capital-intensive physical training facilities",
     3),
    (7,  "DOCK MASTER AI",           "Marine survey with AI pre-loaded historical data and defect patterns — faster, cheaper, more accurate.",
     "Per-survey flat fee ($350–$800) + marina operator subscriptions + insurance B2B contracts",
     "Certified surveyor credentials + proprietary defect database + Jersey Shore marina relationships",
     3),
    (8,  "RENO READY",               "Homeowner AI-designs the project; Reno Ready physically executes — measuring, sourcing, coordinating contractors.",
     "10–15% PM fee + 10–20% materials markup + contractor/supplier referral fees",
     "Local contractor network + TLC supplier relationship + licensed insured PM creates trust",
     5),
    (9,  "CLEAN SLATE PROPERTY",     "AI-managed property management at 4–6% fee vs. industry 8–12%; humans handle only physical work.",
     "Monthly management fee (4–6% gross rent) + maintenance markup (10%) + premium 24hr response tier",
     "AI cost structure incumbents can't replicate without rebuilding; proprietary maintenance dispatch AI",
     5),
    (10, "BLUEPRINT BUILDER",        "AI generates residential plans; licensed architect/engineer stamps and reviews at 80% lower cost.",
     "Per-project fee ($500–$3,000) + builder subscriptions + white-label for contractors",
     "Licensed PE/AE credentials are government-granted monopoly + proprietary quality-check AI",
     4),
    (11, "MATERIAL FLOW",            "AI-powered materials procurement broker — one-click purchasing from AI-generated take-offs.",
     "Broker margin 5–12% on materials + SaaS sub ($99–$299/mo) + white-label licensing to lumber yards",
     "Supplier API integrations (12–18 months to build) + volume discounts + switching costs",
     5),
    (12, "SOIL TRUTH",               "Free AI landscape plan as lead-gen funnel; revenue from professional installation.",
     "Free plan (lead gen) + installation contracts ($5K–$50K) + maintenance subs ($150–$400/mo)",
     "AI plan loss leader creates conversion funnel competitors can't replicate cost-effectively",
     2),
    (13, "SHORE STAGER",             "Premium physical staging planned by AI (what sells to which buyer) but executed by human stagers.",
     "Per-staging fee ($3,000–$15,000 luxury) + furniture rental monthly + inventory resale",
     "High-quality furniture inventory capital moat + AI market model + top realtor relationships",
     5),
    (14, "FLOOD PROOF",              "End-to-end coastal flood protection: AI risk assessment → licensed survey → contractor remediation.",
     "Assessment ($300–$500) + elevation cert ($600–$1,200) + 10–15% PM fee + insurance advocacy retainer",
     "Licensed surveyor relationships + FEMA expertise + TLC contractor network for remediation",
     5),
    (15, "DIGITAL DEED",             "AI title search (95% faster, 60% cheaper) + licensed title insurance partner for policy issuance.",
     "Per-search fee ($150–$400) + title insurance premium sharing + closing coordination fee ($300–$600)",
     "Title plant access in specific counties + underwriter partnership + speed creates realtor loyalty",
     3),
    (16, "SEPTIC INTEL",             "IoT-monitored septic health with AI failure prediction — auto-schedules service before problems occur.",
     "Sensor install ($400–$800) + monitoring sub ($29/mo) + pumping service ($350–$600) + NJ cert ($300–$500)",
     "IoT hardware switching costs + proprietary failure prediction model + NJ real estate regulatory requirement",
     4),
    (17, "ROOF INTEL",               "Drone AI roof inspection → instant report → certified roofer dispatched from preferred network.",
     "Contractor referral fee (8–12% job value) + property manager sub + homeowner report ($99–$199)",
     "Drone+AI model trained on millions of roofs + contractor network + insurance company certifications",
     4),
    (18, "CONCRETE EVIDENCE",        "AI-augmented materials testing: instant analysis and reporting vs. 3–5 day industry standard.",
     "Per-test fee ($150–$500) + GC monthly contracts ($2K–$10K/mo) + certified lab services",
     "AASHTO/ASTM certifications + capital-intensive lab equipment + speed creates GC loyalty",
     2),
    (19, "VINTAGE VAULT",            "AI values and lists estate items across all platforms simultaneously; humans handle pickup/delivery.",
     "Commission on sales (30–40%) + flat-fee cleanout ($500–$3,000) + premium authentication ($50–$200/item)",
     "Proprietary pricing AI trained on thousands of estates + geographic market density for logistics",
     3),
    (20, "GREYWATER GUARDIAN",       "IoT water quality monitoring with AI detection; certified technicians dispatched for physical fixes.",
     "Equipment install ($500–$2,000) + monitoring sub ($39–$89/mo) + filter replacement/maintenance",
     "IoT switching costs + proprietary regional water quality database + compliance documentation lock-in",
     3),
    (21, "LIEN SHIELD",              "Construction lien automation: AI tracks deadlines, generates docs, attorneys only for escalations.",
     "Monthly sub ($49–$199/mo) + per-lien filing fee ($75–$200) + attorney referral for escalations",
     "Regulated legal space + contractor retention once workflow embedded + first-mover NJ/PA",
     4),
    (22, "SURF CITY SOLAR",          "AI-designed, human-installed coastal NJ solar — AI handles all NJ incentive paperwork automatically.",
     "Installation fee ($15K–$50K) + financing origination (3–5%) + monitoring sub ($15/mo)",
     "NJ SREC market expertise + AI permitting eliminates 3–4 week bottleneck + coastal concentration",
     4),
    (23, "STORM READY SERVICES",     "Subscription storm prep for coastal homeowners — crews dispatched when forecast hit, guaranteed response.",
     "Annual membership ($500–$1,500/yr) + storm activation fee ($500–$2,500/event) + off-season services",
     "Pre-committed customer relationships + coordinated crew dispatch complexity + NJ coastal geography",
     5),
    (24, "BUILD TRACK",              "AI scheduling platform auto-adjusts when delays hit and texts all affected parties proactively.",
     "SaaS sub ($99–$299/mo per GC) + supplier integration fee + insurance discount partnerships",
     "Deep supplier integrations (TLC) + insurance partnerships + data flywheel improves AI over time",
     4),
    (25, "TRUST DEED",               "AI drafts estate docs; licensed attorney reviews; platform manages storage and event-triggered actions.",
     "Setup fee ($500–$2,000) + annual doc management sub ($99/yr) + probate coordination ($1,500–$5,000)",
     "Licensed attorney supervision required + proprietary doc management creates lock-in + decades-long trust",
     2),
    (26, "SAFETY SCREEN",            "Contractors submit daily job-site photos; AI flags OSHA violations; monthly physical safety audit.",
     "Monthly sub ($199–$499/active site) + physical audit fee ($300–$600) + insurance revenue sharing",
     "OSHA compliance specialization + insurance referral engine + data flywheel improves detection model",
     4),
    (27, "NANO STORAGE",             "Hyperlocal 5x5 weatherproof micro-pods with AI inventory and app-based access/delivery.",
     "Monthly rental ($75–$150/mo) + per-retrieval delivery ($25–$45) + white-glove packing service",
     "Physical pod infrastructure + software moat + HOA/apartment complex distribution partnerships",
     5),
    (28, "HOME DEBRIEF",             "AI pre-analyzes listing photos before inspector arrives — faster inspection, instant report.",
     "Per-inspection fee ($400–$700), 2-hour report delivery, insurance portfolio inspection partnerships",
     "Speed creates realtor loyalty + defect prediction model improves with each inspection + licensure barrier",
     3),
    (29, "SHORE HAUL",               "AI-optimized junk removal — customer photos items, AI prices and dispatches nearest crew instantly.",
     "Per-job fee ($150–$800) + resale revenue on valuable items + recycling material revenue",
     "Route optimization efficiency + TLC reclaimed lumber partnership + app-based speed advantage",
     4),
    (30, "GRADE MASTER",             "AI pre-processes satellite/deed data before surveyor arrives — 60% less field time, 24hr report delivery.",
     "Per-survey fee ($800–$3,000) + rush premium (50% surcharge) + GC subscription for frequent surveys",
     "Licensed surveyor credentials + speed advantage creates realtor/lender loyalty + proprietary AI",
     3),
    (31, "PANEL READY",              "AI assesses electrical needs + handles permits; licensed electricians install panel upgrades for EV/solar.",
     "Per-project fee ($3,000–$8,000) + EV/solar monitoring sub + contractor platform licensing fees",
     "NJ utility interconnection expertise + AI permitting speed (3 weeks → 3 days) + coastal EV first-mover",
     3),
    (32, "PIER PRESSURE INSPECTIONS","AI-drone dock/pier inspection → licensed engineer stamps → repair crew dispatched, annual subscription.",
     "Annual sub ($400–$800) + repair PM fees (10–20%) + emergency inspection premium",
     "Coastal NJ waterway permit expertise + drone+engineer credential combination + recurring sub revenue",
     4),
    (33, "CONTRACTOR BOND",          "AI-powered contractor insurance marketplace — instant optimized quotes, licensed agent closes the sale.",
     "Insurance commission (10–15%) + bonding fee (1–3% of bond) + compliance management sub ($49/mo)",
     "Licensed agent regulatory requirement + actuarial data advantage + TLC distribution to contractors",
     4),
    (34, "BEACH BLOCK ENERGY",       "AI energy audit + NJ rebate auto-applications + certified contractor dispatch for coastal homes.",
     "Audit fee ($199–$399) + PM fee (8–12%) + rebate processing ($99–$299) + contractor referral fees",
     "NJ rebate program expertise + contractor network + AI calibrated to NJ coastal climate",
     4),
    (35, "INVENTORY INTELLIGENCE",   "AI inventory management built for independent lumber yards on Epicor/Eagle — demand prediction, auto POs.",
     "SaaS sub ($499–$1,999/mo) + implementation fee ($5K–$20K) + inventory health consulting",
     "Deep Epicor/Eagle integration = switching costs + building materials demand model + TLC as pilot/case study",
     5),
    (36, "RENTAL RUNNER",            "AI-powered equipment rental — real-time availability, instant pricing, optimized delivery routing.",
     "Rental fee markup (30–50%) + delivery fee ($75–$200) + equipment training + contractor sub",
     "Equipment fleet capital moat + utilization AI reduces idle time (#1 profitability driver in rental)",
     3),
    (37, "PAINT PREDICTOR",          "Free AI color consultation tool drives customers into TLC + books painters through contractor network.",
     "Free AI tool (lead gen) + painting booking commission (15% job value) + TLC paint sales",
     "TLC Benjamin Moore relationship is distribution moat + near-zero customer acquisition via free AI tool",
     5),
    (38, "DOCK LODGE",               "AI-managed marina platform: slip reservations, pricing, scheduling, pump-out — reduces marina staff 40%.",
     "Platform fee/marina ($500–$2,000/mo) + 2% transaction fee on slip revenue + premium app sub",
     "Marina operator relationships sticky once integrated + proprietary wait list algorithm + NJ coastal concentration",
     3),
    (39, "CLAIMS COMMANDER",         "AI generates comprehensive damage estimate/claim package; licensed public adjuster presents to insurer.",
     "Contingency fee (10–15% of settlement) + documentation service ($300–$500) + property manager retainer",
     "Licensed public adjuster credentials + AI damage model more accurate than manual + speed advantage",
     4),
    (40, "HEAT MAP HOMES",           "Hyper-local coastal NJ real estate analytics — micro-pricing, rental yield, storm risk, flood maps.",
     "Realtor sub ($199/mo) + investor sub ($399/mo) + pay-per-report ($49–$149) + data licensing to lenders",
     "Coastal NJ-specific data model unique + storm/flood data compliance value + Keli's realtor distribution",
     5),
    (41, "GROUND ANCHOR",            "AI pre-underwrites small business loans in minutes + identifies optimal lenders; licensed broker closes.",
     "Origination fee (1–2% loan amount) + consulting retainer + lender partner referral fees",
     "SBA licensing + lender relationships hard to build + proprietary pre-underwriting AI speed advantage",
     3),
    (42, "STORM DOORS",              "AI measures windows via photos (exact specs) → certified installers execute → auto-generates insurance docs.",
     "Product + install package ($800–$3,500/window) + financing origination (2–3%) + insurance doc service ($99)",
     "AI measurement eliminates most common error source in window industry + NJ insurance expertise + TLC distribution",
     4),
    (43, "HABITAT HUB",              "AI slashes affordable housing pre-development costs (design, permitting, financing) — making small projects viable.",
     "Developer fee (5–8% project cost) + property management fee (4–6% rents) + NJ affordable housing credit advisory",
     "NJ COAH regulatory expertise + AI pre-development cost reduction makes otherwise unviable projects work",
     3),
    (44, "SPILL PROOF",              "AI generates remediation plan + regulatory filings; licensed professionals execute physical soil/groundwater work.",
     "PM fee (12–18% remediation cost) + monitoring sub ($500–$1,500/mo) + regulatory filing ($2K–$10K/filing)",
     "Licensed PE/PG credentials + NJ DEP regulatory expertise + site data flywheel improves accuracy",
     2),
    (45, "FIBER FLASH",              "AI-scheduled fiber installation for coastal NJ — AI routes crews, crews execute at AI-optimized pace.",
     "Per-installation project fee ($500–$3,000) + commercial network build contracts + maintenance sub",
     "Physical installation expertise built over years + local telco relationships + AI routing cost advantage",
     2),
    (46, "DOCK BLOCK LUMBER",        "Specialty marine-grade, ipe, and pressure-treated dock lumber — products AI-commoditized yards won't stock.",
     "Lumber at 30–50% premium over commodity + custom cutting service + delivery premium + contractor sub pricing",
     "Specialty inventory capital + supplier relationships + TLC infrastructure already in place",
     5),
    (47, "SMART SHAKE",              "AI calculates exact bulk material quantities from photos — no over-ordering; GPS-tracked delivery.",
     "Material sales at standard margin + $50–$150 delivery fee + AI calc free (lead gen) + contractor sub",
     "AI accuracy reduces waste (huge value prop) + route optimization cuts delivery cost + TLC fleet existing",
     5),
    (48, "CODE KEEPER",              "AI-powered permit review platform for NJ municipalities — 80% of residential reviews automated.",
     "SaaS sub per municipality ($2K–$10K/mo) + implementation fee + ongoing support contract",
     "Government procurement relationships take years + massive switching costs once integrated + NJ code expertise",
     3),
    (49, "NEST WATCHER",             "AI-managed coastal NJ vacation rental service at 12–18% fee vs. traditional 25–35%.",
     "Management fee (12–18% gross rental) + cleaning service fee + emergency response + onboarding ($500/property)",
     "AI dynamic pricing generates 15–25% more revenue + cleaning crew network + NJ coastal concentration",
     5),
    (50, "BRIDGE BUILDERS",          "AI-vetted trades staffing: license check, background, skills test — plus human account managers on job sites.",
     "Placement fee (18–22% first-year salary) + hourly markup (30–40% temp) + GC platform sub",
     "AI screening speed + human relationship layer creates trust pure-digital platforms can't replicate",
     4),
]

# Top 10 by Joe-Fit (score desc, then idea number asc)
TOP10_RATIONALE = [
    (4,  "STORAGE CONCIERGE",     5, "Joe already has Surfbox pods, trucks, and customers. The AI inventory + 'bring me my stuff' app is the upgrade layer that turns a commodity storage business into a premium tech-defensible service."),
    (3,  "LAST MILE LUMBER",      5, "TLC already exists. AI-optimized fractional delivery turns commodity truck runs into a premium differentiated service contractors will pay a premium for."),
    (35, "INVENTORY INTELLIGENCE",5, "Joe runs TLC on Epicor/Eagle — he lives this problem daily. He could be the first customer AND a founder. Clearest tech/business intersection in the list."),
    (37, "PAINT PREDICTOR",       5, "TLC sells Benjamin Moore paint. A free AI color tool that funnels customers into TLC stores and books painters through the contractor network — zero capital, high leverage."),
    (49, "NEST WATCHER",          5, "Joe and Keli own coastal NJ properties. They ARE the first customer. AI dynamic pricing captures more revenue; 12–18% fee crushes the 25–35% incumbents."),
    (47, "SMART SHAKE",           5, "TLC already sells bulk materials and has delivery trucks. AI quantity calculation eliminates the #1 customer frustration (over/under ordering). Direct feature extension."),
    (46, "DOCK BLOCK LUMBER",     5, "Specialty marine-grade lumber TLC doesn't currently stock — 30–50% premium margins, same infrastructure. Could launch as a TLC division tomorrow."),
    (40, "HEAT MAP HOMES",        5, "Keli is a realtor, Joe is a real estate investor — they ARE the target customer. Coastal NJ-specific analytics with flood/storm risk data is unique and defensible."),
    (11, "MATERIAL FLOW",         5, "TLC is both the natural white-label partner AND the customer. Locking in the contractor base with AI-powered procurement creates compounding switching costs."),
    (14, "FLOOD PROOF",           5, "Coastal NJ is ground zero for flooding. Joe owns at-risk properties. TLC serves the remediation contractors. Market gets bigger every year — not smaller."),
]

# ── Build Document ────────────────────────────────────────────────────────
doc = Document()

# Page margins — tighter for compact print
for section in doc.sections:
    section.top_margin    = Inches(0.75)
    section.bottom_margin = Inches(0.75)
    section.left_margin   = Inches(0.9)
    section.right_margin  = Inches(0.9)

# ── Helper: apply Calibri font to a run ──────────────────────────────────
def fmt(run, size=10, bold=False, italic=False, color=None):
    run.font.name = 'Calibri'
    run.font.size = Pt(size)
    run.font.bold = bold
    run.font.italic = italic
    if color:
        run.font.color.rgb = color

def add_para(doc, text='', align=WD_ALIGN_PARAGRAPH.LEFT, space_before=0, space_after=4):
    p = doc.add_paragraph()
    p.alignment = align
    p.paragraph_format.space_before = Pt(space_before)
    p.paragraph_format.space_after  = Pt(space_after)
    if text:
        r = p.add_run(text)
        fmt(r)
    return p

# ═══════════════════════════════════════════════════════════════════════════
# TITLE PAGE
# ═══════════════════════════════════════════════════════════════════════════
# Top spacer
for _ in range(5):
    p = doc.add_paragraph()
    p.paragraph_format.space_after = Pt(0)

# Main title
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(8)
r = p.add_run('IDEA FACTORY — DAY 1 OF 21')
r.font.name = 'Calibri'
r.font.size = Pt(32)
r.font.bold = True
r.font.color.rgb = NAVY

# Gold rule (simulate with border or em-dash row)
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(6)
r = p.add_run('━' * 42)
r.font.name = 'Calibri'
r.font.size = Pt(14)
r.font.color.rgb = GOLD

# Subtitle
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(6)
r = p.add_run('OBSOLESCENCE ARBITRAGE PROMPT')
r.font.name = 'Calibri'
r.font.size = Pt(18)
r.font.bold = True
r.font.color.rgb = GOLD

# Date
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(30)
r = p.add_run('April 8, 2026')
r.font.name = 'Calibri'
r.font.size = Pt(14)
r.font.color.rgb = NAVY

# Prompt box (italicized description)
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(12)
p.paragraph_format.left_indent  = Inches(1)
p.paragraph_format.right_indent = Inches(1)
r = p.add_run(
    'Assume 75% of global population has access to a personal AI agent as capable as a '
    'college-educated assistant within 3–5 years. What businesses/roles lose their value? '
    'What residual human need remains? What new business serves that need?'
)
r.font.name = 'Calibri'
r.font.size = Pt(11)
r.font.italic = True
r.font.color.rgb = RGBColor(0x44, 0x44, 0x44)

# Stats line
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(6)
r = p.add_run('50 Ideas  ·  21-Day Series  ·  Generated by Rob Lobster 🦞')
r.font.name = 'Calibri'
r.font.size = Pt(11)
r.font.bold = True
r.font.color.rgb = NAVY

# Gold rule bottom
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(0)
r = p.add_run('━' * 42)
r.font.name = 'Calibri'
r.font.size = Pt(14)
r.font.color.rgb = GOLD

doc.add_page_break()

# ═══════════════════════════════════════════════════════════════════════════
# IDEAS SECTION
# ═══════════════════════════════════════════════════════════════════════════
# Section header
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.LEFT
p.paragraph_format.space_after = Pt(10)
r = p.add_run('THE 50 IDEAS')
r.font.name = 'Calibri'
r.font.size = Pt(18)
r.font.bold = True
r.font.color.rgb = NAVY

def add_idea(doc, num, name, summary, revenue, moat, score):
    is_five = (score == 5)

    # Idea header bar — use a 1-row table for colored background
    tbl = doc.add_table(rows=1, cols=2)
    tbl.alignment = WD_TABLE_ALIGNMENT.LEFT
    tbl.style = 'Table Grid'

    # Left cell: number + name
    left = tbl.rows[0].cells[0]
    set_cell_bg(left, '002B5C')
    left.width = Inches(4.5)
    p = left.paragraphs[0]
    p.paragraph_format.space_before = Pt(3)
    p.paragraph_format.space_after  = Pt(3)
    r1 = p.add_run(f'  #{num:02d}  ')
    r1.font.name = 'Calibri'
    r1.font.size = Pt(10)
    r1.font.bold = True
    r1.font.color.rgb = GOLD
    r2 = p.add_run(name)
    r2.font.name = 'Calibri'
    r2.font.size = Pt(11)
    r2.font.bold = True
    r2.font.color.rgb = WHITE

    # Right cell: Joe-Fit score
    right = tbl.rows[0].cells[1]
    set_cell_bg(right, 'C59E3C' if is_five else '002B5C')
    right.width = Inches(1.8)
    p2 = right.paragraphs[0]
    p2.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    p2.paragraph_format.space_before = Pt(3)
    p2.paragraph_format.space_after  = Pt(3)
    label_run = p2.add_run(f'JOE-FIT  {stars(score)}  {score}/5  ')
    label_run.font.name = 'Calibri'
    label_run.font.size = Pt(9)
    label_run.font.bold = True
    label_run.font.color.rgb = NAVY if is_five else WHITE

    # Remove table borders except bottom
    for row in tbl.rows:
        for cell in row.cells:
            tc = cell._tc
            tcPr = tc.get_or_add_tcPr()
            tcBdr = OxmlElement('w:tcBdr')
            for side in ['top', 'left', 'right', 'bottom']:
                bd = OxmlElement(f'w:{side}')
                bd.set(qn('w:val'), 'none' if side != 'bottom' else 'single')
                bd.set(qn('w:sz'), '4')
                bd.set(qn('w:space'), '0')
                bd.set(qn('w:color'), 'C59E3C')
                tcBdr.append(bd)
            tcPr.append(tcBdr)

    # Content rows — compact table
    body_tbl = doc.add_table(rows=3, cols=2)
    body_tbl.alignment = WD_TABLE_ALIGNMENT.LEFT
    body_tbl.style = 'Table Grid'
    bg_hex = 'FFF9ED' if is_five else 'FFFFFF'

    labels = ['SUMMARY', 'REVENUE MODEL', 'MOAT']
    values = [summary, revenue, moat]

    for i, (lbl, val) in enumerate(zip(labels, values)):
        row = body_tbl.rows[i]
        # Label cell
        lc = row.cells[0]
        set_cell_bg(lc, 'F0F4FA' if not is_five else 'FFF3D0')
        lc.width = Inches(1.1)
        lp = lc.paragraphs[0]
        lp.paragraph_format.space_before = Pt(2)
        lp.paragraph_format.space_after  = Pt(2)
        lr = lp.add_run(f'  {lbl}')
        lr.font.name = 'Calibri'
        lr.font.size = Pt(7.5)
        lr.font.bold = True
        lr.font.color.rgb = NAVY

        # Value cell
        vc = row.cells[1]
        set_cell_bg(vc, bg_hex)
        vp = vc.paragraphs[0]
        vp.paragraph_format.space_before = Pt(2)
        vp.paragraph_format.space_after  = Pt(2)
        vr = vp.add_run(f'  {val}')
        vr.font.name = 'Calibri'
        vr.font.size = Pt(8.5)
        vr.font.color.rgb = BLACK

    # Remove borders on body table
    for row in body_tbl.rows:
        for cell in row.cells:
            tc = cell._tc
            tcPr = tc.get_or_add_tcPr()
            tcBdr = OxmlElement('w:tcBdr')
            for side in ['top', 'left', 'right', 'bottom']:
                bd = OxmlElement(f'w:{side}')
                bd.set(qn('w:val'), 'none')
                bd.set(qn('w:sz'), '0')
                bd.set(qn('w:space'), '0')
                bd.set(qn('w:color'), 'auto')
                tcBdr.append(bd)
            tcPr.append(tcBdr)

    # Spacer
    sp = doc.add_paragraph()
    sp.paragraph_format.space_before = Pt(0)
    sp.paragraph_format.space_after  = Pt(5)

    # 5/5 marker note
    if is_five:
        mp = doc.add_paragraph()
        mp.paragraph_format.space_before = Pt(0)
        mp.paragraph_format.space_after  = Pt(8)
        mr = mp.add_run('  ★ JOE-FIT 5/5 — HIGH PRIORITY')
        mr.font.name = 'Calibri'
        mr.font.size = Pt(8)
        mr.font.bold = True
        mr.font.color.rgb = GOLD
    else:
        sp2 = doc.add_paragraph()
        sp2.paragraph_format.space_before = Pt(0)
        sp2.paragraph_format.space_after  = Pt(4)

for idea in IDEAS:
    add_idea(doc, *idea)

# ═══════════════════════════════════════════════════════════════════════════
# SUMMARY PAGE — TOP 10
# ═══════════════════════════════════════════════════════════════════════════
doc.add_page_break()

# Header
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(4)
r = p.add_run('TOP 10 IDEAS FOR JOE')
r.font.name = 'Calibri'
r.font.size = Pt(22)
r.font.bold = True
r.font.color.rgb = NAVY

p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(12)
r = p.add_run('Ranked by Joe-Fit Score  ·  All scored 5/5  ·  IDEA FACTORY Day 1 of 21')
r.font.name = 'Calibri'
r.font.size = Pt(10)
r.font.italic = True
r.font.color.rgb = RGBColor(0x55, 0x55, 0x55)

# Gold divider
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(10)
r = p.add_run('━' * 50)
r.font.name = 'Calibri'
r.font.size = Pt(12)
r.font.color.rgb = GOLD

for rank, (num, name, score, rationale) in enumerate(TOP10_RATIONALE, 1):
    tbl = doc.add_table(rows=1, cols=3)
    tbl.alignment = WD_TABLE_ALIGNMENT.LEFT
    tbl.style = 'Table Grid'

    # Rank cell
    rc = tbl.rows[0].cells[0]
    set_cell_bg(rc, 'C59E3C')
    rc.width = Inches(0.45)
    rp = rc.paragraphs[0]
    rp.alignment = WD_ALIGN_PARAGRAPH.CENTER
    rp.paragraph_format.space_before = Pt(4)
    rp.paragraph_format.space_after  = Pt(4)
    rr = rp.add_run(f'#{rank}')
    rr.font.name = 'Calibri'
    rr.font.size = Pt(13)
    rr.font.bold = True
    rr.font.color.rgb = NAVY

    # Name cell
    nc = tbl.rows[0].cells[1]
    set_cell_bg(nc, '002B5C')
    nc.width = Inches(2.0)
    np_ = nc.paragraphs[0]
    np_.paragraph_format.space_before = Pt(4)
    np_.paragraph_format.space_after  = Pt(4)
    nr = np_.add_run(f'  {name}  (#{num})')
    nr.font.name = 'Calibri'
    nr.font.size = Pt(10)
    nr.font.bold = True
    nr.font.color.rgb = WHITE

    # Rationale cell
    vc = tbl.rows[0].cells[2]
    set_cell_bg(vc, 'FFF9ED')
    vp = vc.paragraphs[0]
    vp.paragraph_format.space_before = Pt(4)
    vp.paragraph_format.space_after  = Pt(4)
    vr = vp.add_run(f'  {rationale}')
    vr.font.name = 'Calibri'
    vr.font.size = Pt(8.5)
    vr.font.color.rgb = BLACK

    # Remove table borders
    for row in tbl.rows:
        for cell in row.cells:
            tc = cell._tc
            tcPr = tc.get_or_add_tcPr()
            tcBdr = OxmlElement('w:tcBdr')
            for side in ['top', 'left', 'right', 'bottom']:
                bd = OxmlElement(f'w:{side}')
                bd.set(qn('w:val'), 'none')
                bd.set(qn('w:sz'), '0')
                bd.set(qn('w:space'), '0')
                bd.set(qn('w:color'), 'auto')
                tcBdr.append(bd)
            tcPr.append(tcBdr)

    sp = doc.add_paragraph()
    sp.paragraph_format.space_before = Pt(0)
    sp.paragraph_format.space_after  = Pt(5)

# Footer note
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_before = Pt(16)
p.paragraph_format.space_after  = Pt(4)
r = p.add_run('━' * 50)
r.font.name = 'Calibri'
r.font.size = Pt(12)
r.font.color.rgb = GOLD

p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(2)
r = p.add_run('Generated by Rob Lobster 🦞  ·  IDEA FACTORY Day 1 of 21  ·  April 8, 2026')
r.font.name = 'Calibri'
r.font.size = Pt(9)
r.font.italic = True
r.font.color.rgb = RGBColor(0x77, 0x77, 0x77)

p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(0)
r = p.add_run('Ideas are brainstorm output, not investment advice. All ideas subject to Joe\'s own due diligence.')
r.font.name = 'Calibri'
r.font.size = Pt(8)
r.font.italic = True
r.font.color.rgb = RGBColor(0x99, 0x99, 0x99)

# ── Save ──────────────────────────────────────────────────────────────────
OUTPUT = '/Users/joemac/.openclaw/workspace/projects/idea-factory/idea-factory-day-01-report.docx'
doc.save(OUTPUT)
print(f"Saved: {OUTPUT}")
