"""Analyze the fictional line-extension scenarios. Python 3.9, standard library."""
import argparse
import csv
import json
from decimal import Decimal
from pathlib import Path

FIELDS = ("base_units", "switch_units", "new_units", "core_contribution",
          "new_contribution", "core_hours", "new_hours", "setup_cost", "capacity_hours")


def calculate(row):
    values = {key: Decimal(row[key]) for key in FIELDS}
    if any(not value.is_finite() or value < 0 for value in values.values()):
        raise ValueError("Inputs must be finite and non-negative")
    base, switched, new = (values[key] for key in ("base_units", "switch_units", "new_units"))
    if any(value != value.to_integral_value() for value in (base, switched, new)):
        raise ValueError("Unit counts must be integers")
    if switched > min(base, new):
        raise ValueError("Switching cannot exceed existing demand or new sales")
    demand = base - switched
    raw_planned = row.get("core_units_planned", "")
    planned = Decimal(raw_planned) if raw_planned.strip() else demand
    if not planned.is_finite() or planned < 0 or planned > demand:
        raise ValueError("Planned Core units must lie within remaining demand")
    if planned != planned.to_integral_value():
        raise ValueError("Planned Core units must be integers")
    hours = planned * values["core_hours"] + new * values["new_hours"]
    contribution = planned * values["core_contribution"] + new * values["new_contribution"]
    result = contribution - values["setup_cost"]
    baseline = base * values["core_contribution"]
    return {
        "core_demand": demand, "core_planned": planned,
        "unmet_core": demand - planned, "new_units": new,
        "total_units": planned + new,
        "hours": hours, "capacity": values["capacity_hours"],
        "feasible_hours": hours <= values["capacity_hours"],
        "contribution_before_launch": contribution,
        "result_after_launch": result, "delta_to_baseline": result - baseline,
    }


def read_rows(path):
    with Path(path).open(encoding="utf-8-sig", newline="") as handle:
        rows = list(csv.DictReader(handle, delimiter=";"))
    identifiers = [row["scenario_id"] for row in rows]
    if not rows or len(identifiers) != len(set(identifiers)):
        raise ValueError("Empty dataset or duplicate scenario ID")
    return rows


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--csv", type=Path, default=Path(__file__).with_name("scenarios.csv"))
    args = parser.parse_args()
    result = {row["scenario_id"]: calculate(row) for row in read_rows(args.csv)}
    print(json.dumps(result, ensure_ascii=False, indent=2,
                     default=lambda value: str(value) if isinstance(value, Decimal) else value))


if __name__ == "__main__":
    main()

