#!/usr/bin/env python3
"""Second batch of course figures (lessons 7-11 + reference).

Imported and run by make_diagrams.py; kept in its own file only so neither
module becomes unreadably long.
"""

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from diagram_kit import (  # noqa: E402
    Diagram, INK, MUTED, LINE, SOFT, NAVY, TEAL, AMBER, PLUM, SLATE, hchain,
    T_NAVY, T_TEAL, T_AMBER, T_TONE,
)
import make_diagrams as A  # noqa: E402


def emit(dg, name):
    return A.emit(dg, name)


# ============================================================ Lesson 7

def five_links():
    d = Diagram(900, 220, "Every bill is these five links")
    links = [
        [("① PERIOD", 12.5, "bold"), ("from when", 10.5), ("to when", 10.5)],
        [("② QUANTITY", 12.5, "bold"), ("consumption per", 10.5),
         ("register — readings", 10.5), ("or profiles", 10.5)],
        [("③ RATE", 12.5, "bold"), ("which rules apply,", 10.5),
         ("in what order", 10.5)],
        [("④ PRICE", 12.5, "bold"), ("what each unit", 10.5),
         ("costs, by date", 10.5)],
        [("⑤ POSTING", 12.5, "bold"), ("where the money", 10.5),
         ("lands, and who", 10.5), ("owes it", 10.5)],
    ]
    hchain(d, 34, 26, links, 148, 112, gap=26,
           kind=["navy", "teal", "slate", "plum", "amber"])
    d.box(26, 166, 848, 40,
          [("When a bill is wrong, exactly one link is broken. Check them in this order.",
            12, "bold")], "soft")
    emit(d, "five_links")


def rate_nesting():
    d = Diagram(900, 470, "How a tariff is actually built")
    cx = 320
    rows = [
        (["RATE CATEGORY", "on the INSTALLATION — \"household electricity, single tariff\""],
         "navy", "decides the whole pricing world for this supply point"),
        (["RATE DETERMINATION", "which rates apply, and when"],
         "slate", "runs at the start of every billing run"),
        (["RATE", "one calculation block — base price, consumption, levy, tax"],
         "teal", "each rate is a sequence of steps"),
        (["VARIANT PROGRAM", "SAP-delivered arithmetic: qty × price, tiered, time-proportional"],
         "plum", "you configure these, you rarely code them"),
        (["PRICES + OPERANDS", "the numbers and the inputs"],
         "amber", "prices, quantities, installation facts, flags"),
    ]
    y = 26
    for (lines, kind, note) in rows:
        d.box(cx - 250, y, 500, 60,
              [(lines[0], 12.5, "bold"), (lines[1], 10.5)], kind)
        d.note(cx + 264, y + 34, note)
        y += 60
        if y < 350:
            d.arrow(cx, y + 2, cx, y + 24)
            y += 26
    d.box(70, 440, 760, 0, [], "ghost", rx=0)
    d.caption(450, 452,
              "Rate determination is where 90 % of \"why did it charge that?\" investigations end.")
    emit(d, "rate_nesting")


def period_split():
    d = Diagram(900, 250, "A price change splits the billing period")
    y = 96
    d.box(70, y, 380, 62,
          [("01.01  —  31.03", 12.5, "bold"), ("price €0.28 / kWh", 11)],
          "teal")
    d.box(454, y, 376, 62,
          [("01.04  —  30.06", 12.5, "bold"), ("price €0.31 / kWh", 11)],
          "navy")
    d.line(452, 60, 452, 194, color=AMBER, sw=2, dash="5 4")
    d.text(452, 50, "price change date", size=11.5, color=T_AMBER, weight="bold")

    d.arrow(180, 190, 180, 168)
    d.arrow(720, 190, 720, 168)
    d.caption(450, 212,
              "One reading a year means we don't know when it was used — so consumption is")
    d.caption(450, 230,
              "apportioned across the slices, pro-rata by days or weighted by a load profile.")
    emit(d, "period_split")


def bill_vs_invoice():
    d = Diagram(900, 340, "Billing calculates. Invoicing charges.")
    d.box(30, 46, 250, 56,
          [("electricity contract", 12, "bold")], "plain")
    d.box(30, 122, 250, 56, [("gas contract", 12, "bold")], "plain")
    d.arrow(282, 74, 316, 74)
    d.arrow(282, 150, 316, 150)
    d.box(318, 46, 200, 56,
          [("BILLING", 12, "bold"), ("billing document A", 10.5)], "teal")
    d.box(318, 122, 200, 56,
          [("BILLING", 12, "bold"), ("billing document B", 10.5)], "teal")
    d.note(318, 30, "per CONTRACT · posts nothing")

    d.path("M520,74 L560,74 L560,112", marker=False)
    d.path("M520,150 L560,150 L560,112", marker=False)
    d.arrow(560, 112, 596, 112)
    d.box(598, 84, 272, 58,
          [("INVOICING", 12.5, "bold"),
           ("one invoice, one amount to pay", 10.5)], "amber")
    d.note(598, 68, "per CONTRACT ACCOUNT · posts")

    d.arrow(734, 144, 734, 176)
    d.line(640, 176, 828, 176, color=MUTED)
    d.line(640, 176, 640, 196, color=MUTED)
    d.line(828, 176, 828, 196, color=MUTED)
    d.box(500, 198, 280, 52,
          [("print document", 11.5, "bold"), ("letter / PDF / portal", 10.5)],
          "plain")
    d.box(788, 198, 92, 52, [("FI-CA", 11.5, "bold"), ("open item", 10.5)],
          "navy")

    d.box(30, 278, 840, 40,
          [("Two calculations, one envelope, one amount to pay — that is why the two steps exist.",
            11.5, "bold")], "soft")
    emit(d, "bill_vs_invoice")


def money_lifecycle():
    d = Diagram(900, 520, "The money lifecycle in FI-CA")
    cx = 300
    d.box(cx - 160, 24, 320, 52,
          [("INVOICE POSTS", 12.5, "bold"),
           ("open item on the contract account", 10.5)], "amber")
    d.arrow(cx, 78, cx, 106)

    d.box(cx - 160, 108, 320, 52, [("PAYMENT", 12.5, "bold")], "teal")
    for i, t in enumerate(["direct debit / SEPA payment run",
                           "bank statement, automatic clearing",
                           "cash, agency, portal or card"]):
        d.note(cx + 175, 122 + i * 20, "· " + t)
    d.arrow(cx, 162, cx, 196)
    d.caption(cx + 84, 184, "if not paid…")

    d.box(cx - 160, 198, 320, 52, [("DUNNING", 12.5, "bold")], "slate")
    for i, t in enumerate(["proposal run selects overdue items",
                           "activity run: letters, fees, interest",
                           "reminder → warning → notice"]):
        d.note(cx + 175, 212 + i * 20, "· " + t)
    d.arrow(cx, 252, cx, 286)

    d.box(cx - 160, 288, 320, 52,
          [("DISCONNECTION", 12.5, "bold"),
           ("a field job — legally constrained", 10.5)], "navy")
    d.arrow(cx, 342, cx, 376)
    d.caption(cx + 96, 364, "if still unpaid…")

    d.box(cx - 160, 378, 320, 52, [("COLLECTIONS", 12.5, "bold")], "plum")
    for i, t in enumerate(["instalment plan or deferral",
                           "external collection agency",
                           "write-off (authorised, audited)",
                           "insolvency handling"]):
        d.note(cx + 175, 392 + i * 20, "· " + t)

    d.box(60, 462, 780, 40,
          [("FI-CA holds every item in detail; only summarised totals reach the general ledger.",
            11.5, "bold")], "soft")
    emit(d, "money_lifecycle")


def billing_calendar():
    d = Diagram(900, 380, "One portion's monthly cycle")
    x0, y = 132, 130
    d.line(x0 - 40, y, 808, y, color=LINE, sw=2)
    events = [
        (0, "Day 1–5", "meter reading orders\ncreated & distributed", TEAL, True),
        (1, "Day 5–10", "readings captured,\nuploaded, validated", TEAL, False),
        (2, "Day 11", "readings released;\nimplausible cases cleared", SLATE, True),
        (3, "Day 12", "BILLING RUN\n→ billing documents", AMBER, False),
        (4, "Day 14", "INVOICING RUN\n→ posts to FI-CA", AMBER, True),
        (5, "Day 15", "PRINT run\n→ letters, PDFs, portal", SLATE, False),
        (6, "Day 25", "PAYMENT RUN\n(direct debits)", NAVY, True),
        (7, "Day 28+", "returns processed;\nDUNNING for the unpaid", NAVY, False),
    ]
    step = 636 / (len(events) - 1)
    for i, (idx, day, label, col, above) in enumerate(events):
        cx = x0 + i * step
        d.raw(f'<circle cx="{cx:.1f}" cy="{y}" r="7" fill="{col}"/>')
        first, _, second = label.partition("\n")
        if above:
            d.line(cx, y - 8, cx, y - 34, color=LINE)
            d.text(cx, y - 74, day, size=11, color=T_TONE[col], weight="bold")
            d.text(cx, y - 58, first, size=10.5, color=INK)
            d.text(cx, y - 44, second, size=10.5, color=MUTED)
        else:
            d.line(cx, y + 8, cx, y + 34, color=LINE)
            d.text(cx, y + 50, day, size=11, color=T_TONE[col], weight="bold")
            d.text(cx, y + 66, first, size=10.5, color=INK)
            d.text(cx, y + 80, second, size=10.5, color=MUTED)

    d.box(70, 244, 780, 44,
          [("Twelve portions, twelve of these overlapping every month. That is a utility's heartbeat.",
            11.5, "bold")], "soft")
    d.caption(450, 322,
              "Day 20: budget billing instalments fall due · exceptions are worked continuously")
    emit(d, "billing_calendar")


# ============================================================ Lesson 8

def service_layers():
    d = Diagram(900, 470, "The four layers of utility customer service")
    rows = [
        ("SELF-SERVICE", "customer solves it alone — portal, app, IVR, chatbot",
         "60–80 % of contacts in a mature utility", "teal", "cents"),
        ("FRONT OFFICE", "agent solves it live, on the call",
         "target: first-contact resolution", "navy", "a few €"),
        ("BACK OFFICE", "specialist solves it later",
         "clarification cases, exception worklists, corrections", "slate", "more"),
        ("FIELD SERVICE", "somebody has to physically go there",
         "service orders, dispatch, mobile app", "plum", "tens to hundreds of €"),
    ]
    y = 40
    for name, what, detail, kind, cost in rows:
        d.box(60, y, 620, 78,
              [(name, 12.5, "bold"), (what, 11), (detail, 10.5)], kind)
        d.text(700, y + 44, cost, size=11.5, color=INK, anchor="start",
               weight="bold")
        y += 96
    d.path(f"M690,34 L690,406", color=MUTED, sw=1.6)
    d.text(760, 26, "cost per contact", size=11, color=MUTED, anchor="middle",
           weight="bold")
    d.box(60, 420, 780, 38,
          [("Every layer you push work UP out of saves real money — which is why the portal is a business case.",
            11.5, "bold")], "soft")
    emit(d, "service_layers")


def service_order_chain():
    d = Diagram(900, 200, "From contact to closed job")
    hchain(d, 44, 26, [
        [("Contact", 12, "bold"), ("\"no power\"", 10.5)],
        [("SERVICE", 11.5, "bold"), ("NOTIFICATION", 11.5, "bold"),
         ("what, where, urgency", 10)],
        [("SERVICE ORDER", 11.5, "bold"), ("operations, materials,", 10),
         ("skills, duration", 10)],
        [("DISPATCH", 11.5, "bold"), ("who, when,", 10),
         ("in what order", 10)],
        [("MOBILE EXECUTION", 11, "bold"), ("work, readings,", 10),
         ("photos, materials", 10)],
    ], 148, 100, gap=26,
        kind=["plain", "amber", "navy", "plain", "teal"])
    d.caption(450, 176,
              "Then: device record updated (lesson 6) and costs settled in CO (lesson 10).")
    emit(d, "service_order_chain")


# ============================================================ Lesson 9

def three_reporting():
    d = Diagram(900, 330, "Three kinds of reporting, three audiences")
    cols = [
        ("① OPERATIONAL", "\"What must I fix today?\"",
         ["worklists", "exception queues", "due lists"],
         "Priya, Deniz, Tomas", "real time, per case", "teal"),
        ("② MANAGEMENT", "\"How is the business doing?\"",
         ["KPIs", "trends and dashboards", "forecasts"],
         "Sabine, the board", "periodic, aggregated", "navy"),
        ("③ REGULATORY", "\"Prove it to the regulator.\"",
         ["fixed formats", "fixed deadlines", "auditable"],
         "Frau Dr. Ostermann", "periodic, exact", "plum"),
    ]
    for i, (title, q, items, who, when, kind) in enumerate(cols):
        x = 30 + i * 288
        d.box(x, 26, 264, 240, [], "plain")
        d.box(x, 26, 264, 44, [(title, 12.5, "bold")], kind)
        d.text(x + 132, 92, q, size=11.5, color=INK, weight="bold")
        for j, it in enumerate(items):
            d.note(x + 22, 122 + j * 19, "· " + it)
        d.line(x + 16, 192, x + 248, 192, color=LINE)
        d.text(x + 132, 214, who, size=11, color=MUTED)
        d.text(x + 132, 234, when, size=11, color=MUTED)
    d.box(30, 286, 840, 38,
          [("A dashboard can be 2 % off and still useful. A regulatory report cannot be 0.01 % off.",
            11.5, "bold")], "soft")
    emit(d, "three_reporting")


# ============================================================ Lesson 10

def integration_map():
    d = Diagram(900, 470, "What IS-U is connected to")
    d.box(250, 30, 400, 74,
          [("SAP IS-U", 14, "bold"),
           ("master data · billing · FI-CA", 11)], "navy")

    inner = [("FI", "G/L, tax,\nAR/AP"), ("CO", "cost centres,\nprofitability"),
             ("MM", "meters as\nstock"), ("PM", "field work,\nasset history"),
             ("CRM", "customer\nengagement")]
    for i, (name, sub) in enumerate(inner):
        x = 32 + i * 172
        d.box(x, 176, 156, 74,
              [(name, 12.5, "bold")] +
              [(s, 10) for s in sub.split("\n")], "teal")
        d.arrow(450, 106, x + 78, 172)

    d.box(60, 300, 780, 116, [], "soft")
    d.text(80, 326, "THIRD PARTY / EXTERNAL", size=11.5, color=MUTED,
           anchor="start", weight="bold")
    ext = ["AMI head-end · MDUS", "market partners (EDIFACT)",
           "banks (SEPA)", "print & output", "GIS · portals · mobile",
           "collection agencies"]
    for i, e in enumerate(ext):
        d.box(80 + (i % 3) * 250, 340 + (i // 3) * 40, 232, 32,
              [(e, 10.5, "bold")], "plain")
    # External systems talk to IS-U itself, not to the module row — so route
    # this connector up the margin rather than through the FI/CO/MM boxes.
    d.path("M60,358 L20,358 L20,67 L246,67")
    d.path("M654,67 L880,67 L880,358 L844,358")
    d.caption(450, 442,
              "Half of a utility's process happens outside the company entirely.")
    emit(d, "integration_map")


def two_ledger():
    d = Diagram(900, 300, "Detail in FI-CA, summary in FI")
    hchain(d, 60, 40, [
        [("IS-U BILLING", 12, "bold"), ("billing document", 10.5),
         ("per contract", 10.5)],
        [("FI-CA  (sub-ledger)", 12, "bold"),
         ("one open item per customer —", 10.5),
         ("millions of them", 10.5)],
        [("FI  (general ledger)", 12, "bold"),
         ("SUMMARISED postings —", 10.5), ("a few thousand lines", 10.5)],
    ], 252, 96, gap=48, kind=["teal", "navy", "slate"])
    d.text(474, 190, "grouped by RECONCILIATION KEY, then transferred",
           size=11, color=T_AMBER, weight="bold")
    d.line(344, 172, 604, 172, color=AMBER, sw=1.4, dash="4 4")

    d.box(60, 218, 780, 60,
          [("When IS-U and FI disagree, it is almost always one of three things:", 11.5, "bold"),
           ("detail vs. summary   ·   timing / cut-off   ·   different selection", 11.5)],
          "soft")
    emit(d, "two_ledger")


def crm_isu():
    d = Diagram(900, 260, "The classic ECC + CRM landscape")
    d.box(70, 40, 320, 96,
          [("SAP CRM", 13, "bold"), ("Interaction Center", 11),
           ("campaigns · service requests", 10.5)], "teal")
    d.box(510, 40, 320, 96,
          [("SAP IS-U  (ECC)", 13, "bold"), ("master data of record", 11),
           ("contracts · billing · FI-CA", 10.5)], "navy")
    d.arrow(394, 76, 506, 76)
    d.arrow(506, 100, 394, 100)
    d.text(450, 30, "middleware replication", size=11, color=T_AMBER,
           weight="bold")

    d.box(70, 160, 760, 76,
          [("The recurring pain: replication lag and errors, ambiguity over which system may change a field,",
            11.5, "bold"),
           ("and double maintenance of configuration. It is a major driver of the move to S/4HANA Utilities.",
            11.5)], "soft")
    emit(d, "crm_isu")


# ============================================================ Lesson 11

def regulation_families():
    d = Diagram(900, 300, "The six families of utility regulation")
    fams = [
        ("① MARKET CONDUCT", "switching, market communication,\ndeadlines, unbundling", "navy"),
        ("② CONSUMER PROTECTION", "billing accuracy, complaints,\ndisconnection rules, notice periods", "teal"),
        ("③ METROLOGY", "meters as legal instruments:\ncalibration and certification", "slate"),
        ("④ DATA PROTECTION", "GDPR — consumption data\nis personal data", "plum"),
        ("⑤ FINANCIAL & TAX", "accounting standards, tax,\nretention, auditability", "amber"),
        ("⑥ ENERGY POLICY", "efficiency obligations, levies,\nreporting, emissions", "slate"),
    ]
    for i, (name, sub, kind) in enumerate(fams):
        x = 30 + (i % 3) * 288
        y = 30 + (i // 3) * 110
        d.box(x, y, 264, 92,
              [(name, 11.5, "bold")] + [(s, 10.5) for s in sub.split("\n")],
              kind)
    d.box(30, 254, 840, 38,
          [("Every one of these resolves into a dated master-data setting, a documented process step, or a report.",
            11.5, "bold")], "soft")
    emit(d, "regulation_families")


# ============================================================ Reference

def money_flow():
    d = Diagram(900, 560, "Following the money, object by object")
    cx = 330
    steps = [
        ([("meter reading", 12.5, "bold"),
          ("on a REGISTER — dated, with a reason and a type", 10.5)], "plain",
         "tables EABL / EABLG"),
        ([("consumption", 12.5, "bold"),
          ("this reading − previous reading", 10.5)], "soft",
         "attributed to the INSTALLATION"),
        ([("BILLING  →  billing document", 12.5, "bold"),
          ("rate determination · quantity × price", 10.5)], "teal",
         "per CONTRACT · table ERCH"),
        ([("INVOICING  →  invoice + print document", 12.5, "bold"),
          ("bundles contracts · applies budget billing", 10.5)], "amber",
         "per CONTRACT ACCOUNT"),
        ([("FI-CA open item", 12.5, "bold"),
          ("payment run clears it — or dunning begins", 10.5)], "navy",
         "table DFKKOP"),
        ([("summarised posting → FI general ledger", 12, "bold")], "slate",
         "via the reconciliation key"),
    ]
    y = 30
    for lines, kind, note in steps:
        d.box(cx - 250, y, 500, 62, lines, kind)
        d.note(cx + 264, y + 36, note)
        y += 62
        if y < 460:
            d.arrow(cx, y + 2, cx, y + 26)
            y += 28
    emit(d, "money_flow")


def build_all():
    five_links()
    rate_nesting()
    period_split()
    bill_vs_invoice()
    money_lifecycle()
    billing_calendar()
    service_layers()
    service_order_chain()
    three_reporting()
    integration_map()
    two_ledger()
    crm_isu()
    regulation_families()
    money_flow()
