#!/usr/bin/env python3
"""Create the Firehouse Historic Tax Credit memo as a 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
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
import copy

# Navy blue color
NAVY = RGBColor(0x1F, 0x35, 0x64)  # #1F3564 — deep navy
DARK_NAVY = RGBColor(0x00, 0x27, 0x4D)  # even darker
LIGHT_GRAY = RGBColor(0xF2, 0xF2, 0xF2)

def set_font(run, name='Calibri', size=11, bold=False, italic=False, color=None):
    run.font.name = name
    run.font.size = Pt(size)
    run.font.bold = bold
    run.font.italic = italic
    if color:
        run.font.color.rgb = color

def add_heading(doc, text, level=1):
    """Add a navy blue section heading."""
    p = doc.add_paragraph()
    p.paragraph_format.space_before = Pt(14)
    p.paragraph_format.space_after = Pt(4)
    run = p.add_run(text)
    run.font.name = 'Calibri'
    run.font.size = Pt(13 if level == 1 else 11)
    run.font.bold = True
    run.font.color.rgb = NAVY
    # Add bottom border to heading
    pPr = p._p.get_or_add_pPr()
    pBdr = OxmlElement('w:pBdr')
    bottom = OxmlElement('w:bottom')
    bottom.set(qn('w:val'), 'single')
    bottom.set(qn('w:sz'), '6')
    bottom.set(qn('w:space'), '1')
    bottom.set(qn('w:color'), '1F3564')
    pBdr.append(bottom)
    pPr.append(pBdr)
    return p

def add_bullet(doc, text, bold_part=None, level=0):
    """Add a bullet point."""
    p = doc.add_paragraph(style='List Bullet')
    p.paragraph_format.space_before = Pt(2)
    p.paragraph_format.space_after = Pt(2)
    p.paragraph_format.left_indent = Inches(0.25 + level * 0.25)
    if bold_part and text.startswith(bold_part):
        run = p.add_run(bold_part)
        set_font(run, bold=True, size=11)
        rest = text[len(bold_part):]
        run2 = p.add_run(rest)
        set_font(run2, size=11)
    else:
        run = p.add_run(text)
        set_font(run, size=11)
    return p

def add_numbered(doc, number, text):
    """Add a numbered item."""
    p = doc.add_paragraph()
    p.paragraph_format.space_before = Pt(3)
    p.paragraph_format.space_after = Pt(3)
    p.paragraph_format.left_indent = Inches(0.25)
    run = p.add_run(f"{number}. ")
    set_font(run, bold=True, size=11, color=NAVY)
    run2 = p.add_run(text)
    set_font(run2, size=11)
    return p

def add_body(doc, text):
    p = doc.add_paragraph()
    p.paragraph_format.space_before = Pt(3)
    p.paragraph_format.space_after = Pt(3)
    run = p.add_run(text)
    set_font(run, size=11)
    return p

# ---- Build Document ----
doc = Document()

# Set margins
for section in doc.sections:
    section.top_margin = Inches(1)
    section.bottom_margin = Inches(1)
    section.left_margin = Inches(1.25)
    section.right_margin = Inches(1.25)

# ---- HEADER BLOCK ----
# Title bar
title_p = doc.add_paragraph()
title_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
title_p.paragraph_format.space_before = Pt(0)
title_p.paragraph_format.space_after = Pt(6)
title_run = title_p.add_run("MEMORANDUM")
title_run.font.name = 'Calibri'
title_run.font.size = Pt(16)
title_run.font.bold = True
title_run.font.color.rgb = NAVY

subtitle_p = doc.add_paragraph()
subtitle_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
subtitle_p.paragraph_format.space_before = Pt(0)
subtitle_p.paragraph_format.space_after = Pt(14)
sub_run = subtitle_p.add_run("Historic Tax Credit Opportunity")
sub_run.font.name = 'Calibri'
sub_run.font.size = Pt(12)
sub_run.font.italic = True
sub_run.font.color.rgb = NAVY

# Header table (TO/FROM/RE/DATE)
header_table = doc.add_table(rows=4, cols=2)
header_table.alignment = WD_TABLE_ALIGNMENT.LEFT
header_table.style = 'Table Grid'

header_data = [
    ("TO:", "Robert MacArthur, CPA"),
    ("FROM:", "Joe Lynch, Managing Member — Old School Firehouse LLC"),
    ("RE:", "Historic Tax Credit Opportunity — 18 New Street, Crosswicks, NJ 08515"),
    ("DATE:", "April 7, 2026"),
]

for i, (label, value) in enumerate(header_data):
    row = header_table.rows[i]
    # Label cell
    cell_label = row.cells[0]
    cell_label.width = Inches(0.9)
    p = cell_label.paragraphs[0]
    run = p.add_run(label)
    run.font.name = 'Calibri'
    run.font.size = Pt(11)
    run.font.bold = True
    run.font.color.rgb = NAVY
    # Shade label cell
    tc = cell_label._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'), 'E8EDF5')
    tcPr.append(shd)

    # Value cell
    cell_value = row.cells[1]
    p2 = cell_value.paragraphs[0]
    run2 = p2.add_run(value)
    run2.font.name = 'Calibri'
    run2.font.size = Pt(11)
    if i == 2:  # RE: line — make slightly bold
        run2.font.bold = True

doc.add_paragraph()  # spacer

# ---- SECTION 1: THE PROPERTY ----
add_heading(doc, "SECTION 1: THE PROPERTY")

bullets_s1 = [
    ("Address:", "Address: 18 New Street, Crosswicks, NJ 08515"),
    ("Owner:", "Owner: Old School Firehouse LLC (Joe Lynch, Managing Member)"),
    ("Parcel:", "Parcel: Block 300, Lot 12, Chesterfield Township, Burlington County, NJ"),
    ("Structure:", "Structure: Former firehouse and schoolhouse — solid brick construction, two full levels + basement"),
    ("Size:", "Size: Approximately 4,000+ square feet with HIGH CEILINGS on both levels"),
    ("Historic Status:", "Historic Status: Property is listed on the NATIONAL REGISTER OF HISTORIC PLACES"),
    ("Redevelopment:", "Location: Within a NJ Redevelopment Plan area (non-condemnation designation)"),
    ("Investment:", "Investment to Date: Approximately $550,000 (acquisition + approvals + some renovation)"),
]

for bold, full in bullets_s1:
    p = doc.add_paragraph(style='List Bullet')
    p.paragraph_format.space_before = Pt(2)
    p.paragraph_format.space_after = Pt(2)
    p.paragraph_format.left_indent = Inches(0.25)
    r1 = p.add_run(bold + " ")
    set_font(r1, bold=True, size=11)
    r2 = p.add_run(full[len(bold)+1:].strip())
    set_font(r2, size=11)

# ---- SECTION 2: FEDERAL HTC ----
add_heading(doc, "SECTION 2: FEDERAL HISTORIC TAX CREDIT (HTC)")

s2_items = [
    ("IRC Section 47:", "The Federal Historic Preservation Tax Credit (IRC Section 47) provides a 20% FEDERAL TAX CREDIT for certified rehabilitation of certified historic structures."),
    ("Qualification:", 'A "certified historic structure" is a building listed individually on the National Register of Historic Places OR in a registered historic district. The Old School Firehouse qualifies by virtue of its National Register listing.'),
    ("Credit Rate:", "The credit equals 20% of Qualified Rehabilitation Expenditures (QREs) — costs for renovation work that meets the Secretary of the Interior's Standards."),
    ("Example:", "If renovation costs $500,000 in QREs, the federal credit = $100,000 — a dollar-for-dollar reduction in federal tax liability (not a deduction)."),
    ("Timing:", "Credits can be used in the year the rehabilitated building is placed in service."),
    ("Carryover:", "Unused credits can be carried back 1 year and forward 20 years."),
]

for bold, text in s2_items:
    p = doc.add_paragraph(style='List Bullet')
    p.paragraph_format.space_before = Pt(2)
    p.paragraph_format.space_after = Pt(2)
    p.paragraph_format.left_indent = Inches(0.25)
    r1 = p.add_run(bold + " ")
    set_font(r1, bold=True, size=11)
    r2 = p.add_run(text)
    set_font(r2, size=11)

# ---- SECTION 3: NJ STATE HTC ----
add_heading(doc, "SECTION 3: NJ STATE HISTORIC PRESERVATION TAX CREDIT")

s3_items = [
    ("NJ Statute:", "New Jersey offers a state Historic Property Reinvestment Act tax credit (N.J.S.A. 54:10A-5.42)."),
    ("Credit Rate:", "NJ state credit: up to 40% of QREs for qualified historic structures (commercial/income-producing)."),
    ("Combined Credit:", "Combined federal + state: potentially 60% of rehabilitation costs covered by tax credits."),
    ("Certification:", "NJ program requires State Historic Preservation Office (SHPO) certification."),
    ("Transferability:", "Credits are transferable in NJ — meaning they can be sold to investors who can use them, even if the developer lacks sufficient tax liability."),
]

for bold, text in s3_items:
    p = doc.add_paragraph(style='List Bullet')
    p.paragraph_format.space_before = Pt(2)
    p.paragraph_format.space_after = Pt(2)
    p.paragraph_format.left_indent = Inches(0.25)
    r1 = p.add_run(bold + " ")
    set_font(r1, bold=True, size=11)
    r2 = p.add_run(text)
    set_font(r2, size=11)

# ---- SECTION 4: REQUIREMENTS AND CONSIDERATIONS ----
add_heading(doc, "SECTION 4: IMPORTANT REQUIREMENTS AND CONSIDERATIONS")

s4_items = [
    ("Income-Producing Requirement:", "The property must be income-producing to qualify for the federal credit — it cannot be used as a personal residence. This is a critical planning consideration."),
    ("Single-Family Scenario:", "If converted to a single-family luxury residence (current plan option), the FEDERAL credit does NOT apply. The property must be rental, commercial, or mixed-use."),
    ("Multi-Unit Scenario:", "If converted to 4 residential units (the approved development plan), credits likely DO apply to common areas and commercial portions."),
    ("Secretary of Interior's Standards:", "The rehabilitation must meet the Secretary of the Interior's Standards for Rehabilitation — basic historic character must be preserved."),
    ("Pre-Approval Required:", "SHPO (NJ State Historic Preservation Office) and National Park Service pre-approval must be obtained before starting any qualified work."),
    ("QRE Scope:", "QREs generally include structural, mechanical, electrical, and plumbing work — but NOT acquisition cost or work on non-historic additions."),
    ("Tax Credit Investor Partnerships:", "Developers often bring in tax credit investors who fund renovation in exchange for the credits, partially financing the project through the credit value."),
]

for bold, text in s4_items:
    p = doc.add_paragraph(style='List Bullet')
    p.paragraph_format.space_before = Pt(2)
    p.paragraph_format.space_after = Pt(2)
    p.paragraph_format.left_indent = Inches(0.25)
    r1 = p.add_run(bold + " ")
    set_font(r1, bold=True, size=11)
    r2 = p.add_run(text)
    set_font(r2, size=11)

# ---- SECTION 5: POTENTIAL TAX CREDIT VALUE ----
add_heading(doc, "SECTION 5: POTENTIAL TAX CREDIT VALUE (PRELIMINARY ESTIMATE)")

intro_p = doc.add_paragraph()
intro_p.paragraph_format.space_before = Pt(4)
intro_p.paragraph_format.space_after = Pt(6)
intro_run = intro_p.add_run(
    "The following table illustrates potential credit value at various QRE levels. "
    "Federal credit = 20% of QREs; NJ credit = 40% of QREs."
)
set_font(intro_run, size=11)

# Table
credit_table = doc.add_table(rows=5, cols=4)
credit_table.alignment = WD_TABLE_ALIGNMENT.CENTER
credit_table.style = 'Table Grid'

headers = ["Qualified Rehabilitation Expenditures", "Federal Credit (20%)", "NJ State Credit (40%)", "Total Credits"]
data_rows = [
    ["$300,000", "$60,000", "$120,000", "$180,000"],
    ["$500,000", "$100,000", "$200,000", "$300,000"],
    ["$750,000", "$150,000", "$300,000", "$450,000"],
]

# Header row
header_row = credit_table.rows[0]
for j, h in enumerate(headers):
    cell = header_row.cells[j]
    p = cell.paragraphs[0]
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = p.add_run(h)
    run.font.name = 'Calibri'
    run.font.size = Pt(10)
    run.font.bold = True
    run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
    # Navy background
    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'), '1F3564')
    tcPr.append(shd)

# Data rows
for i, row_data in enumerate(data_rows):
    row = credit_table.rows[i + 1]
    fill = 'F2F5FA' if i % 2 == 0 else 'FFFFFF'
    for j, val in enumerate(row_data):
        cell = row.cells[j]
        p = cell.paragraphs[0]
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = p.add_run(val)
        run.font.name = 'Calibri'
        run.font.size = Pt(11)
        if j == 3:  # Total column — bold
            run.font.bold = True
            run.font.color.rgb = NAVY
        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'), fill)
        tcPr.append(shd)

note_p = doc.add_paragraph()
note_p.paragraph_format.space_before = Pt(6)
note_p.paragraph_format.space_after = Pt(4)
note_run = note_p.add_run(
    "Note: These are preliminary estimates. Actual QREs must be certified by the NPS/SHPO. "
    "Not all renovation costs qualify as QREs. Consult with a historic preservation specialist for a formal QRE assessment."
)
set_font(note_run, size=10, italic=True, color=RGBColor(0x60, 0x60, 0x60))

# ---- SECTION 6: QUESTIONS FOR ROBERT MACARTHUR ----
add_heading(doc, "SECTION 6: QUESTIONS FOR ROBERT MACARTHUR")

questions = [
    "Does the income-producing requirement create a planning issue given Joe's current intent to use this as a personal residence? Are there hybrid approaches (e.g., short-term rental income, ADU) that could preserve credit eligibility while meeting personal use goals?",
    "Can the tax credits be carried forward or transferred if the renovation is completed before Joe has sufficient tax liability to absorb them?",
    "Are there any AMT (Alternative Minimum Tax) implications associated with the federal Historic Tax Credit?",
    "Should Old School Firehouse LLC remain the holding entity, or would a different structure (e.g., a pass-through to individuals with higher tax liability) optimize credit utilization?",
    "What is the process and timeline for obtaining SHPO approval? Should Joe engage a historic preservation consultant early in the process?",
    "Is a tax credit investor/partnership structure worth exploring if the combined credit value approaches or exceeds $300,000?",
]

for i, q in enumerate(questions, 1):
    add_numbered(doc, i, q)

# ---- SECTION 7: RECOMMENDED NEXT STEPS ----
add_heading(doc, "SECTION 7: RECOMMENDED NEXT STEPS")

next_steps = [
    "Confirm with SHPO that the property qualifies and inquire about the pre-certification process.",
    "Engage a historic preservation architect or consultant to assess which planned renovation costs would qualify as QREs.",
    "Obtain a preliminary estimate of total QREs based on current renovation plans and scope.",
    "Review entity structure with Robert to optimize credit utilization and ensure the property is positioned as income-producing.",
    "If renovation budget exceeds $300,000 in QREs, seriously evaluate a tax credit investor partnership to monetize the credits.",
]

for i, step in enumerate(next_steps, 1):
    add_numbered(doc, i, step)

# ---- CLOSING ----
doc.add_paragraph()  # spacer

closing_p = doc.add_paragraph()
closing_p.paragraph_format.space_before = Pt(8)
closing_p.paragraph_format.space_after = Pt(8)
# Add left border for emphasis
pPr = closing_p._p.get_or_add_pPr()
pBdr = OxmlElement('w:pBdr')
left = OxmlElement('w:left')
left.set(qn('w:val'), 'single')
left.set(qn('w:sz'), '12')
left.set(qn('w:space'), '4')
left.set(qn('w:color'), '1F3564')
pBdr.append(left)
pPr.append(pBdr)
closing_p.paragraph_format.left_indent = Inches(0.25)

closing_run = closing_p.add_run(
    "Robert, given the scale of our planned renovation and the National Register listing, I believe the historic tax "
    "credit program warrants serious exploration before we finalize our renovation approach. The credits could "
    "materially reduce our out-of-pocket costs and potentially attract outside capital. I would appreciate your "
    "guidance on the planning considerations and whether the income-producing requirement creates any obstacles we "
    "need to structure around."
)
set_font(closing_run, size=11, italic=True)

# Signature block
doc.add_paragraph()
sig_p = doc.add_paragraph()
sig_p.paragraph_format.space_before = Pt(12)
sig_p.paragraph_format.space_after = Pt(2)
sig_run = sig_p.add_run("Joe Lynch")
set_font(sig_run, size=12, bold=True, color=NAVY)

sig2_p = doc.add_paragraph()
sig2_p.paragraph_format.space_before = Pt(0)
sig2_p.paragraph_format.space_after = Pt(2)
sig2_run = sig2_p.add_run("Managing Member, Old School Firehouse LLC")
set_font(sig2_run, size=11)

sig3_p = doc.add_paragraph()
sig3_p.paragraph_format.space_before = Pt(0)
sig3_p.paragraph_format.space_after = Pt(2)
sig3_run = sig3_p.add_run("jlynch@tlcnj.com")
set_font(sig3_run, size=11, color=NAVY)

sig4_p = doc.add_paragraph()
sig4_p.paragraph_format.space_before = Pt(0)
sig4_p.paragraph_format.space_after = Pt(2)
sig4_run = sig4_p.add_run("April 7, 2026")
set_font(sig4_run, size=11, italic=True, color=RGBColor(0x60, 0x60, 0x60))

# Save
output_path = '/Users/joemac/.openclaw/workspace/projects/firehouse-historic-tax-credit-memo.docx'
doc.save(output_path)
print(f"Document saved to: {output_path}")
