#!/usr/bin/env python3
"""
as_chart_style.py — Konsistenter Chart-Style für Autismus-Stiftung

Stand 2026-05-01 · Sibling zu as_pdf_brand.py · brand-context §11 + §15c

USAGE
-----

from as_chart_style import AS_PALETTE, apply_style, save_brand_chart
import matplotlib.pyplot as plt

apply_style()

fig, ax = plt.subplots()
ax.bar([1,2,3], [10,20,30], color=AS_PALETTE['magenta'])
save_brand_chart(fig, 'mein-chart.png', title='Spenden 2025')

OUTPUT
------

PNG mit:
- Magenta-Akzent (#d92d68) für primäre Datenreihe
- Navy-Deep (#060C2D) für Achsen + Beschriftungen
- Roboto als Schriftart (oder DejaVu Sans als Fallback)
- Magenta-Stripe (4 px) am unteren Rand als Brand-Hint
- Optional Stiftungs-Bildmarke unten rechts (wenn AS_LOGO_PATH gesetzt)
- Default 1200×800 px @ 150 dpi

KEINE Header, KEIN Logo oben — nur dezenter Brand-Hinweis am Rand.
"""
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.font_manager import FontProperties

# ============================================================
# BRAND-PALETTE — synchron mit tokens.css §11
# ============================================================

AS_PALETTE = {
    # Primär
    'magenta':          '#d92d68',
    'magenta_dark':     '#b01f52',
    'magenta_light':    '#fdeef4',
    'magenta_xlight':   '#fef6f9',
    # Navy
    'navy_deep':        '#060C2D',
    'navy_mid':         '#0C1648',
    # Neutral
    'creme':            '#F5F0E8',
    'gray_line':        '#ebebeb',
    'gray_bg':          '#f8f8f8',
    'gray_muted':       '#7C7C7C',
    'text':             '#515151',
    'heading':          '#1A1A1A',
    'ink':              '#231f20',
    'white':            '#ffffff',
    # Persona-Tints (für Personae-Charts)
    'johanna':          '#efe6f0',
    'lisa':             '#fdeef4',
    'peter':            '#f0ede6',
}

# Reihenfolge für Multi-Series-Charts (Stacked-Bars, Line-Charts)
AS_SERIES_ORDER = [
    AS_PALETTE['magenta'],
    AS_PALETTE['navy_deep'],
    AS_PALETTE['magenta_dark'],
    AS_PALETTE['navy_mid'],
    AS_PALETTE['gray_muted'],
    AS_PALETTE['creme'],
]

# Pfad zur SVG-Bildmarke (für optionale Footer-Insertion). Wenn None, wird kein Logo eingefügt.
AS_LOGO_PATH = None  # Setze auf '/path/to/AutismusStiftung_Logo_standalone.png'


# ============================================================
# STYLE-FUNKTION — vor Plot aufrufen
# ============================================================

def apply_style():
    """
    Setzt matplotlib rcParams auf Stiftungs-Standard.
    Vor jedem Chart aufrufen.
    """
    matplotlib.rcParams.update({
        # Font
        'font.family': 'sans-serif',
        'font.sans-serif': ['Roboto', 'DejaVu Sans', 'Arial', 'sans-serif'],
        'font.size': 11,
        'font.weight': 'normal',

        # Title + Labels
        'axes.titlesize': 14,
        'axes.titleweight': 'bold',
        'axes.titlecolor': AS_PALETTE['heading'],
        'axes.titlepad': 16,
        'axes.labelsize': 10,
        'axes.labelweight': 'normal',
        'axes.labelcolor': AS_PALETTE['text'],

        # Axes
        'axes.facecolor': AS_PALETTE['white'],
        'axes.edgecolor': AS_PALETTE['gray_line'],
        'axes.linewidth': 1.0,
        'axes.spines.top': False,
        'axes.spines.right': False,
        'axes.grid': True,
        'axes.axisbelow': True,

        # Grid
        'grid.color': AS_PALETTE['gray_line'],
        'grid.linewidth': 0.6,
        'grid.linestyle': '-',
        'grid.alpha': 0.6,

        # Ticks
        'xtick.color': AS_PALETTE['text'],
        'ytick.color': AS_PALETTE['text'],
        'xtick.labelsize': 9,
        'ytick.labelsize': 9,
        'xtick.major.size': 0,
        'ytick.major.size': 0,

        # Legend
        'legend.frameon': False,
        'legend.fontsize': 9,
        'legend.labelcolor': AS_PALETTE['text'],

        # Figure
        'figure.facecolor': AS_PALETTE['white'],
        'figure.dpi': 150,
        'figure.figsize': (8, 5.33),
        'figure.constrained_layout.use': True,

        # Color cycle — Stiftungs-Reihenfolge
        'axes.prop_cycle': matplotlib.cycler(color=AS_SERIES_ORDER),

        # PDF-Output
        'pdf.fonttype': 42,
        'svg.fonttype': 'path',
    })


# ============================================================
# BRAND-FOOTER-STRIPE
# ============================================================

def add_brand_stripe(fig, color=None, height_pct=0.012):
    """
    Magenta-Streifen am unteren Rand der Figur.
    Brand-Hint, ohne den Plot-Inhalt zu stören.
    """
    color = color or AS_PALETTE['magenta']
    # Rechteck am unteren Rand
    rect = mpatches.Rectangle(
        (0, 0), 1, height_pct,
        transform=fig.transFigure,
        facecolor=color,
        edgecolor='none',
        zorder=1000,
    )
    fig.patches.append(rect)


def add_brand_footer_text(fig, text='Autismus-Stiftung Kassel · autismusstiftung.de', y=0.02):
    """
    Kleine Brand-Zeile als Footer-Text (Roboto 7pt, grau).
    """
    fig.text(
        0.5, y, text,
        ha='center', va='bottom',
        fontsize=7, color=AS_PALETTE['gray_muted'],
        family='sans-serif',
    )


# ============================================================
# SAVE-FUNKTION
# ============================================================

def save_brand_chart(fig, filename, title=None, footer_text='Autismus-Stiftung Kassel · autismusstiftung.de',
                     dpi=150, brand_stripe=True, format=None):
    """
    Speichert Chart mit Brand-Stripe + optionaler Footer-Zeile.

    Parameters
    ----------
    fig : matplotlib.figure.Figure
        Die Figur, die gespeichert werden soll.
    filename : str
        Output-Pfad (PNG, PDF, SVG werden anhand der Endung erkannt).
    title : str, optional
        Wenn gesetzt, wird er als suptitle gesetzt (überschreibt vorhandene).
    footer_text : str
        Brand-Zeile am unteren Rand. Auf '' setzen, um zu unterdrücken.
    dpi : int
        Standard 150 dpi.
    brand_stripe : bool
        Magenta-Streifen am unteren Rand. Default True.
    format : str, optional
        Falls die Endung nicht aussagekräftig ist (z.B. bei stdout-Output).
    """
    if title:
        fig.suptitle(title, fontsize=15, fontweight='bold', color=AS_PALETTE['heading'], y=0.98)

    if brand_stripe:
        add_brand_stripe(fig)

    if footer_text:
        add_brand_footer_text(fig, footer_text)

    # Padding unten erhöhen, damit Footer-Text Platz hat
    fig.subplots_adjust(bottom=0.12)

    fig.savefig(filename, dpi=dpi, format=format, bbox_inches='tight', pad_inches=0.3,
                facecolor=AS_PALETTE['white'])


# ============================================================
# DEMO — wenn das Skript direkt aufgerufen wird
# ============================================================

if __name__ == '__main__':
    import sys
    apply_style()

    # Demo 1 — Bar-Chart
    fig, ax = plt.subplots(figsize=(10, 6))
    categories = ['Einmal-\nspende', 'Dauer-\nspende', 'Förder-\nmitglied', 'Zustift-\nung']
    values = [4200, 3800, 1200, 25000]
    ax.bar(categories, values, color=AS_PALETTE['magenta'])
    ax.set_ylabel('Betrag in EUR')
    ax.set_title('Spenden-Modelle nach Volumen 2025 (Beispiel)')
    save_brand_chart(fig, '/tmp/demo-bar.png',
                     title='Spenden-Modelle nach Volumen 2025')
    print('Demo Bar-Chart: /tmp/demo-bar.png')

    # Demo 2 — Line-Chart mit zwei Serien
    fig, ax = plt.subplots(figsize=(10, 6))
    months = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez']
    spenden = [320, 280, 410, 850, 380, 310, 290, 250, 480, 720, 1100, 1850]
    fördermitglieder = [10, 12, 15, 22, 23, 25, 28, 30, 35, 42, 50, 65]
    ax2 = ax.twinx()
    l1, = ax.plot(months, spenden, color=AS_PALETTE['magenta'], linewidth=2.5, marker='o', label='Spenden EUR')
    l2, = ax2.plot(months, fördermitglieder, color=AS_PALETTE['navy_deep'], linewidth=2.5, marker='s', label='Fördermitglieder')
    ax.set_ylabel('Spenden EUR', color=AS_PALETTE['magenta'])
    ax2.set_ylabel('Fördermitglieder kumuliert', color=AS_PALETTE['navy_deep'])
    ax.legend(handles=[l1, l2], loc='upper left')
    ax2.spines['right'].set_visible(True)
    ax2.spines['right'].set_color(AS_PALETTE['gray_line'])
    save_brand_chart(fig, '/tmp/demo-line.png',
                     title='Wachstum 2025 — Spenden + Fördermitgliedschaften')
    print('Demo Line-Chart: /tmp/demo-line.png')

    # Demo 3 — Pie-Chart mit Persona-Verteilung
    fig, ax = plt.subplots(figsize=(8, 8))
    sizes = [40, 35, 25]
    labels = ['Johanna\n(Vorsorge-Beraterin)', 'Lisa\n(Eltern, digital)', 'Peter\n(Großvater, Vermögen)']
    colors_personas = [AS_PALETTE['johanna'], AS_PALETTE['lisa'], AS_PALETTE['peter']]
    wedges, texts, autotexts = ax.pie(sizes, labels=labels, colors=colors_personas,
                                       autopct='%1.0f%%', startangle=90, textprops={'fontsize': 10})
    for autotext in autotexts:
        autotext.set_color(AS_PALETTE['heading'])
        autotext.set_weight('bold')
    save_brand_chart(fig, '/tmp/demo-pie.png',
                     title='Newsletter-Subscriber nach Persona (Beispiel)')
    print('Demo Pie-Chart: /tmp/demo-pie.png')

    print('\n3 Demo-Charts erstellt in /tmp/.')
    print('Sichtprüfung: Magenta-Stripe am unteren Rand, Roboto-Font, Footer-Zeile.')