#!/usr/bin/env python3
"""MSC-P-024 reference calculation. MIT licensed; standard library only."""

from __future__ import annotations

import csv
from pathlib import Path


DATA = Path(__file__).resolve().parents[1] / "datasets" / "msc-p024-price-volume-margin.csv"


def main() -> None:
    rows = list(csv.DictReader(DATA.open(encoding="utf-8", newline="")))
    if len(rows) != 1:
        raise ValueError("reference dataset must contain exactly one scenario")
    row = rows[0]
    p0 = float(row["baseline_price"])
    q0 = float(row["baseline_volume"])
    vc = float(row["variable_cost"])
    delta_p = float(row["price_change"])
    elasticity = float(row["elasticity"])
    delta_fc = float(row["fixed_cost_change"])
    if not (p0 > vc >= 0 and q0 > 0 and delta_p > -1):
        raise ValueError("price, cost, volume or price change outside the declared support")

    p1 = p0 * (1 + delta_p)
    q1 = q0 * (1 + delta_p) ** elasticity
    contribution_0 = (p0 - vc) * q0
    contribution_1 = (p1 - vc) * q1
    delta_profit = contribution_1 - contribution_0 - delta_fc
    break_even_volume = (contribution_0 + delta_fc) / (p1 - vc)
    max_fixed_cost_change = contribution_1 - contribution_0

    print(f"scenario={row['scenario']}")
    print(f"new_price={p1:.6f}")
    print(f"new_volume={q1:.6f}")
    print(f"baseline_contribution={contribution_0:.6f}")
    print(f"scenario_contribution={contribution_1:.6f}")
    print(f"incremental_profit={delta_profit:.6f}")
    print(f"incremental_profit_pct={100 * delta_profit / contribution_0:.6f}")
    print(f"break_even_volume={break_even_volume:.6f}")
    print(f"max_fixed_cost_change={max_fixed_cost_change:.6f}")


if __name__ == "__main__":
    main()

