
import json
from datetime import datetime
from pathlib import Path

SRC = Path("data/betrieb_ein_ausgaben.json")
OUT = Path("data/exchange/betrieb_ausgaben.json")

YEARS = [2026, 2027, 2028]

def parse_date(s):
    try:
        return datetime.strptime(s, "%Y-%m-%d")
    except:
        return None

def to_float(x):
    try:
        return float(str(x).replace(",", "."))
    except:
        return 0.0

def month_keys():
    return [f"{y}-{m:02d}" for y in YEARS for m in range(1, 13)]

def occurs(turnus, start, year, month):
    if turnus == "monatlich":
        return True
    if turnus == "jaehrlich" and start:
        return start.month == month
    if turnus == "halbjaehrlich" and start:
        diff = (year - start.year) * 12 + (month - start.month)
        return diff >= 0 and diff % 6 == 0
    if turnus == "vierteljaehrlich" and start:
        diff = (year - start.year) * 12 + (month - start.month)
        return diff >= 0 and diff % 3 == 0
    if turnus == "einmalig" and start:
        return start.year == year and start.month == month
    return False

def active(zeitf, start, year, month):
    if not start:
        return True
    if zeitf == "ab":
        return (year, month) >= (start.year, start.month)
    if zeitf == "bis":
        return (year, month) <= (start.year, start.month)
    if zeitf == "einmalig":
        return True
    return True

def main():
    result = {k:0.0 for k in month_keys()}
    if not SRC.exists():
        OUT.write_text(json.dumps(result, indent=2))
        return

    data = json.loads(SRC.read_text())

    for e in data:
        if (e.get("typ") or "").strip() != "Betrieb Ausgabe":
            continue

        betrag = to_float(e.get("betrag"))
        turnus = (e.get("turnus") or "").lower()
        zeitf  = (e.get("zeitfilter") or "").lower()
        start  = parse_date(e.get("gueltig_datum"))

        for y in YEARS:
            for m in range(1, 13):
                key = f"{y}-{m:02d}"
                if not active(zeitf, start, y, m):
                    continue
                if occurs(turnus, start, y, m):
                    result[key] += betrag

    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps({k:round(v,2) for k,v in result.items()}, indent=2))
    print("Betriebsausgaben komplett neu berechnet.")

if __name__ == "__main__":
    main()
