"""Reproducible scenario arithmetic and static isometric editorial illustrations.

Run from the repository with scripts/build.py. No company observation is used as
a scenario input. The charts are rendered separately by pinned Apache ECharts.
"""
import csv
from html import escape
import io
import json
import subprocess

SLUG = "l3-ai-economics"


def calculate(inputs):
    n = inputs["monthly_cases"]
    rate = inputs["hourly_loaded_labor_cost_usd"] / 60
    baseline = sum(inputs["baseline_minutes"].values())
    team = sum(inputs["team_automation_minutes"].values())
    audit = inputs["audit_sample_share"] * inputs["human_minutes_per_sampled_case"]
    exception = inputs["human_minutes_per_exception"]
    p = inputs["verified_autonomous_completion_share"]
    recurring = sum(inputs["recurring_monthly_service_cost_usd"].values())
    amortization = inputs["implementation_cost_usd"] / inputs["amortization_months"]
    service = recurring + amortization
    human = (1 - p) * exception + audit
    gross = n * (baseline - human) * rate
    loss = n * inputs["additional_loss_event_probability"] * inputs["additional_loss_per_event_usd"]

    def usable_value(value, realization):
        # A realization discount applies only to released capacity. Any extra
        # human work required by a worse configuration is charged in full.
        return max(value, 0) * realization + min(value, 0)

    realization_rows = [
        {"fraction": r, "usable_capacity_value_usd": round(usable_value(gross, r), 2),
         "service_cost_usd": round(service, 2),
         "net_capacity_value_usd": round(usable_value(gross, r) - service, 2),
         "financial_break_even_autonomous_share":
             (exception + audit - baseline + service / (n * rate * r)) / exception}
        for r in inputs["capacity_realization_fractions"]
    ]
    sensitivity = []
    for share in inputs["sensitivity_autonomous_shares"]:
        minutes = (1 - share) * exception + audit
        capacity = n * (baseline - minutes) * rate
        for r in inputs["capacity_realization_fractions"]:
            sensitivity.append({"autonomous_completion_share": share,
                                "capacity_realization_fraction": r,
                                "human_minutes_per_incoming_case": round(minutes, 4),
                                "potential_capacity_value_usd": round(capacity, 2),
                                "net_capacity_value_usd": round(usable_value(capacity, r) - service, 2)})
    return {"classification": inputs["classification"], "monthly_cases": n,
            "baseline_minutes": baseline, "team_minutes": team,
            "connected_minutes": round(human, 6), "audit_minutes": audit,
            "exception_minutes_per_incoming_case": round((1 - p) * exception, 6),
            "baseline_monthly_hours": n * baseline / 60,
            "connected_monthly_hours": n * human / 60,
            "released_monthly_hours": n * (baseline - human) / 60,
            "baseline_labor_usd": round(n * baseline * rate, 2),
            "connected_labor_usd": round(n * human * rate, 2),
            "recurring_service_usd": recurring,
            "implementation_amortization_usd": amortization,
            "monthly_service_usd": service,
            "connected_labor_and_service_usd": round(n * human * rate + service, 2),
            "potential_capacity_value_usd": round(gross, 2),
            "full_realization_net_usd": round(gross - service, 2),
            "additional_expected_loss_usd": round(loss, 2),
            "net_after_additional_loss_usd": round(gross - service - loss, 2),
            "realization": realization_rows, "sensitivity": sensitivity}


def table(headers, rows):
    return "\n".join(["| " + " | ".join(headers) + " |",
                      "| " + " | ".join("---" for _ in headers) + " |",
                      *("| " + " | ".join(str(v) for v in row) + " |" for row in rows)])


def money(n):
    return ("−" if n < 0 else "") + f"${abs(n):,.0f}"


def expand_l3_economics_content(body, root):
    if "<!-- l3-data:" not in body:
        return body
    inputs = json.loads((root / "content/editorial" / SLUG / "scenario.json").read_text())
    d = calculate(inputs)
    replacements = {
        "work-table": table(["Human work per incoming case", "Baseline", "Team automation", "Connected execution"], [
            ("Substantive task work", "8 min", "4 min", "Included in exception work"),
            ("Context reconstruction", "6 min", "6 min", "Included in exception work"),
            ("Handoff administration", "4 min", "4 min", "Included in exception work"),
            ("Validation and rework", "2 min", "2 min", "Included in exception work"),
            ("All human exception handling", "Included above", "Included above", f"{d['exception_minutes_per_incoming_case']:g} min"),
            ("Additional sampled audit", "Included in baseline", "Included in baseline", f"{d['audit_minutes']:g} min"),
            ("**Total active human time**", f"**{d['baseline_minutes']:g} min**", f"**{d['team_minutes']:g} min**", f"**{d['connected_minutes']:g} min**")]),
        "cost-table": table(["Monthly item", "Baseline", "Connected execution"], [
            ("Human labor", money(d["baseline_labor_usd"]), money(d["connected_labor_usd"])),
            ("Incremental recurring service", "—", money(d["recurring_service_usd"])),
            ("Implementation amortization", "—", money(d["implementation_amortization_usd"])),
            ("**Labor plus incremental service**", f"**{money(d['baseline_labor_usd'])}**", f"**{money(d['connected_labor_and_service_usd'])}**"),
            ("Cost per case, assuming all achieve the required outcome", money(d["baseline_labor_usd"] / d["monthly_cases"]), money(d["connected_labor_and_service_usd"] / d["monthly_cases"]))]),
        "realization-table": table(["Released capacity used productively", "Usable monthly value", "Service allowance", "Modeled net value"], [
            (f"{r['fraction']:.0%}", money(r["usable_capacity_value_usd"]), money(r["service_cost_usd"]), money(r["net_capacity_value_usd"])) for r in d["realization"]])
    }
    for name, replacement in replacements.items():
        body = body.replace(f"<!-- l3-data:{name} -->", replacement)
    if "<!-- l3-data:" in body:
        raise ValueError("Unknown L3 economics table marker")
    return body


def blend(a, b, fraction):
    rgb = lambda c: [int(c[i:i+2], 16) for i in (1, 3, 5)]
    return "#" + "".join(f"{round(x*(1-fraction)+y*fraction):02x}" for x, y in zip(rgb(a), rgb(b)))


class Canvas:
    def __init__(self, palette, title, description, height):
        self.c = palette["colors"]
        self.parts = [f'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="{height}" viewBox="0 0 1200 {height}" role="img" aria-labelledby="title desc">',
                      f'<title id="title">{escape(title)}</title><desc id="desc">{escape(description)}</desc>',
                      '<defs><filter id="shadow" x="-50%" y="-50%" width="200%" height="220%"><feGaussianBlur stdDeviation="8"/></filter>',
                      f'<marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 10 5 0 10Z" fill="{self.c["teal"]}"/></marker></defs>',
                      f'<rect width="1200" height="{height}" rx="24" fill="{self.c["bg"]}"/>',
                      f'<g font-family="{escape(palette["typography"]["sans"], quote=True)}" fill="{self.c["ink"]}">']

    def add(self, value):
        self.parts.append(value)

    def text(self, x, y, value, size=18, color=None, weight=400, anchor="start"):
        self.add(f'<text x="{x}" y="{y}" font-size="{size}" fill="{color or self.c["ink"]}" font-weight="{weight}" text-anchor="{anchor}">{escape(value)}</text>')

    def rect(self, x, y, w, h, fill=None, stroke=None, radius=14):
        self.add(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{radius}" fill="{fill or self.c["paper"]}" stroke="{stroke or self.c["line"]}"/>')

    def path(self, points, color, width=4, dashed=False, arrow=False):
        d = "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in points)
        dash = ' stroke-dasharray="7 8"' if dashed else ""
        marker = ' marker-end="url(#arrow)"' if arrow else ""
        self.add(f'<path d="{d}" fill="none" stroke="{color}" stroke-width="{width}" stroke-linecap="round" stroke-linejoin="round"{dash}{marker}/>')

    def header(self, eyebrow, title, deck):
        self.text(42, 42, eyebrow, 14, self.c["blue"], 650)
        self.text(42, 88, title, 34, weight=650)
        self.text(42, 124, deck, 19, self.c["muted"])

    def finish(self):
        return "\n".join(self.parts + ["</g></svg>\n"])


class Iso:
    def __init__(self, canvas, cx, cy, scale=1):
        self.s, self.cx, self.cy, self.scale = canvas, cx, cy, scale

    def p(self, x, y, z=0):
        return self.cx + (x-y)*.866*self.scale, self.cy + (x+y)*.5*self.scale - z*self.scale

    def polygon(self, vertices, fill, stroke="none"):
        self.s.add('<polygon points="' + " ".join(f"{x:.1f},{y:.1f}" for x, y in vertices) + f'" fill="{fill}" stroke="{stroke}" stroke-linejoin="round"/>')

    def box(self, x, y, z, w, d, h, color):
        top = blend(color, "#ffffff", .5)
        left = blend(color, "#ffffff", .18)
        right = blend(color, self.s.c["ink"], .16)
        self.polygon([self.p(x,y+d,z),self.p(x+w,y+d,z),self.p(x+w,y+d,z+h),self.p(x,y+d,z+h)],left)
        self.polygon([self.p(x+w,y,z),self.p(x+w,y+d,z),self.p(x+w,y+d,z+h),self.p(x+w,y,z+h)],right)
        self.polygon([self.p(x,y,z+h),self.p(x+w,y,z+h),self.p(x+w,y+d,z+h),self.p(x,y+d,z+h)],top)

    def building(self, x, y, color, height=82, w=62, d=54):
        self.box(x-6,y-6,0,w+12,d+12,8,self.s.c["line"])
        self.box(x,y,8,w,d,height,color)
        self.box(x-3,y-3,height+8,w+6,d+6,5,blend(color,"#ffffff",.7))
        for row in range(3):
            for col in range(3):
                a=x+8+col*17; z=21+row*19
                self.polygon([self.p(a,y+d+.2,z),self.p(a+9,y+d+.2,z),self.p(a+9,y+d+.2,z+9),self.p(a,y+d+.2,z+9)],self.s.c["paper"])
        self.box(x+w*.38,y+d+.2,8,w*.24,1,20,blend(color,self.s.c["ink"],.45))

    def person(self, x, y, color):
        self.box(x-3,y-2,0,3,5,12,self.s.c["muted"])
        self.box(x+2,y-2,0,3,5,12,self.s.c["muted"])
        self.box(x-5,y-3,11,12,7,18,color)
        a,b=self.p(x,y,37)
        self.s.add(f'<circle cx="{a:.1f}" cy="{b:.1f}" r="{6*self.scale}" fill="#C79F85"/>')

    def plant(self, x, y):
        self.box(x-2,y-2,0,4,4,25,self.s.c["muted"])
        a,b=self.p(x,y,37)
        self.s.add(f'<circle cx="{a:.1f}" cy="{b:.1f}" r="{15*self.scale}" fill="{blend(self.s.c["teal"],"#ffffff",.64)}"/>')


def connected_enterprise(palette):
    s=Canvas(palette,"From functional islands to connected execution", "Two isometric enterprises compare repeated human handoffs with bounded cross-system execution. Conceptual diagram, not measured data.",760)
    c=s.c
    s.header("L3 / THE ECONOMICS OF COORDINATION", "Connect the work across the company.", "The same functions. A different way to carry a case from request to resolution.")
    for center, connected in ((306,False),(894,True)):
        left=center-282
        s.rect(left,165,564,526)
        s.text(left+25,203,"CONNECTED EXECUTION" if connected else "FUNCTIONAL ISLANDS",15,c["teal"] if connected else c["amber"],650)
        s.text(left+25,235,"Shared context and bounded action" if connected else "People relay the case between teams",21,weight=600)
        iso=Iso(s,center,461,.78)
        s.add(f'<ellipse cx="{center}" cy="530" rx="218" ry="49" fill="{c["ink"]}" opacity=".10" filter="url(#shadow)"/>')
        iso.box(-190,-150,-22,380,300,22,c["blueLight"] if connected else c["line"])
        iso.polygon([iso.p(-180,-140,1),iso.p(180,-140,1),iso.p(180,140,1),iso.p(-180,140,1)],c["paper"])
        positions=[(-140,-100,"Operations",c["tealLight"]),(48,-100,"Finance",c["amberLight"]),(-140,70,"Support",c["blueLight"]),(48,70,"Sales",blend(c["blue"],"#ffffff",.78))]
        if connected:
            for x,y,_,_ in positions:
                s.path([iso.p(x+32,y+28,3),iso.p(0,15,3)],blend(c["teal"],"#ffffff",.52),9)
                s.path([iso.p(x+32,y+28,4),iso.p(0,15,4)],c["teal"],2,True)
        else:
            s.path([iso.p(-105,-25,3),iso.p(85,-25,3),iso.p(85,35,3),iso.p(-105,35,3)],c["amber"],3,True)
        if connected:
            iso.box(-22,-8,4,50,46,29,c["blue"])
            px,py=iso.p(3,38,19)
            s.text(round(px),round(py),"AI",12,c["paper"],650,"middle")
        for x,y,name,color in sorted(positions,key=lambda item:item[0]+item[1]):
            iso.building(x,y,color)
            px,py=iso.p(x+30,y+42,0)
            s.text(round(px),round(py-111 if name=="Operations" else py+33),name,15,c["muted"],550,"middle")
        if connected:
            iso.person(145,22,c["teal"])
        else:
            for x,y in [(-80,-18),(35,2),(-40,36)]:iso.person(x,y,c["amber"])
        iso.plant(-165,115);iso.plant(150,-115)
        s.rect(left+24,601,516,59,c["tealLight"] if connected else c["amberLight"],radius=12)
        s.text(center,626,"Identity · Policy · Verified records" if connected else "Search · Explain · Transfer · Reconcile",17,c["ink"],550,"middle")
        s.text(center,648,"People own outcomes and exceptions" if connected else "The next team reconstructs the context",15,c["muted"],400,"middle")
    s.text(42,732,"CONCEPTUAL / Functions retain expertise; the shared service changes their interfaces.",15,c["muted"])
    return s.finish()


def verified_execution(palette):
    s=Canvas(palette,"Bounded execution with verified outcomes", "Four isometric stations connect source evidence, a proposed action, enforced authority and verified records. A human service receives exceptions; a shared control layer underpins the workflow.",740)
    c=s.c
    s.header("L3 / AN INSPECTABLE OPERATING LOOP", "A permitted action needs a verified result.", "Trace the case, constrain its authority, check the changed records and recover failures.")
    s.rect(806,164,350,112,c["amberLight"])
    reviewer=Iso(s,851,247,.65);reviewer.person(0,0,c["amber"])
    s.text(884,201,"Human exception service",18,weight=650)
    s.text(884,229,"Judgment · Approval · Recovery",15,c["muted"])
    s.text(884,253,"Named owner and service target",15,c["muted"])
    s.path([(690,363),(742,294),(829,273)],c["amber"],3,True)
    s.text(570,256,"Outside delegated limits",15,c["amber"],550)
    xs=[180,450,720,990]
    s.path([(205,431),(1100,431)],blend(c["teal"],"#ffffff",.6),14)
    s.path([(205,431),(1100,431)],c["teal"],3,False,True)
    names=[("01","Evidence","Source records + freshness",c["blueLight"]),
           ("02","Proposed action","Case + applicable policy",c["blueLight"]),
           ("03","Authority gate","Identity + permitted scope",c["amberLight"]),
           ("04","Verified outcome","Actual records + follow-up",c["tealLight"])]
    for x,(number,name,detail,color) in zip(xs,names):
        iso=Iso(s,x,402,.75)
        iso.box(-63,-57,-10,126,114,10,c["line"])
        if number=="01":
            for a,b in [(-30,-20),(-3,-30),(24,-9)]:iso.box(a,b,0,24,30,60,c["blueLight"])
        elif number=="02":iso.building(-32,-25,color,65)
        elif number=="03":
            iso.box(-36,-22,0,10,47,90,c["amber"]);iso.box(27,-22,0,10,47,90,c["amber"]);iso.box(-36,-22,85,73,47,10,c["amber"])
        else:
            iso.box(-38,-28,0,76,56,61,c["teal"])
            px,py=iso.p(0,28,37)
            s.path([(px-12,py-2),(px-4,py+5),(px+13,py-14)],c["paper"],4)
        s.text(x,496,number+" / "+name,21,weight=600,anchor="middle")
        s.text(x,525,detail,16,c["muted"],anchor="middle")
    s.rect(42,575,1116,104,c["blueLight"])
    s.text(68,610,"SHARED CONTROL LAYER",14,c["blue"],650)
    for i,(title,detail) in enumerate([("Identity","Scoped access"),("Policy","Enforced action limits"),("Audit","Evidence and lineage"),("Recovery","Retries and repair")]):
        x=68+i*278
        s.text(x,641,title,20,weight=600);s.text(x,665,detail,16,c["muted"])
    s.text(42,714,"CONCEPTUAL / A model's claim of completion is evidence to inspect, not the final business outcome.",15,c["muted"])
    return s.finish()


def outcome_organization(palette):
    s=Canvas(palette,"Organize around outcomes with domain expertise and shared infrastructure", "Three isometric platforms show a service owner accountable for results, domain specialists owning knowledge and policy, and a platform team maintaining the execution foundation. This is a proposed operating design.",650)
    c=s.c
    s.header("L3 / A PROPOSED OPERATING DESIGN", "Change responsibility as execution changes.", "One owner for the outcome. Domain expertise and platform reliability remain explicit.")
    columns=[(213,"Outcome ownership",["Quality · Cost · Backlog","Customer result + exceptions"],c["teal"]),
             (600,"Domain expertise",["Policies · Knowledge · Judgment","Finance, operations and service"],c["blue"]),
             (987,"Shared platform",["Connectors · Identity · Validation","Reliability, monitoring and repair"],c["amber"])]
    s.path([(280,363),(920,363)],blend(c["teal"],"#ffffff",.6),10)
    for x,title,details,color in columns:
        iso=Iso(s,x,350,.9)
        s.add(f'<ellipse cx="{x}" cy="395" rx="151" ry="40" fill="{c["ink"]}" opacity=".08" filter="url(#shadow)"/>')
        iso.box(-100,-80,-23,200,160,23,blend(color,"#ffffff",.72))
        if title=="Outcome ownership":
            iso.building(-40,-20,blend(color,"#ffffff",.7),92)
            iso.person(62,34,color);iso.person(-59,43,color)
        elif title=="Domain expertise":
            for a,b in [(-60,-42),(15,-48),(-18,30)]:iso.building(a,b,blend(color,"#ffffff",.78),55,40,34)
        else:
            for a,b in [(-55,-40),(5,-40),(-55,30),(5,30)]:
                iso.box(a,b,0,36,28,55,blend(color,"#ffffff",.56))
                for z in [14,28,42]:iso.box(a+5,b+29,z,24,1,2,c["paper"])
        iso.plant(75,-60)
        s.text(x,462,title,25,weight=600,anchor="middle")
        s.text(x,496,details[0],17,c["muted"],anchor="middle")
        s.text(x,524,details[1],16,c["muted"],anchor="middle")
    s.rect(42,565,1116,55,c["paper"])
    s.text(600,599,"Measure the complete service. Assign released capacity. Retain expertise for the remaining work.",18,c["ink"],550,"middle")
    return s.finish()


def build_l3_economics_assets(root):
    source = root / "content/editorial" / SLUG
    if not (source / "index.md").exists():
        return {}
    inputs = json.loads((source / "scenario.json").read_text())
    datasets = calculate(inputs)
    palette = json.loads((root / "theme/palette.json").read_text())
    public = f"assets/editorial/{SLUG}"
    outputs = {f"{public}/scenario.json": (source / "scenario.json").read_text(),
               f"{public}/sources.json": (source / "sources.json").read_text(),
               f"{public}/calculated-results.json": json.dumps(datasets, indent=2) + "\n",
               f"{public}/l3_economics_figures.py": (root / "scripts/l3_economics_figures.py").read_text(),
               f"{public}/connected-enterprise.svg": connected_enterprise(palette),
               f"{public}/verified-execution.svg": verified_execution(palette),
               f"{public}/outcome-organization.svg": outcome_organization(palette)}
    csv_data=io.StringIO()
    writer=csv.DictWriter(csv_data,fieldnames=list(datasets["sensitivity"][0]),lineterminator="\n")
    writer.writeheader();writer.writerows(datasets["sensitivity"])
    outputs[f"{public}/sensitivity.csv"]=csv_data.getvalue()
    try:
        result = subprocess.run(["node", str(root / "scripts/render_l3_economics_charts.mjs")],
                                input=json.dumps({"palette":palette,"inputs":inputs,"datasets":datasets}),
                                capture_output=True,text=True,check=True,timeout=30)
    except (OSError,subprocess.SubprocessError) as error:
        raise ValueError(f"L3 economics charts require ECharts: {getattr(error,'stderr','') or error}") from error
    outputs.update({f"{public}/{name}":value for name,value in json.loads(result.stdout).items()})
    return outputs


if __name__ == "__main__":
    import argparse
    from pathlib import Path
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--scenario",type=Path,required=True)
    parser.add_argument("--palette",type=Path)
    parser.add_argument("--svg-dir",type=Path)
    args=parser.parse_args()
    if args.svg_dir and not args.palette:
        parser.error("--svg-dir requires --palette")
    print(json.dumps(calculate(json.loads(args.scenario.read_text())),indent=2))
    if args.svg_dir:
        p=json.loads(args.palette.read_text());args.svg_dir.mkdir(parents=True,exist_ok=True)
        for name,fn in [("connected-enterprise",connected_enterprise),("verified-execution",verified_execution),("outcome-organization",outcome_organization)]:
            (args.svg_dir/(name+".svg")).write_text(fn(p))
