#!/usr/bin/env python3
"""Build the AI/DE Opportunities Index workbook (.xlsx) for the AIDE Opportunities Audit.

Mirrors the AIDE Matrix and Opportunities Audit Workbook format (9 tabs) and fills it
with the audit's data. Pure standard library: no openpyxl or other packages required.

Usage:
    python3 build_opportunities_index.py --data audit.json --out company-aide-opportunities-index.xlsx

Input JSON schema (all sections optional except opportunities):
{
  "company":   { "name","industry","stage","annualRevenue","ftes","revenuePerFte",
                 "competitors","boardSize","execTeamSize","assessmentDate","completedBy","website" },
  "aideMatrix":{ "boardLiteracy":n,"boardAdvocacy":n,"tmtLiteracy":n,"tmtAdvocacy":n,
                 "orientation":n,"implementation":n,"leadershipScore":n,"companyScore":n,"quadrant":"" },
  "innovation":{ "scores":[n x8], "readinessScore":n, "interpretation":"" },
  "riskAsymmetry":{ "annualRevenue","totalFtes","revenuePerFte","growthTargetPct",
                    "projectedRevenue","projectedFtes","fteGap","annualCostOfGap" },
  "deepDive":  [ { "area","relevance":n,"pain":n,"data":n,"notes":"" } ],
  "opportunities":[ { "functionalArea","name","description","frequencyPerMonth","avgHoursPerMonth",
                      "humanVsAi":1-5,"risk":1-5,"impact":1-5,"feasibility":1-5,
                      "quadrant","owner","nextStep","notes" } ]
}
Priority Score is written as a live formula (=Impact+Feasibility+HumanVsAI+(6-Risk)) so the
workbook stays editable: change a score and the priority recomputes.
Every tab ends with a footer linking PaulCheek.com and NoOneWorksHere.com.
"""
import argparse, json, zipfile
from datetime import date
from xml.sax.saxutils import escape

NAVY = "FF38324A"; BLUE = "FF007FB2"; FOG = "FFF4F5F7"; WHITE = "FFFFFFFF"

# ---------------------------------------------------------------- xlsx writer
class Sheet:
    def __init__(self, name):
        self.name = name
        self.rows = {}          # row_index -> {col_index: (value, style, formula)}
        self.widths = {}        # col_index -> width
        self.links = []         # (cell_ref, url)
    def cell(self, r, c, v, style=0, formula=None):
        self.rows.setdefault(r, {})[c] = (v, style, formula)
    def row(self, r, values, start=1, style=0):
        for i, v in enumerate(values):
            if v is not None:
                self.cell(r, start + i, v, style)
    def link(self, r, c, text, url, style=0):
        self.cell(r, c, text, style)
        self.links.append((ref(r, c), url))
    def width(self, c, w):
        self.widths[c] = w

def col_letter(c):
    s = ""
    while c: c, rem = divmod(c - 1, 26); s = chr(65 + rem) + s
    return s

def ref(r, c): return f"{col_letter(c)}{r}"

STYLES_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<fonts count="6">
<font><sz val="11"/><color rgb="FF38324A"/><name val="Helvetica Neue"/></font>
<font><b/><sz val="16"/><color rgb="FF38324A"/><name val="Helvetica Neue"/></font>
<font><b/><sz val="11"/><color rgb="FFFFFFFF"/><name val="Helvetica Neue"/></font>
<font><b/><sz val="11"/><color rgb="FF38324A"/><name val="Helvetica Neue"/></font>
<font><u/><sz val="10"/><color rgb="FF007FB2"/><name val="Helvetica Neue"/></font>
<font><i/><sz val="10"/><color rgb="FF8E909A"/><name val="Helvetica Neue"/></font>
</fonts>
<fills count="4"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>
<fill><patternFill patternType="solid"><fgColor rgb="%s"/></patternFill></fill>
<fill><patternFill patternType="solid"><fgColor rgb="%s"/></patternFill></fill></fills>
<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>
<cellXfs count="7">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment wrapText="1" vertical="top"/></xf>
<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyAlignment="1"><alignment wrapText="1" vertical="top"/></xf>
<xf numFmtId="0" fontId="3" fillId="3" borderId="0" xfId="0" applyAlignment="1"><alignment wrapText="1" vertical="top"/></xf>
<xf numFmtId="0" fontId="4" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="0" fontId="5" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="0" fontId="3" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment wrapText="1" vertical="top"/></xf>
</cellXfs>
</styleSheet>""" % (NAVY, FOG)
# style ids: 0 body(wrap), 1 title, 2 header(navy/white), 3 subheader(fog/bold), 4 link, 5 footnote, 6 bold

def sheet_xml(sh):
    cols = ""
    if sh.widths:
        cols = "<cols>" + "".join(
            f'<col min="{c}" max="{c}" width="{w}" customWidth="1"/>' for c, w in sorted(sh.widths.items())
        ) + "</cols>"
    rows_xml = []
    for r in sorted(sh.rows):
        cells_xml = []
        for c in sorted(sh.rows[r]):
            v, st, formula = sh.rows[r][c]
            attr = f' s="{st}"' if st else ' s="0"'
            if formula is not None:
                cells_xml.append(f'<c r="{ref(r,c)}"{attr}><f>{escape(formula)}</f></c>')
            elif isinstance(v, (int, float)) and not isinstance(v, bool):
                cells_xml.append(f'<c r="{ref(r,c)}"{attr}><v>{v}</v></c>')
            else:
                cells_xml.append(f'<c r="{ref(r,c)}" t="inlineStr"{attr}><is><t xml:space="preserve">{escape(str(v))}</t></is></c>')
        rows_xml.append(f'<row r="{r}">' + "".join(cells_xml) + "</row>")
    hl = ""
    rels = ""
    if sh.links:
        parts, relparts = [], []
        for i, (cell, url) in enumerate(sh.links, start=1):
            parts.append(f'<hyperlink ref="{cell}" r:id="rIdHL{i}"/>')
            relparts.append(f'<Relationship Id="rIdHL{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="{escape(url)}" TargetMode="External"/>')
        hl = "<hyperlinks>" + "".join(parts) + "</hyperlinks>"
        rels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' + "".join(relparts) + "</Relationships>"
    xml = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
           '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
           'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
           f'{cols}<sheetData>' + "".join(rows_xml) + f"</sheetData>{hl}</worksheet>")
    return xml, rels

def write_workbook(path, sheets):
    z = zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED)
    n = len(sheets)
    z.writestr("[Content_Types].xml",
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
        '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
        '<Default Extension="xml" ContentType="application/xml"/>'
        '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
        + "".join(f'<Override PartName="/xl/worksheets/sheet{i}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>' for i in range(1, n + 1))
        + '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>')
    z.writestr("_rels/.rels",
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
        '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>')
    z.writestr("xl/workbook.xml",
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
        'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>'
        + "".join(f'<sheet name="{escape(sh.name)}" sheetId="{i}" r:id="rId{i}"/>' for i, sh in enumerate(sheets, 1))
        + "</sheets></workbook>")
    z.writestr("xl/_rels/workbook.xml.rels",
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
        + "".join(f'<Relationship Id="rId{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{i}.xml"/>' for i in range(1, n + 1))
        + f'<Relationship Id="rId{n+1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')
    z.writestr("xl/styles.xml", STYLES_XML)
    for i, sh in enumerate(sheets, 1):
        xml, rels = sheet_xml(sh)
        z.writestr(f"xl/worksheets/sheet{i}.xml", xml)
        if rels:
            z.writestr(f"xl/worksheets/_rels/sheet{i}.xml.rels", rels)
    z.close()

def footer(sh, r):
    sh.cell(r, 1, "(c) 2026 Cheek LLC", 5)
    sh.link(r, 2, "PaulCheek.com", "https://paulcheek.com", 4)
    sh.link(r, 3, "NoOneWorksHere.com", "https://noOneWorksHere.com", 4)

# ---------------------------------------------------------------- tabs
FUNCTIONAL_AREAS = [
    ("Strategy & Planning", "Scenario simulation, demand forecasting, board-grade narrative drafting"),
    ("Market & Competitive Intelligence", "Autonomous desk research, sentiment tracking, pricing surveillance"),
    ("Revenue - Sales", "Deal scoring, next-step email drafting, dynamic forecasting"),
    ("Revenue - Marketing", "Asset generation (copy, creatives), intent-based segmentation, SEO brief writing"),
    ("Product & R&D", "Requirements co-authoring, concept testing with synthetic users, design QA"),
    ("Engineering & DevOps", "Code suggestion, test-case authoring, incident root-cause chats"),
    ("Customer Support & Success", "Self-service chat, proactive risk alerts, ticket summarization"),
    ("Operations & Supply Chain", "Demand sensing, dynamic routing, doc extraction for logistics"),
    ("Finance & Accounting", "Invoice coding, close checklist automation, fraud anomaly alerts"),
    ("HR & Talent", "Role-fit assessment chats, internal mobility matching, policy Q&A"),
    ("Legal & Compliance", "Contract risk summarization, clause comparison, control testing"),
    ("Fundraising / Investor Relations", "Investor-match ranking, deck tailoring, FAQ agent"),
]

def build(data, out_path):
    g = lambda d, k, default="": (d or {}).get(k, default)
    sheets = []

    # 1 Instructions
    s = Sheet("Instructions"); sheets.append(s)
    s.width(1, 6); s.width(2, 30); s.width(3, 90)
    s.cell(1, 1, "AI/DE Opportunities Index", 1)
    s.cell(2, 1, "AIDE Matrix and Opportunities Audit Workbook", 6)
    s.cell(3, 1, "Based on Chapter 21 of No One Works Here")
    s.cell(5, 1, "Purpose", 6)
    s.cell(6, 1, "This workbook holds the complete output of your AIDE Opportunities Audit: your company profile, AIDE Matrix position, risk asymmetry, innovation readiness, functional-area scores, and every opportunity surfaced in the audit, scored and prioritized. Edit any score; Priority recomputes automatically.")
    s.cell(8, 1, "How to Use This Workbook", 6)
    steps = [
        ("1", "Company Profile", "Your company details, stage, and strategic context from the audit."),
        ("2", "AIDE Matrix Assessment", "Your scores on the two axes: Strategic Intent & Advocacy (Leadership) and Operational Integration & Adoption (Company), and your quadrant."),
        ("3", "Risk Asymmetry", "The cost of inertia vs. execution, and the New Audit Question for your board."),
        ("4", "Innovation Pre-Requisite", "Whether your innovation culture can support AI adoption."),
        ("5", "Vector of Change", "Quadrant prescriptions and your 90-day action plan."),
        ("6", "Operational Deep Dive", "Functional-area scores for tactical deployment prioritization."),
        ("7", "Process Inventory", "EVERY opportunity from the audit, scored on the four key metrics. This is the Opportunities Index. Edit scores freely; Priority recomputes."),
    ]
    for i, (num, name, desc) in enumerate(steps):
        s.row(9 + i, [num, name, desc])
    s.cell(17, 1, "Scoring Guide", 6)
    for i, (sc, lab, desc) in enumerate([
        ("1", "No activity / Not applicable", "No evidence of this capability in the organization."),
        ("2", "Early awareness", "Topic discussed but no formal action or investment."),
        ("3", "Pilot / Exploratory", "Active experiments, early hires, or initial programs underway."),
        ("4", "Systematic", "Structured programs, measurable KPIs, embedded in workflows."),
        ("5", "Leading / Best-in-class", "Industry-recognized, scaled across the enterprise, driving measurable outcomes."),
    ]):
        s.row(18 + i, [sc, lab, desc])
    footer(s, 24)

    # 2 Company Profile
    c = data.get("company", {})
    s = Sheet("Company Profile"); sheets.append(s)
    s.width(1, 44); s.width(2, 50)
    s.cell(1, 1, "Company Profile", 1)
    fields = [("Company Name", "name"), ("Industry / Sector", "industry"),
              ("Company Stage (Startup / Growth / Scale / Enterprise)", "stage"),
              ("Annual Revenue", "annualRevenue"), ("Team Size (FTEs)", "ftes"),
              ("Current Revenue per FTE", "revenuePerFte"), ("Primary Competitor(s)", "competitors"),
              ("Board Size", "boardSize"), ("Executive Team Size", "execTeamSize"),
              ("Date of Assessment", "assessmentDate"), ("Completed By", "completedBy"), ("Website", "website")]
    for i, (label, key) in enumerate(fields):
        s.cell(3 + i, 1, label, 6); s.cell(3 + i, 2, g(c, key))
    footer(s, 17)

    # 3 AIDE Matrix Assessment
    m = data.get("aideMatrix", {})
    s = Sheet("AIDE Matrix Assessment"); sheets.append(s)
    s.width(1, 5); s.width(2, 34); s.width(3, 64); s.width(4, 14); s.width(5, 9); s.width(6, 60)
    s.cell(1, 1, "AIDE Matrix Self-Assessment", 1)
    s.cell(3, 1, "X-AXIS: STRATEGIC INTENT & ADVOCACY (LEADERSHIP SCORE)", 6)
    s.row(5, ["#", "Dimension", "What to Assess", "Your Score (1-5)", "Weight"], style=2)
    xrows = [(1, "Board AI Literacy", "Hands-on understanding of AI tools and concepts, not just awareness.", g(m, "boardLiteracy", ""), 0.25),
             (2, "Board AI Advocacy", "Public advocacy: posts, talks, governance communications.", g(m, "boardAdvocacy", ""), 0.25),
             (3, "Top Management Team AI Literacy", "Executives' hands-on understanding.", g(m, "tmtLiteracy", ""), 0.25),
             (4, "Top Management Team AI Advocacy", "The single most powerful predictor of organizational AI maturity.", g(m, "tmtAdvocacy", ""), 0.25)]
    for i, row in enumerate(xrows): s.row(6 + i, list(row))
    s.cell(10, 2, "LEADERSHIP SCORE (X-Axis)", 6); s.cell(10, 4, g(m, "leadershipScore", ""))
    s.cell(12, 1, "Y-AXIS: OPERATIONAL INTEGRATION & ADOPTION (COMPANY SCORE)", 6)
    s.row(13, ["#", "Dimension", "What to Assess", "Your Score (1-5)", "Weight"], style=2)
    s.row(14, [1, "AI Orientation", "AI in job postings, earnings calls, communications, planning.", g(m, "orientation", ""), 0.4])
    s.row(15, [2, "AI Implementation", "Tangible deployments: patents, features, infrastructure, workflows.", g(m, "implementation", ""), 0.6])
    s.cell(16, 2, "COMPANY SCORE (Y-Axis)", 6); s.cell(16, 4, g(m, "companyScore", ""))
    s.cell(18, 1, "YOUR AIDE MATRIX POSITION", 6); s.cell(19, 2, g(m, "quadrant", ""), 3)
    s.cell(21, 1, "The Four Quadrants", 6)
    quads = [("LAGGARD (Bottom-Left)", "Low Intent, Low Adoption. Standing still is an active bet against survival."),
             ("AI VISIONARY (Bottom-Right)", "High Intent, Low Adoption. The Magic Wand trap: strategy without execution."),
             ("STEALTH ADOPTER (Top-Left)", "Low Intent, High Adoption. Fragile, ungoverned, hard to scale."),
             ("TRAILBLAZER (Top-Right)", "High Intent, High Adoption. Revenue growth decoupled from headcount growth.")]
    for i, (q, d) in enumerate(quads): s.cell(22 + i, 2, q, 6); s.cell(22 + i, 3, d)
    footer(s, 27)

    # 4 Risk Asymmetry
    ra = data.get("riskAsymmetry", {})
    s = Sheet("Risk Asymmetry"); sheets.append(s)
    s.width(1, 46); s.width(2, 24); s.width(3, 24); s.width(4, 52)
    s.cell(1, 1, "Risk Asymmetry: Inertia vs. Execution", 1)
    s.cell(3, 1, "The most dangerous threat doesn't appear on the risk register: the Risk of Inertia.")
    s.cell(5, 1, "THE NEW AUDIT QUESTION", 6)
    s.cell(6, 1, 'Instead of asking what the risk is if an AI initiative fails, the board must ask: what is the systemic risk to our 10-year valuation if competitors achieve $1M+ ARR/FTE while we remain where we are?')
    s.cell(8, 1, "COST OF INERTIA CALCULATOR", 6)
    s.row(9, ["Metric", "Your Organization", "Competitor Benchmark", "Interpretation"], style=2)
    rows = [("Annual Revenue", g(ra, "annualRevenue"), "", ""),
            ("Total FTEs", g(ra, "totalFtes"), "", ""),
            ("Revenue per FTE", g(ra, "revenuePerFte"), g(ra, "competitorBenchmark", "$1M+ ARR/FTE"), ""),
            ("5-Year Revenue Growth Target (%)", g(ra, "growthTargetPct"), "", ""),
            ("Projected 5-Year Revenue", g(ra, "projectedRevenue"), "", ""),
            ("Projected FTEs Needed at Current Ratio", g(ra, "projectedFtes"), "", ""),
            ("FTE Gap (Yours vs. Competitor Model)", g(ra, "fteGap"), "", "How many more people you need vs. a Trailblazer"),
            ("Estimated Annual Cost of FTE Gap ($100K/FTE)", g(ra, "annualCostOfGap"), "", "The annual cost of operating at human speed")]
    for i, row in enumerate(rows): s.row(10 + i, list(row))
    footer(s, 20)

    # 5 Innovation Pre-Requisite
    innov = data.get("innovation", {})
    dims = ["Experimentation Culture", "Speed of Decision-Making", "Cross-Functional Collaboration",
            "Leadership Appetite for Risk", "Learning Rate", "Resource Allocation for Innovation",
            "Track Record of Scaling New Ideas", "Tolerance for Ambiguity"]
    scores = innov.get("scores", [""] * 8)
    s = Sheet("Innovation Pre-Requisite"); sheets.append(s)
    s.width(1, 5); s.width(2, 38); s.width(3, 16)
    s.cell(1, 1, "Innovation Pre-Requisite Assessment", 1)
    s.cell(3, 1, "The AI muscle and the innovation muscle are the same muscle.")
    s.row(5, ["#", "Dimension", "Your Score (1-5)"], style=2)
    for i, d in enumerate(dims):
        s.row(6 + i, [i + 1, d, scores[i] if i < len(scores) else ""])
    s.cell(14, 2, "INNOVATION READINESS SCORE", 6); s.cell(14, 3, g(innov, "readinessScore", ""))
    s.cell(15, 2, "INTERPRETATION", 6); s.cell(15, 3, g(innov, "interpretation", ""))
    footer(s, 17)

    # 6 Vector of Change
    s = Sheet("Vector of Change"); sheets.append(s)
    s.width(1, 5); s.width(2, 30); s.width(3, 66); s.width(4, 52); s.width(5, 14)
    s.cell(1, 1, "Vector of Change: Your 90-Day Action Plan", 1)
    s.cell(3, 1, "YOUR CURRENT QUADRANT", 6); s.cell(3, 2, g(m, "quadrant", ""), 3)
    s.cell(5, 1, "QUADRANT-SPECIFIC PRESCRIPTION", 6)
    pres = [("If you are a LAGGARD:", "Board and top management AI education plus a single sandbox pilot.", "Board AI literacy program + appoint AI champion + single 8-week pilot"),
            ("If you are an AI VISIONARY:", "You need a Sandbox Policy and an operational AI lead, not more strategy.", "Appoint operational AI lead + fund 2-3 sandbox pilots + define success KPIs within 90 days"),
            ("If you are a STEALTH ADOPTER:", "Solve the boardroom literacy crisis; govern what already works.", "Board AI education sprint + governance framework + catalog existing AI deployments"),
            ("If you are a TRAILBLAZER:", "Run the AIDE maturity cycle iteratively; decouple revenue from headcount.", "Set ARR/FTE targets + expand AI to remaining functions + publish AI strategy externally")]
    for i, row in enumerate(pres): s.row(6 + i, list(row), start=2)
    s.cell(11, 1, "YOUR 90-DAY ACTION PLAN", 6)
    s.row(12, ["#", "Action Item", "Rationale / How It Moves You Top-Right", "Owner", "Target Date"], style=2)
    for i in range(10): s.cell(13 + i, 1, i + 1)
    footer(s, 24)

    # 7 Operational Deep Dive
    dd = {x.get("area"): x for x in data.get("deepDive", [])}
    s = Sheet("Operational Deep Dive"); sheets.append(s)
    s.width(1, 5); s.width(2, 32); s.width(3, 64)
    for cix, w in [(4, 14), (5, 14), (6, 18), (7, 14)]: s.width(cix, w)
    s.width(8, 40)
    s.cell(1, 1, "Operational Deep Dive: Functional Area Scoring", 1)
    s.row(3, ["#", "Functional Area", "High-Impact AI Use Cases", "Relevance (1-5)", "Pain Level (1-5)", "Data Availability (1-5)", "Priority Score", "Notes"], style=2)
    for i, (area, cases) in enumerate(FUNCTIONAL_AREAS):
        r = 4 + i; x = dd.get(area, {})
        s.row(r, [i + 1, area, cases, x.get("relevance", ""), x.get("pain", ""), x.get("data", "")])
        s.cell(r, 7, "", 0, formula=f"IF(COUNT(D{r}:F{r})=3,SUM(D{r}:F{r}),\"\")")
        s.cell(r, 8, x.get("notes", ""))
    base = 4 + len(FUNCTIONAL_AREAS) + 1
    s.cell(base, 1, "PRIORITIZATION GUIDE", 6)
    guide = [("Score 12-15", "Pilot Now: high relevance, high pain, data available. Launch an 8-week pilot."),
             ("Score 9-11", "Build Data Readiness: strong opportunity with data or infrastructure gaps."),
             ("Score 6-8", "Low-Stakes Experiment: fast, cheap experiments to build AI muscle."),
             ("Score 3-5", "Defer: revisit after higher-impact areas are addressed.")]
    for i, (a, b) in enumerate(guide): s.cell(base + 1 + i, 2, a, 6); s.cell(base + 1 + i, 3, b)
    footer(s, base + 6)

    # 8 Process Inventory (the Opportunities Index)
    opps = data.get("opportunities", [])
    s = Sheet("Process Inventory"); sheets.append(s)
    headers = ["Functional Area", "Process / Opportunity Name", "Description", "Frequency (/month)", "Avg Hours/Month",
               "Human vs. AI\n(1=Human; 5=AI)", "Risk\n(1=Low Risk; 5=High Risk)", "Business Impact\n(1=Low; 5=High)",
               "Feasibility\n(1=Not Feasible; 5=Very Feasible)", "Priority Score", "Quadrant", "Owner", "Recommended Next Step", "Notes"]
    widths = [30, 34, 56, 14, 13, 13, 13, 13, 13, 12, 18, 16, 34, 30]
    for i, w in enumerate(widths, 1): s.width(i, w)
    s.cell(1, 1, "Process Inventory: The AI/DE Opportunities Index", 1)
    s.cell(2, 1, "Every opportunity from the audit. Edit any score in F-I and Priority recomputes: Impact + Feasibility + HumanVsAI + (6 - Risk). Bands: 16-20 Pilot Now, 12-15 Build Readiness, 8-11 Low-Stakes Experiment, 4-7 Defer.")
    s.row(4, headers, style=2)
    s.cell(5, 6, "Should we use AI for this?", 3); s.cell(5, 7, "Could using AI negatively impact the business?", 3)
    s.cell(5, 8, "Would using AI drive business results? Avoidance of loss?", 3); s.cell(5, 9, "Can we use AI for this?", 3)
    r0 = 6
    for i, o in enumerate(opps):
        r = r0 + i
        s.row(r, [o.get("functionalArea", ""), o.get("name", ""), o.get("description", ""),
                  o.get("frequencyPerMonth", ""), o.get("avgHoursPerMonth", ""),
                  o.get("humanVsAi", ""), o.get("risk", ""), o.get("impact", ""), o.get("feasibility", "")])
        s.cell(r, 10, "", 0, formula=f"IF(COUNT(F{r}:I{r})=4,H{r}+I{r}+F{r}+(6-G{r}),\"\")")
        s.row(r, [o.get("quadrant", ""), o.get("owner", ""), o.get("nextStep", ""), o.get("notes", "")], start=11)
    footer(s, r0 + max(len(opps), 1) + 2)

    # 9 Tooling Types (Ref)
    s = Sheet("Tooling Types (Ref)"); sheets.append(s)
    s.width(1, 30); s.width(2, 80)
    s.cell(1, 1, "Reference: AI Tooling Landscape", 1)
    s.row(3, ["Layer", "Representative Options"], style=2)
    tools = [("Foundation & Chat Models", "Anthropic Claude, OpenAI GPT, Google Gemini"),
             ("Vertical SaaS Copilots", "GitHub Copilot (engineering), Salesforce Einstein GPT (CRM), Gong Agents (sales)"),
             ("Automation / RPA", "UiPath Autopilot, Zapier Agents, n8n workflows"),
             ("Retrieval & Orchestration", "LangChain, LlamaIndex, Haystack, Pinecone, Weaviate"),
             ("Observability", "Monte Carlo Data, Evidently AI")]
    for i, row in enumerate(tools): s.row(4 + i, list(row))
    footer(s, 10)

    write_workbook(out_path, sheets)
    return len(opps)

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--data", required=True, help="Path to the audit JSON")
    ap.add_argument("--out", required=True, help="Output .xlsx path")
    args = ap.parse_args()
    with open(args.data) as f:
        data = json.load(f)
    n = build(data, args.out)
    print(f"Wrote {args.out} with {n} opportunities in the Process Inventory (index generated {date.today().isoformat()}).")
