#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Erzeugt 'gehaltsverhandlung_reallohn.html' aus 'gehalt.json'.

Die jährlichen Daten (Jahr, Nominallohn, Inflationsrate) liegen in 'gehalt.json'.
Ein neues Jahr hinzufügen = eine JSON-Zeile. Diagramme, Tabelle und alle
Erklärtexte werden daraus automatisch generiert.

Aufruf:
    python3 gehalts-html.py
"""

import io
import json
import re

import matplotlib.pyplot as plt

JSON_FILE = "gehalt.json"
HTML_FILE = "gehaltsverhandlung_reallohn.html"

# ==========================================
# 1. DATEN LADEN
# ==========================================


def load_data(path):
    """Liest gehalt.json ein und validiert die Struktur."""
    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)

    if "jahre" not in data or not data["jahre"]:
        raise SystemExit(f"Fehler: '{path}' enthaelt keine 'jahre'-Liste.")
    if len(data["jahre"]) < 2:
        raise SystemExit("Fehler: mindestens zwei Jahre noetig.")

    jahre = []
    for eintrag in data["jahre"]:
        for feld in ("jahr", "nominallohn", "inflation"):
            if feld not in eintrag:
                raise SystemExit(f"Fehler: Eintrag {eintrag} ohne Feld '{feld}'.")
        jahr = int(eintrag["jahr"])
        nominallohn = float(eintrag["nominallohn"])
        inflation = float(eintrag["inflation"])
        prognose = bool(eintrag.get("prognose", False))
        if inflation < 0:
            raise SystemExit(f"Fehler: negative Inflationsrate fuer {jahr}.")
        jahre.append({
            "jahr": jahr,
            "nominallohn": nominallohn,
            "inflation": inflation,
            "prognose": prognose,
        })

    vorheriges = None
    for eintrag in jahre:
        if vorheriges is not None and eintrag["jahr"] <= vorheriges:
            raise SystemExit("Fehler: Jahre muessen strikt aufsteigend sein.")
        vorheriges = eintrag["jahr"]

    data["jahre"] = jahre
    return data

# ==========================================
# 2. BERECHNUNGEN
# ==========================================


def compute(jahre):
    """Berechnet alle abgeleiteten Kennzahlen aus den Jahresdaten."""
    jahr_labels = [str(e["jahr"]) for e in jahre]
    nominallohn = [e["nominallohn"] for e in jahre]
    inflation_jaehrlich = [e["inflation"] for e in jahre]
    prognose = [e["prognose"] for e in jahre]

    # Kumulierte Inflation (Zinseszins-Effekt), erstes Jahr = Basis (Faktor 1).
    kumulierte_inflation = [1.0]
    for infl in inflation_jaehrlich[1:]:
        kumulierte_inflation.append(kumulierte_inflation[-1] * (1 + infl))

    start_gehalt = nominallohn[0]
    reallohn = [nom / inf for nom, inf in zip(nominallohn, kumulierte_inflation)]
    reallohn_verlust = [real - start_gehalt for real in reallohn]
    notwendiges_gehalt = [start_gehalt * inf for inf in kumulierte_inflation]
    fehlbetrag = [nom - notwend for nom, notwend in zip(nominallohn, notwendiges_gehalt)]

    return {
        "jahr_labels": jahr_labels,
        "nominallohn": nominallohn,
        "inflation_jaehrlich": inflation_jaehrlich,
        "prognose": prognose,
        "kumulierte_inflation": kumulierte_inflation,
        "reallohn": reallohn,
        "reallohn_verlust": reallohn_verlust,
        "notwendiges_gehalt": notwendiges_gehalt,
        "fehlbetrag": fehlbetrag,
        "start_gehalt": start_gehalt,
    }


def erste_prognose_index(prognose):
    """Index des ersten Prognose-Jahres oder None."""
    for i, prog in enumerate(prognose):
        if prog:
            return i
    return None

# ==========================================
# 3. SVG-HILFSFUNKTION
# ==========================================


def clean_svg(svg_string, prefix, aria_label="Diagramm"):
    """Bereinigt matplotlib-SVG fuer valides HTML5-Inline-SVG."""
    svg = svg_string
    svg = re.sub(r'<\?xml[^?]*\?>\s*', '', svg)
    svg = re.sub(r'<!DOCTYPE[^>]*>\s*', '', svg)
    svg = re.sub(r'<metadata>.*?</metadata>\s*', '', svg, flags=re.DOTALL)
    svg = re.sub(r'\s+xmlns:xlink="[^"]*"', '', svg)
    svg = svg.replace('xlink:href', 'href')
    svg = re.sub(r'(<svg[^>]*)\s+width="[\d.]+pt"', r'\1', svg)
    svg = re.sub(r'(<svg[^>]*)\s+height="[\d.]+pt"', r'\1', svg)
    svg = re.sub(
        r'<svg ([^>]*)>',
        lambda m: f'<svg {m.group(1)} role="img" aria-label="{aria_label}">',
        svg,
        count=1,
    )
    svg = re.sub(r'\bid="([^"]+)"', lambda m: f'id="{prefix}_{m.group(1)}"', svg)
    svg = re.sub(r'href="#([^"]+)"', lambda m: f'href="#{prefix}_{m.group(1)}"', svg)
    svg = re.sub(r'url\(#([^)]+)\)', lambda m: f'url(#{prefix}_{m.group(1)})', svg)

    def round_coords(match):
        val = float(match.group(0))
        rounded = f"{val:.2f}"
        if '.' in rounded:
            rounded = rounded.rstrip('0').rstrip('.')
        return rounded

    svg = re.sub(r'-?\d+\.\d{3,}', round_coords, svg)
    return svg.strip()

# ==========================================
# 4. DIAGRAMME
# ==========================================


def _plot_linie(jahre, werte, prognose, **kwargs):
    """Zeichnet eine Serie; Prognose-Jahre gestrichelt."""
    p = erste_prognose_index(prognose)
    if p is None:
        plt.plot(jahre, werte, **kwargs)
        return
    solid_kwargs = dict(kwargs)
    solide_stop = p  # inklusiv letztes Ist-Jahr als Verbindung
    dashed_kwargs = dict(kwargs)
    dashed_kwargs["linestyle"] = "--"
    plt.plot(jahre[:solide_stop + 1], werte[:solide_stop + 1], **solid_kwargs)
    plt.plot(jahre[p - 1:p + 1], werte[p - 1:p + 1], **dashed_kwargs)
    plt.plot(jahre[p + 1:], werte[p + 1:], **dashed_kwargs)


def plot_nominal_vs_real(derived):
    jahre = derived["jahr_labels"]
    fig = plt.figure(figsize=(10, 6))
    _plot_linie(jahre, derived["nominallohn"], derived["prognose"],
                marker="o", linestyle="--", color="gray",
                label="Nominallohn (auf dem Papier)")
    _plot_linie(jahre, derived["reallohn"], derived["prognose"],
                marker="o", linestyle="-", color="red", linewidth=3,
                label="Reallohn (tatsaechliche Kaufkraft)")

    plt.fill_between(
        jahre, derived["reallohn"], derived["nominallohn"],
        color="red", alpha=0.1, label="Kaufkraftverlust durch Inflation",
    )
    plt.title("Gehaltsentwicklung: Nominallohn vs. Reallohn", fontsize=14, fontweight="bold")
    plt.ylabel("Gehalt in Euro", fontsize=12)
    lo, hi = min(derived["reallohn"]), max(derived["nominallohn"])
    plt.ylim(lo - 4000, hi + 2000)
    plt.grid(True, linestyle=":", alpha=0.7)
    plt.legend(loc="upper left")

    _buf = io.StringIO()
    plt.savefig(_buf, format="svg", bbox_inches="tight")
    plt.close(fig)
    return clean_svg(
        _buf.getvalue(), "p1",
        "Liniendiagramm: Nominallohn vs. Reallohn",
    )


def plot_reallohnverlust(derived):
    jahre = derived["jahr_labels"]
    verlust = derived["reallohn_verlust"]
    prognose = derived["prognose"]
    fig = plt.figure(figsize=(10, 4))

    colors = []
    hatches = []
    for val, prog in zip(verlust, prognose):
        colors.append("green" if val >= 0 else "darkred")
        hatches.append("//" if prog else None)

    bars = plt.bar(jahre, verlust, color=colors)
    for bar, hatch in zip(bars, hatches):
        if hatch:
            bar.set_hatch(hatch)
            bar.set_edgecolor("gray")

    plt.title(
        "Absoluter Reallohnverlust pro Jahr im Vergleich zum Einstieg",
        fontsize=14, fontweight="bold",
    )
    plt.ylabel("Verlust in Euro (Kaufkraft)", fontsize=12)
    plt.axhline(0, color="black", linewidth=1)

    for bar, val in zip(bars, verlust):
        yval = bar.get_height()
        offset = 150 if yval >= 0 else -400
        plt.text(
            bar.get_x() + bar.get_width() / 2, yval + offset,
            f"{int(round(val))} €", ha="center",
            va="bottom" if yval >= 0 else "top",
            fontweight="bold", color="black",
        )

    plt.ylim(min(verlust) - 1000, 1000)

    _buf = io.StringIO()
    plt.savefig(_buf, format="svg", bbox_inches="tight")
    plt.close(fig)
    return clean_svg(
        _buf.getvalue(), "p2",
        "Balkendiagramm: Absoluter Reallohnverlust pro Jahr",
    )


def plot_notwendiges_gehalt(derived):
    jahre = derived["jahr_labels"]
    fig = plt.figure(figsize=(10, 6))
    _plot_linie(jahre, derived["nominallohn"], derived["prognose"],
                marker="o", linestyle="--", color="gray",
                label="Tatsaechlicher Nominallohn")
    _plot_linie(jahre, derived["notwendiges_gehalt"], derived["prognose"],
                marker="o", linestyle="-", color="green", linewidth=3,
                label="Notwendiges Gehalt (Inflationsausgleich)")

    nominallohn = derived["nominallohn"]
    notwendig = derived["notwendiges_gehalt"]
    plt.fill_between(
        jahre, nominallohn, notwendig,
        where=[nom < notw for nom, notw in zip(nominallohn, notwendig)],
        color="red", alpha=0.15, label="Luecke (zu wenig Gehalt)",
    )
    plt.fill_between(
        jahre, nominallohn, notwendig,
        where=[nom >= notw for nom, notw in zip(nominallohn, notwendig)],
        color="green", alpha=0.15, label="Ueberschuss (Gehalt ueber Inflationsausgleich)",
    )

    for j, notw in zip(jahre, notwendig):
        plt.annotate(
            f"{int(round(notw))} €", xy=(j, notw), xytext=(0, 12),
            textcoords="offset points", ha="center", fontsize=9,
            color="green", fontweight="bold",
        )

    plt.title(
        "Notwendiges Gehalt zum Inflationsausgleich vs. tatsaechlicher Lohn",
        fontsize=14, fontweight="bold",
    )
    plt.ylabel("Gehalt in Euro", fontsize=12)
    hi = max(notwendig)
    plt.ylim(hi - 14000, hi + 2000)
    plt.grid(True, linestyle=":", alpha=0.7)
    plt.legend(loc="upper left")

    _buf = io.StringIO()
    plt.savefig(_buf, format="svg", bbox_inches="tight")
    plt.close(fig)
    return clean_svg(
        _buf.getvalue(), "p3",
        "Liniendiagramm: Notwendiges Gehalt zum Inflationsausgleich",
    )

# ==========================================
# 5. FLIESSTEXTE GENERIEREN
# ==========================================


def _fmt(zahl):
    """Zahl mit Tausenderpunkt und ohne Nachkommastellen."""
    return f"{int(round(zahl)):,}".replace(",", ".")


def build_narrative(derived):
    """Erzeugt die Erklärtexte datengetrieben."""
    nom = derived["nominallohn"]
    verlust = derived["reallohn_verlust"]
    notwendig = derived["notwendiges_gehalt"]
    jahre = derived["jahr_labels"]

    # Nullrunden detektieren (Jahre ohne Erhöhung gegenueber Vorjahr).
    # Prognose-Jahre ausklammern, da deren Lohn nur eine Annahme ist.
    nullrunden = [
        jahre[i] for i in range(1, len(nom))
        if nom[i] == nom[i - 1] and not derived["prognose"][i]
    ]

    if len(nullrunden) == 1:
        nullrunden_satz = (
            f"Besonders die Nullrunde im Jahr {nullrunden[0]} hat zu einem "
            "massiven Kaufkraftverlust geführt, der bis heute nicht ausgeglichen ist."
        )
    elif len(nullrunden) > 1:
        aufzaehlung = ", ".join(nullrunden[:-1]) + " und " + nullrunden[-1]
        nullrunden_satz = (
            f"Besonders die Nullrunden in den Jahren {aufzaehlung} haben zu "
            "massiven Kaufkraftverlusten geführt, die bis heute nicht ausgeglichen sind."
        )
    else:
        nullrunden_satz = ""

    # Groesster jährlicher Kaufkraftverlust.
    min_idx = verlust.index(min(verlust))
    min_jahr = jahre[min_idx]
    min_betrag = abs(verlust[min_idx])

    # Prognose-Hinweis.
    prognose_jahre = [j for j, p in zip(jahre, derived["prognose"]) if p]
    if prognose_jahre:
        prognose_satz = (
            f"Die Werte für {', '.join(p for p in prognose_jahre)} sind "
            "Annahmen/Prognosen (gestrichelt dargestellt)."
        )
    else:
        prognose_satz = ""

    return {
        "nullrunden_satz": nullrunden_satz,
        "min_jahr": min_jahr,
        "min_betrag": min_betrag,
        "prognose_satz": prognose_satz,
        "prognose_markierung": bool(prognose_jahre),
        "start_gehalt": derived["start_gehalt"],
        "erster_lohn": nom[0],
        "letzter_lohn": nom[-1],
        "letztes_jahr": jahre[-1],
        "letztes_notwendig": notwendig[-1],
        "letztes_nominell": nom[-1],
        "letzter_fehlbetrag": derived["fehlbetrag"][-1],
    }

# ==========================================
# 6. TABELLE + HTML
# ==========================================


def build_tabellen_zeilen(derived):
    zeilen = ""
    for jahr, nom, notwend, fehlt in zip(
        derived["jahr_labels"], derived["nominallohn"],
        derived["notwendiges_gehalt"], derived["fehlbetrag"],
    ):
        css_klasse = "positiv" if fehlt >= 0 else "negativ"
        pfeil = "+" if fehlt >= 0 else ""
        zeilen += (
            f"<tr>"
            f"<td>{jahr}</td>"
            f"<td>{_fmt(nom)} €</td>"
            f"<td>{_fmt(notwend)} €</td>"
            f'<td class="{css_klasse}">{pfeil}{_fmt(fehlt)} €</td>'
            f"</tr>\n"
        )
    return zeilen


def build_html(data, derived, narr, svg_plot1, svg_plot2, svg_plot3):
    tabellen_zeilen = build_tabellen_zeilen(derived)

    prognose_hinweis_html = ""
    if narr["prognose_markierung"]:
        prognose_hinweis_html = f'<p class="prognose-hinweis">{narr["prognose_satz"]}</p>'

    html_content = f"""<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Analyse der Reallohnentwicklung mit Inflationsausgleich und Kaufkraftverlust.">
    <title>Auswertung Gehaltsentwicklung</title>
    <link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2016%2016%22%3E%3Crect%20width%3D%2216%22%20height%3D%2216%22%20rx%3D%222%22%20fill%3D%22%232c3e50%22%2F%3E%3Crect%20x%3D%222%22%20y%3D%228%22%20width%3D%223%22%20height%3D%226%22%20fill%3D%22%23e74c3c%22%2F%3E%3Crect%20x%3D%226%22%20y%3D%225%22%20width%3D%223%22%20height%3D%229%22%20fill%3D%22%23f39c12%22%2F%3E%3Crect%20x%3D%2211%22%20y%3D%223%22%20width%3D%223%22%20height%3D%2211%22%20fill%3D%22%231a7a40%22%2F%3E%3C%2Fsvg%3E" type="image/svg+xml">
    <style>
        body {{
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
        }}
        .container {{
            max-width: 900px;
            margin: 0 auto;
            background: #fff;
            padding: 30px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            border-radius: 8px;
        }}
        h1 {{
            color: #2c3e50;
            text-align: center;
        }}
        h2 {{
            color: #e74c3c;
            border-bottom: 2px solid #eee;
            padding-bottom: 5px;
        }}
        .chart-container {{
            text-align: center;
            margin: 30px 0;
        }}
        .chart-container svg {{
            max-width: 100%;
            height: auto;
        }}
        .prognose-hinweis {{
            font-size: 0.85rem;
            color: #8a6d3b;
            background: #fcf8e3;
            border-left: 5px solid #f0ad4e;
            padding: 10px 15px;
            border-radius: 4px;
        }}
        .info-box {{
            background: #eef2f3;
            border-left: 5px solid #3498db;
            padding: 15px;
            margin-top: 20px;
            border-radius: 4px;
        }}
        .data-sources ul {{
            margin-top: 5px;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            font-size: 15px;
        }}
        th {{
            background-color: #2c3e50;
            color: white;
            padding: 10px 14px;
            text-align: right;
        }}
        th:first-child {{
            text-align: left;
        }}
        td {{
            padding: 9px 14px;
            border-bottom: 1px solid #ddd;
            text-align: right;
        }}
        td:first-child {{
            text-align: left;
            font-weight: bold;
        }}
        tr:nth-child(even) {{
            background-color: #f9f9f9;
        }}
        .positiv {{
            color: #1a7a40;
            font-weight: bold;
        }}
        .negativ {{
            color: #a93226;
            font-weight: bold;
        }}
        h2.gruen {{
            color: #1a7a40;
            border-bottom: 2px solid #eee;
            padding-bottom: 5px;
        }}
    </style>
</head>
<body>
    <main class="container">
        <h1>Analyse der Reallohnentwicklung</h1>

        <p>
            Diese Auswertung zeigt, dass das nominale Gehaltswachstum die Preissteigerungen
            der letzten Jahre nicht auffangen konnte. {narr["nullrunden_satz"]}
        </p>

        {prognose_hinweis_html}

        <div class="chart-container">
            {svg_plot1}
        </div>

        <p>
            Während der <b>Nominallohn (grau)</b> auf dem Papier scheinbar kontinuierlich gestiegen ist,
            zeigt der <b>Reallohn (rot)</b> die tatsächliche Kaufkraft. Die Schere zwischen beiden Linien
            öffnet sich immer weiter. Jeder Euro ist heute weniger wert als beim Start im ersten Jahr.
        </p>

        <h2>Der absolute Kaufkraftverlust</h2>

        <div class="chart-container">
            {svg_plot2}
        </div>

        <p>
            Im Jahr {narr["min_jahr"]} hatte das Gehalt durch die kumulierte Inflation der Vorjahre
            eine reale Kaufkraft, die knapp <b>{_fmt(narr["min_betrag"])} € unter dem Niveau des
            Einstiegsjahres</b> lag. Selbst mit den späteren Erhöhungen liegt der reale Wert des
            Gehalts noch deutlich im Minusbereich. Man arbeitet heute für effektiv weniger Kaufkraft
            als am ersten Tag.
        </p>

        <h2 class="gruen">Notwendiges Gehalt zum Inflationsausgleich</h2>

        <p>
            Das folgende Diagramm zeigt, wie hoch der Nominallohn jedes Jahr hätte sein müssen,
            um die Kaufkraft des Einstiegsjahres exakt zu erhalten. Die <b>grüne Linie</b> ist die
            Ziellinie &mdash; der tatsächliche Lohn (grau) bleibt durchgehend darunter.
        </p>

        <div class="chart-container">
            {svg_plot3}
        </div>

        <table>
            <thead>
                <tr>
                    <th>Jahr</th>
                    <th>Tatsächlicher Lohn</th>
                    <th>Notwendiges Gehalt</th>
                    <th>Differenz</th>
                </tr>
            </thead>
            <tbody>
                {tabellen_zeilen}
            </tbody>
        </table>

        <p style="margin-top: 15px;">
            Eine negative Differenz bedeutet: Das Gehalt liegt unter dem Wert, der zum vollständigen
            Ausgleich der Inflation seit dem Einstiegsjahr nötig wäre. Für {narr["letztes_jahr"]} müsste
            das Gehalt <b>{_fmt(narr["letztes_notwendig"])} €</b> betragen &mdash; tatsächlich sind es
            nur {_fmt(narr["letztes_nominell"])} €.
        </p>

        <div class="info-box data-sources">
            <h3>Quellen und Berechnungsgrundlagen</h3>
            <ul>
                <li><b>Basisgehalt:</b> Nominallöhne laut eigenen Unterlagen/Verträgen.
                    {data.get("praemie_hinweis", "")}</li>
                <li><b>Inflation:</b> {data.get("inflation_quelle", "VPI, Destatis")};
                    kumuliert ab dem ersten Jahr betrachtet (Zinseszins-Effekt).</li>
                <li><b>Methodik:</b> Der Reallohn entspricht dem Nominallohn dividiert durch den
                    kumulierten Inflationsfaktor des jeweiligen Jahres.</li>
            </ul>
        </div>
    </main>
</body>
</html>
"""
    return html_content

# ==========================================
# 7. HAUPTABLAUF
# ==========================================


def main():
    data = load_data(JSON_FILE)
    derived = compute(data["jahre"])
    narr = build_narrative(derived)

    svg_plot1 = plot_nominal_vs_real(derived)
    svg_plot2 = plot_reallohnverlust(derived)
    svg_plot3 = plot_notwendiges_gehalt(derived)

    html_content = build_html(data, derived, narr, svg_plot1, svg_plot2, svg_plot3)

    with open(HTML_FILE, "w", encoding="utf-8") as f:
        f.write(html_content)

    print(f"Erfolgreich! '{HTML_FILE}' wurde erstellt.")


if __name__ == "__main__":
    main()