from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY

OUTPUT = "/home/aria/marketing-assets/uploads/VectorPM-Market-Research-2026.pdf"

ORANGE = colors.HexColor("#ea580c")
DARK = colors.HexColor("#171717")
SURFACE = colors.HexColor("#f5f5f5")
MUTED = colors.HexColor("#6b7280")
WHITE = colors.white

doc = SimpleDocTemplate(OUTPUT, pagesize=A4,
    rightMargin=20*mm, leftMargin=20*mm, topMargin=20*mm, bottomMargin=20*mm)

styles = getSampleStyleSheet()
def S(name, **kw):
    return ParagraphStyle(name, parent=styles["Normal"], **kw)

h1_s  = S("H1", fontSize=16, textColor=DARK, fontName="Helvetica-Bold", spaceBefore=12, spaceAfter=5, leading=20)
h2_s  = S("H2", fontSize=12, textColor=ORANGE, fontName="Helvetica-Bold", spaceBefore=8, spaceAfter=3)
body_s= S("B", fontSize=9.5, textColor=colors.HexColor("#374151"), fontName="Helvetica", leading=15, spaceAfter=4, alignment=TA_JUSTIFY)
bul_s = S("Bu", fontSize=9.5, textColor=colors.HexColor("#374151"), fontName="Helvetica", leading=14, spaceAfter=3, leftIndent=10)
foot_s= S("F", fontSize=8, textColor=MUTED, fontName="Helvetica", alignment=TA_CENTER)
rec_s = S("R", fontSize=10.5, textColor=DARK, fontName="Helvetica", leading=17, alignment=TA_JUSTIFY)
pos_l = S("PL", fontSize=9, textColor=ORANGE, fontName="Helvetica-Bold")
pos_v = S("PV", fontSize=9.5, textColor=DARK, fontName="Helvetica", leading=14)

def grid_style(n_header=1, last_color=None):
    s = TableStyle([
        ("BACKGROUND",(0,0),(-1,n_header-1),DARK),
        ("TEXTCOLOR",(0,0),(-1,n_header-1),WHITE),
        ("FONTNAME",(0,0),(-1,n_header-1),"Helvetica-Bold"),
        ("FONTSIZE",(0,0),(-1,-1),9),
        ("ROWBACKGROUNDS",(0,n_header),(-1,-1),[WHITE,SURFACE]),
        ("GRID",(0,0),(-1,-1),0.3,colors.HexColor("#e5e7eb")),
        ("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5),
        ("LEFTPADDING",(0,0),(-1,-1),7),("RIGHTPADDING",(0,0),(-1,-1),7),
        ("VALIGN",(0,0),(-1,-1),"MIDDLE"),
    ])
    if last_color:
        s.add("BACKGROUND",(0,-1),(-1,-1),last_color)
        s.add("TEXTCOLOR",(0,-1),(-1,-1),WHITE)
        s.add("FONTNAME",(0,-1),(-1,-1),"Helvetica-Bold")
    return s

story = []

# COVER
for txt, fsize, pb, pa in [
    ("VectorPM", 26, 20, 4),
    ("Market Research: Underserved Industries for Project Management Tools", 12, 0, 18),
]:
    blk = Table([[Paragraph(txt, S("C"+str(fsize), fontSize=fsize,
        textColor=WHITE if fsize==26 else colors.HexColor("#fb923c"),
        fontName="Helvetica-Bold" if fsize==26 else "Helvetica"))]], colWidths=[170*mm])
    blk.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),DARK),
        ("TOPPADDING",(0,0),(-1,-1),pb),("BOTTOMPADDING",(0,0),(-1,-1),pa),
        ("LEFTPADDING",(0,0),(-1,-1),14),("RIGHTPADDING",(0,0),(-1,-1),14)]))
    story.append(blk)

story.append(Spacer(1,3*mm))
story.append(Paragraph("Prepared: February 2026  |  Symph Agency  |  Confidential", S("D",fontSize=9,textColor=MUTED,fontName="Helvetica")))
story.append(Spacer(1,4*mm))
story.append(HRFlowable(width="100%",thickness=1.5,color=ORANGE))
story.append(Spacer(1,4*mm))

# EXEC SUMMARY
story.append(Paragraph("Executive Summary", h1_s))
story.append(Paragraph(
    "The project management software market is dominated by horizontal tools built primarily for software development teams. "
    "This creates a significant gap: millions of project-driven businesses in construction, event management, and creative agencies "
    "operate with sequential phases, physical handoffs, and multi-vendor coordination that generic PM tools handle poorly. "
    "This report evaluates three high-potential verticals and recommends a go-to-market strategy.",
    body_s))

# STRATEGY
story.append(HRFlowable(width="100%",thickness=0.5,color=colors.HexColor("#e5e7eb")))
story.append(Spacer(1,3*mm))
story.append(Paragraph("Strategic Framework: Build Horizontal, Launch Vertical", h1_s))
story.append(Paragraph(
    "VectorPM is designed as a flexible platform for any project-driven team. However, launching with a 'works for everyone' message "
    "is the fastest route to acquiring no one. The recommended approach mirrors how Monday.com and Linear scaled: "
    "build horizontal, market vertically, expand once proven.",
    body_s))

fw = Table([
    ["Phase","Action","Goal"],
    ["1. Build","Develop a flexible, customizable PM core","Product works for any team"],
    ["2. Launch","Market exclusively to construction teams","Nail the wedge, acquire first customers"],
    ["3. Prove","50–100 happy customers in construction","Story is earned, not just claimed"],
    ["4. Expand","Add templates for Events, Agencies, etc.","Cross-vertical growth with credibility"],
], colWidths=[28*mm,82*mm,60*mm])
fw.setStyle(grid_style())
story.append(Spacer(1,2*mm))
story.append(fw)
story.append(Spacer(1,6*mm))

# INDUSTRY HELPER
def industry_section(emoji, name, tag, tag_color, stats_rows, pains, score_rows, score_last_color):
    story.append(HRFlowable(width="100%",thickness=2 if tag else 1,color=ORANGE if tag else colors.HexColor("#e5e7eb")))
    story.append(Spacer(1,3*mm))
    if tag:
        hdr = Table([[
            Paragraph(f"{emoji}  {name}", S("IH",fontSize=15,textColor=DARK,fontName="Helvetica-Bold")),
            Paragraph(tag, S("IT",fontSize=8.5,textColor=WHITE,fontName="Helvetica-Bold",alignment=TA_CENTER)),
        ]], colWidths=[120*mm,50*mm])
        hdr.setStyle(TableStyle([
            ("BACKGROUND",(1,0),(1,0),tag_color),("ALIGN",(1,0),(1,0),"CENTER"),
            ("VALIGN",(0,0),(-1,-1),"MIDDLE"),
            ("TOPPADDING",(1,0),(1,0),6),("BOTTOMPADDING",(1,0),(1,0),6),
            ("LEFTPADDING",(1,0),(1,0),6),("RIGHTPADDING",(1,0),(1,0),6),
        ]))
        story.append(hdr)
    else:
        story.append(Paragraph(f"{emoji}  {name}", h1_s))
    story.append(Spacer(1,3*mm))
    story.append(Paragraph("Market Overview", h2_s))
    t = Table(stats_rows, colWidths=[88*mm,82*mm])
    t.setStyle(TableStyle([("FONTNAME",(0,0),(0,-1),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,-1),9),
        ("ROWBACKGROUNDS",(0,0),(-1,-1),[SURFACE,WHITE]),("GRID",(0,0),(-1,-1),0.3,colors.HexColor("#e5e7eb")),
        ("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5),
        ("LEFTPADDING",(0,0),(-1,-1),7),("RIGHTPADDING",(0,0),(-1,-1),7)]))
    story.append(t)
    story.append(Spacer(1,3*mm))
    story.append(Paragraph("Core Pain Points", h2_s))
    for title, desc in pains:
        story.append(Paragraph(f"<b>• {title}:</b> {desc}", bul_s))
    story.append(Spacer(1,3*mm))
    story.append(Paragraph("Scorecard", h2_s))
    sc = Table(score_rows, colWidths=[75*mm,38*mm,57*mm])
    sc.setStyle(grid_style(last_color=score_last_color))
    story.append(sc)
    story.append(Spacer(1,7*mm))

industry_section(
    "🏗️", "Industry 1: Construction", "★ RECOMMENDED WEDGE", ORANGE,
    [
        ["Global Construction PM Software Market","~$2.8B (2024), 9.4% CAGR"],
        ["Construction Firms (US alone)","750,000+ firms, majority SMB"],
        ["Avg. Subcontractors per Commercial Build","10–40 per project"],
        ["Current Primary Tools","Spreadsheets, WhatsApp, Procore (enterprise only)"],
    ],
    [
        ("Sequential dependency problem","Construction is phase-locked — you can't pour concrete before the foundation sets. Generic PM tools treat tasks as parallel and flexible, forcing constant workarounds."),
        ("Subcontractor accountability gap","10–40 subcontractors per build. Coordinating handoffs between trades via WhatsApp and email is the industry norm — and the primary source of delays."),
        ("Missed handoffs cost real money","A delayed handoff doesn't slip a sprint — it idles labor at $5K–$50K/day and triggers penalty clauses on fixed-price contracts."),
        ("Enterprise tools are inaccessible","Procore and Autodesk Build cost $50K+/year. The vast SMB majority is priced out and chronically underserved."),
        ("No punch-list or RFI workflow","RFIs, punch lists, inspection sign-offs, and daily site reports are tracked in spreadsheets because PM tools don't support them natively."),
    ],
    [
        ["Criterion","Score","Notes"],
        ["Market size & accessibility","⭐⭐⭐⭐⭐","Huge SMB gap; no dominant mid-market player"],
        ["Pain intensity","⭐⭐⭐⭐⭐","Missed handoffs = immediate financial penalty"],
        ["Product-market fit today","⭐⭐⭐⭐⭐","Phase-aware PM is a direct match"],
        ["Sales cycle complexity","⭐⭐⭐⭐","SMB = shorter cycles; PM makes the call"],
        ["Willingness to pay","⭐⭐⭐⭐","Budget exists; currently wasted on workarounds"],
        ["Overall Score","4.8 / 5.0","STRONGEST WEDGE CANDIDATE"],
    ],
    ORANGE
)

industry_section(
    "🎪", "Industry 2: Event Management", None, None,
    [
        ["Global Events Industry Size","~$1.5T; event tech growing at 11% CAGR"],
        ["Typical Event Timeline","3–18 months of phased planning → hard deadline"],
        ["Key Coordination Challenge","Venues, AV, catering, logistics, talent — all external"],
        ["Current Primary Tools","Google Sheets, Trello, Asana (hacked), email threads"],
    ],
    [
        ("Hard deadline with zero flexibility","The event date is fixed. Every upstream delay compounds and the event still happens — teams absorb all the crunch, which standard PM tools don't model well."),
        ("Multi-vendor coordination chaos","8–20 external vendors with separate deliverables, deposits, and schedules. A single PM view across all of them doesn't exist in generic tools."),
        ("No run-of-show workflow","Pre-event task tracking is partially supported; day-of minute-by-minute execution (run-of-show) is not supported at all in generic PM tools."),
        ("Budget tightly linked to tasks","Cost tracking per vendor and task is critical — but generic PM tools don't connect financials to task progress natively."),
    ],
    [
        ["Criterion","Score","Notes"],
        ["Market size & accessibility","⭐⭐⭐⭐","Large but geographically fragmented"],
        ["Pain intensity","⭐⭐⭐⭐","Hard deadlines create urgency"],
        ["Product-market fit today","⭐⭐⭐","Timeline view fits; run-of-show needs custom work"],
        ["Sales cycle complexity","⭐⭐⭐⭐","Planners are decisive, often solo buyers"],
        ["Willingness to pay","⭐⭐⭐","Moderate price sensitivity"],
        ["Overall Score","3.6 / 5.0","STRONG SECOND VERTICAL"],
    ],
    colors.HexColor("#374151")
)

industry_section(
    "🎨", "Industry 3: Creative & Marketing Agencies", None, None,
    [
        ["Global Agency Market","$700B+ across marketing, design, PR, and digital"],
        ["Average Team Size","10–150 people organized around client accounts"],
        ["Primary PM Challenge","Simultaneous deliverables across multiple client accounts"],
        ["Current Primary Tools","Asana, Notion, ClickUp — high switching frustration"],
    ],
    [
        ("Client visibility without oversharing","Agencies need to give clients project status without exposing internal commentary, billing rates, or team discussions. Most tools force all-or-nothing access."),
        ("Approval and feedback loops","Creative work requires review → feedback → revision cycles. Generic PM tools track tasks but don't model the approval workflow natively."),
        ("Retainer vs. project work","Many agencies run monthly retainers alongside fixed-scope projects. Tracking both billing models cleanly in one PM tool is rarely supported."),
        ("High tool fatigue","Agencies already use Asana, Notion, Harvest, and Slack. Adding another tool faces strong internal resistance unless immediate value is obvious."),
    ],
    [
        ["Criterion","Score","Notes"],
        ["Market size & accessibility","⭐⭐⭐⭐⭐","Massive, digitally native, easy to reach online"],
        ["Pain intensity","⭐⭐⭐","Existing tools partially work; pain is diffuse"],
        ["Product-market fit today","⭐⭐⭐","Needs approval workflows not yet in VectorPM"],
        ["Sales cycle complexity","⭐⭐⭐","Multiple stakeholders; longer eval cycles"],
        ["Willingness to pay","⭐⭐⭐⭐","Software budget exists; but churn is high"],
        ["Overall Score","3.4 / 5.0","THIRD VERTICAL — longer runway needed"],
    ],
    colors.HexColor("#374151")
)

# COMPARISON
story.append(HRFlowable(width="100%",thickness=2,color=ORANGE))
story.append(Spacer(1,3*mm))
story.append(Paragraph("Comparative Summary & Recommendation", h1_s))
story.append(Spacer(1,2*mm))

ct = Table([
    ["Industry","Market","Pain","PM Fit","Score","Priority"],
    ["Construction","Large","🔴 Critical","High","4.8/5","Launch Wedge"],
    ["Event Management","Large","🟠 High","Medium","3.6/5","Vertical #2"],
    ["Creative Agencies","Very Large","🟡 Medium","Medium","3.4/5","Vertical #3"],
], colWidths=[42*mm,24*mm,26*mm,24*mm,20*mm,34*mm])
ct.setStyle(TableStyle([
    ("BACKGROUND",(0,0),(-1,0),DARK),("TEXTCOLOR",(0,0),(-1,0),WHITE),("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),
    ("BACKGROUND",(0,1),(-1,1),colors.HexColor("#fff7ed")),
    ("FONTNAME",(0,1),(0,1),"Helvetica-Bold"),
    ("TEXTCOLOR",(5,1),(5,1),ORANGE),("FONTNAME",(5,1),(5,1),"Helvetica-Bold"),
    ("FONTSIZE",(0,0),(-1,-1),9),
    ("ROWBACKGROUNDS",(0,2),(-1,-1),[WHITE,SURFACE]),
    ("GRID",(0,0),(-1,-1),0.3,colors.HexColor("#e5e7eb")),
    ("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),
    ("LEFTPADDING",(0,0),(-1,-1),6),("RIGHTPADDING",(0,0),(-1,-1),6),
    ("ALIGN",(1,0),(-1,-1),"CENTER"),("VALIGN",(0,0),(-1,-1),"MIDDLE"),
]))
story.append(ct)
story.append(Spacer(1,4*mm))

rec = Table([[Paragraph(
    "<b>Recommendation: Launch with Construction.</b> It has the highest pain intensity, the clearest product-market fit "
    "with VectorPM's current feature set, and a massive underserved SMB segment priced out of enterprise tools. "
    "Once 50–100 construction teams are acquired and happy, the expansion to Events and Agencies becomes a proven, credible story — "
    "not just a claim.",
    rec_s)]], colWidths=[170*mm])
rec.setStyle(TableStyle([
    ("BACKGROUND",(0,0),(-1,-1),colors.HexColor("#fff7ed")),
    ("LEFTPADDING",(0,0),(-1,-1),14),("RIGHTPADDING",(0,0),(-1,-1),14),
    ("TOPPADDING",(0,0),(-1,-1),12),("BOTTOMPADDING",(0,0),(-1,-1),12),
    ("BOX",(0,0),(-1,-1),2,ORANGE),
]))
story.append(rec)
story.append(Spacer(1,6*mm))

# POSITIONING
story.append(HRFlowable(width="100%",thickness=1,color=colors.HexColor("#e5e7eb")))
story.append(Spacer(1,3*mm))
story.append(Paragraph("Agreed Positioning (Construction Wedge)", h1_s))
story.append(Spacer(1,2*mm))
for label, value in [
    ("Headline","Your projects have phases. Your PM tool should too."),
    ("Subheadline","Track phases, assign handoffs, and keep every subcontractor accountable — without the spreadsheet chaos."),
    ("Expansion Bridge","Turns out, every team works like a construction site — sequential phases, handoffs, deadlines, real accountability."),
    ("Differentiator","Phase-locked, dependency-aware project tracking built for how construction actually works."),
    ("Competitor Policy","No competitor names in any public-facing copy — lead with our own story."),
]:
    rt = Table([[Paragraph(label, pos_l), Paragraph(value, pos_v)]], colWidths=[36*mm,134*mm])
    rt.setStyle(TableStyle([("VALIGN",(0,0),(-1,-1),"TOP"),("TOPPADDING",(0,0),(-1,-1),4),("BOTTOMPADDING",(0,0),(-1,-1),4),("LEFTPADDING",(0,0),(-1,-1),0)]))
    story.append(rt)
    story.append(HRFlowable(width="100%",thickness=0.3,color=colors.HexColor("#e5e7eb")))

story.append(Spacer(1,5*mm))
story.append(HRFlowable(width="100%",thickness=0.5,color=colors.HexColor("#e5e7eb")))
story.append(Spacer(1,3*mm))
story.append(Paragraph("VectorPM Market Research  ·  February 2026  ·  Symph Agency  ·  Confidential — Internal Use Only", foot_s))

doc.build(story)
print(f"PDF saved: {OUTPUT}")
