#!/usr/bin/env python3
import json, matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.edgecolor':'#cfd8db',
                     'axes.grid':True,'grid.color':'#eef2f3','grid.linewidth':.8})
PET='#037493'; RED='#c0392b'; GRN='#1e8449'; ORA='#e08a1e'; GREY='#8aa0a8'
d=json.load(open("deep.json"))
prog=d['prog']; B=prog['basis']; R=prog['repr']
labels={'Material':'Material','Labor':'Labor','Manufacturing':'Manufacturing',
        'ScrapB':'Scrap','SGA':'SG&A','Profit':'Profit'}
order=['Material','Labor','Manufacturing','ScrapB','SGA','Profit']

# 1) Cost structure grouped bar with % share
fig,ax=plt.subplots(figsize=(8.6,4.2))
import numpy as np
x=np.arange(len(order)); w=0.38
b=[B[k] for k in order]; r=[R[k] for k in order]
ax.bar(x-w/2,b,w,label='Basis (24Q4)',color=GREY)
ax.bar(x+w/2,r,w,label='RePricing (26Q1)',color=PET)
for i,k in enumerate(order):
    ax.text(i-w/2,b[i]+2,f"{B['_pct'][k]:.0f}%",ha='center',fontsize=8,color='#555')
    ax.text(i+w/2,r[i]+2,f"{R['_pct'][k]:.0f}%",ha='center',fontsize=8,color=PET,fontweight='bold')
ax.set_xticks(x); ax.set_xticklabels([labels[k] for k in order])
ax.set_ylabel('€ je Fahrzeugsatz (Σ aller Positionen)')
ax.set_title('Kostenstruktur Basis vs RePricing  (Sales: 380 € → 500 €, +31,5 %)',fontweight='bold')
ax.legend(frameon=False)
plt.tight_layout(); plt.savefig('c1_kostenstruktur.png',dpi=140); plt.close()

# 2) Waterfall from basis Sales to repr Sales by bucket delta
fig,ax=plt.subplots(figsize=(8.6,4.2))
start=B['Sales']; cum=start; xs=[]; lab=['Basis\nSales']; vals=[start]
ax.bar(0,start,color=GREY); xs.append(0)
i=1
for k in order:
    dlt=R[k]-B[k]
    col=RED if dlt>0 else GRN
    ax.bar(i,dlt,bottom=cum,color=col)
    ax.text(i,cum+dlt+ (4 if dlt>0 else -8),f"{dlt:+.0f}",ha='center',fontsize=8,color=col,fontweight='bold')
    cum+=dlt; lab.append(labels[k]); i+=1
ax.bar(i,cum,color=PET); lab.append('RePricing\nSales')
ax.set_xticks(range(i+1)); ax.set_xticklabels(lab,fontsize=8)
ax.set_ylabel('€ je Fahrzeugsatz')
ax.set_title('Woher der Preisanstieg kommt (+120 € / Satz)',fontweight='bold')
plt.tight_layout(); plt.savefig('c2_waterfall.png',dpi=140); plt.close()

# 3) Top movers by delta € per set
st=d['sales_by_tab']
mv=sorted(st.items(),key=lambda kv:(kv[1]['r']-kv[1]['b']),reverse=True)[:12]
fig,ax=plt.subplots(figsize=(8.6,4.6))
names=[f"{t}  {v['part'][:18]}" for t,v in mv][::-1]
delt=[v['r']-v['b'] for t,v in mv][::-1]
ax.barh(names,delt,color=PET)
for i,val in enumerate(delt): ax.text(val+0.1,i,f"+{val:.1f} €",va='center',fontsize=8,color=RED)
ax.set_xlabel('Δ Angebotspreis € / Satz'); ax.set_title('Top 12 Preistreiber (absolut)',fontweight='bold')
plt.tight_layout(); plt.savefig('c3_topmover.png',dpi=140); plt.close()

# 4) Production drivers: what changed vs not
fig,(a1,a2)=plt.subplots(1,2,figsize=(8.6,3.8))
cats=['Maschinen-\nstundensatz','Ineffizienz\n(Lohn)','Scrap je\nProzess-Schritt']
basev=[1.0,0.0,2.0]; reprv=[2.95,0.55,3.0]   # machine as factor x, ineff %, scrap %
# normalize display: machine as x-factor, others as %
a1.bar([0],[111],0.5,color=GREY,label='Basis'); a1.bar([0.55],[327.45],0.5,color=PET,label='RePr')
a1.set_xticks([0.27]); a1.set_xticklabels(['Maschinen-Std.satz €/h']); a1.set_ylabel('€/h')
a1.set_title('Maschine: 111 → 327 €/h (+195 %)',fontsize=10,fontweight='bold'); a1.legend(frameon=False,fontsize=8)
labels2=['Ineffizienz\n(Lohn) %','Scrap/Step %','Cycle time','# Mitarbeiter']
bb=[0,2,100,100]; rr=[55,3,100,100]
xx=np.arange(4); a2.bar(xx-0.19,bb,0.38,color=GREY); a2.bar(xx+0.19,rr,0.38,color=PET)
a2.set_xticks(xx); a2.set_xticklabels(labels2,fontsize=8)
a2.set_title('Cycle/ #MA unverändert · Ineff+Scrap rauf',fontsize=10,fontweight='bold')
a2.text(2.5,55,'Cycle & #MA:\nIndex 100 = gleich',fontsize=7,color=GREY,ha='center')
plt.tight_layout(); plt.savefig('c4_produktion.png',dpi=140); plt.close()

# 5) Annual impact
yrs=d['years']; vol=d['volume']; ann=[a/1e6 for a in d['annual']]
fig,ax=plt.subplots(figsize=(8.6,4.2))
ax.bar([str(y) for y in yrs],ann,color=PET,label='Mehrkosten / Jahr')
ax2=ax.twinx()
cum=np.cumsum(ann); ax2.plot([str(y) for y in yrs],cum,color=RED,marker='o',label='kumuliert')
for i,c in enumerate(cum): ax2.text(i,c+3,f"{c:.0f}",fontsize=7,color=RED,ha='center')
ax.set_ylabel('Mehrkosten / Jahr [M€]'); ax2.set_ylabel('kumuliert [M€]',color=RED)
ax.set_title('Jahres-Mehrkosten (Δ 120 €/Satz × Volumen) — Obergrenze ~186 M€',fontweight='bold')
ax.grid(False)
plt.tight_layout(); plt.savefig('c5_jahre.png',dpi=140); plt.close()
print("charts written: c1..c5")
