#!/usr/bin/env python3
"""Sum a hypothetical upgrade work ledger; preserve unpriced lines as unknown."""
import csv, json
from decimal import Decimal
from pathlib import Path
from argparse import ArgumentParser

def calculate(path, reserve_hours=Decimal("16"), reserve_rate=Decimal("120")):
    known = Decimal("0")
    unknown = []
    hours = {}
    with Path(path).open(newline="", encoding="utf-8") as stream:
        for row in csv.DictReader(stream):
            if not row["assumed_hours"] or not row["assumed_hourly_eur"]:
                unknown.append(row["workstream"])
                continue
            h, rate = Decimal(row["assumed_hours"]), Decimal(row["assumed_hourly_eur"])
            if not h.is_finite() or not rate.is_finite() or h < 0 or rate < 0:
                raise ValueError("Hours/rate must be finite nonnegative values")
            known += h * rate
            owner = row["delivery_owner"]
            hours[owner] = hours.get(owner, Decimal(0)) + h
    if reserve_hours < 0 or reserve_rate < 0 or not reserve_hours.is_finite() or not reserve_rate.is_finite():
        raise ValueError("Reserve inputs must be finite nonnegative values")
    reserve = reserve_hours * reserve_rate
    return {"synthetic_only": True, "currency": "EUR", "hours_by_owner": {k:str(v) for k,v in hours.items()},
            "known_work_subtotal": str(known), "conditional_reserve": str(reserve),
            "known_work_ceiling_with_reserve": str(known+reserve), "unpriced_lines": unknown,
            "complete_project_quote": False,
            "note": "All rates/hours are hypothetical. Reserve requires separate authorization. Unpriced lines, taxes and other exclusions remain outside these sums."}

if __name__ == "__main__":
    p=ArgumentParser(description=__doc__)
    p.add_argument("ledger", nargs="?", default=str(Path(__file__).with_name("scope-budget.csv")))
    p.add_argument("--reserve-hours", type=Decimal, default=Decimal("16"))
    p.add_argument("--reserve-rate", type=Decimal, default=Decimal("120"))
    a=p.parse_args()
    print(json.dumps(calculate(a.ledger,a.reserve_hours,a.reserve_rate),indent=2))
