import csv, sys
FILE = sys.argv[1]
MAT_ABS, MAT_PCT, PCT_FLOOR = 15000, 0.10, 5000   # material: >= 15k, or >= 10% and >= 5k
rows = list(csv.DictReader(open(FILE, encoding="utf-8")))
COLS = ["month_actual", "month_prior_year", "month_budget", "ytd_actual", "ytd_prior_year", "ytd_budget"]

def total(col, groups):
    return sum(float(r[col]) for r in rows if r["group"] in groups)

for c in COLS:  # subtotals computed here, never by the assistant
    rev = total(c, {"income"})
    gm = rev - total(c, {"cogs"})
    ebitda = gm - total(c, {"opex"})
    pbt = ebitda - total(c, {"below_ebitda"})
    print(f"{c}: revenue {rev:,.0f} | gross margin {gm:,.0f} ({gm/rev:.1%}) | EBITDA {ebitda:,.0f} ({ebitda/rev:.1%}) | PBT {pbt:,.0f}")

def var(r, a, b):
    d = float(r[a]) - float(r[b])
    fav = d if r["group"] == "income" else -d       # > 0 favourable, < 0 unfavourable
    return d, (d / float(r[b]) if float(r[b]) else None), "F" if fav > 0 else "U" if fav < 0 else "="

print("line | YTD vs budget | % | F/U | YTD vs prior year | % | F/U | material vs budget")
for r in rows:
    d, p, f = var(r, "ytd_actual", "ytd_budget")
    d2, p2, f2 = var(r, "ytd_actual", "ytd_prior_year")
    mat = abs(d) >= MAT_ABS or (p is not None and abs(p) >= MAT_PCT and abs(d) >= PCT_FLOOR)
    print(f"{r['line']} | {d:+,.0f} | {p:+.1%} | {f} | {d2:+,.0f} | {p2:+.1%} | {f2} | {'yes' if mat else 'no'}")

# EBITDA bridge, YTD actual vs budget: material lines + the rest, ties to the total
ebitda_lines = [r for r in rows if r["group"] != "below_ebitda"]
bridge, rest = [], 0.0
for r in ebitda_lines:
    d, p, f = var(r, "ytd_actual", "ytd_budget")
    impact = d if r["group"] == "income" else -d
    mat = abs(d) >= MAT_ABS or (p is not None and abs(p) >= MAT_PCT and abs(d) >= PCT_FLOOR)
    if mat: bridge.append((r["line"], impact))
    else: rest += impact
e_bud = total("ytd_budget", {"income"}) - total("ytd_budget", {"cogs", "opex"})
e_act = total("ytd_actual", {"income"}) - total("ytd_actual", {"cogs", "opex"})
assert abs(e_bud + sum(i for _, i in bridge) + rest - e_act) < 0.01
print(f"EBITDA bridge YTD: budget {e_bud:,.0f}")
for l, i in bridge: print(f"  {l}: {i:+,.0f}")
print(f"  other lines: {rest:+,.0f}\n  actual {e_act:,.0f}")
