#!/usr/bin/env python3
"""Offline scenario calculator. Rates are inputs, never live vendor prices."""
import json
import sys
from decimal import Decimal
from decimal import InvalidOperation

def amount(value):
    if isinstance(value, bool) or not isinstance(value, (int, float, str)):
        raise ValueError("expected a nonnegative numeric input")
    number = Decimal(str(value))
    if not number.is_finite() or number < 0:
        raise ValueError("expected a finite nonnegative input")
    return number

def annual(option):
    units = option["monthlyUnits"]
    rates = option["unitRates"]
    if set(units) != set(rates):
        raise ValueError("every usage unit needs exactly one matching rate")
    recurring = sum(amount(units[k]) * amount(rates[k]) for k in units)
    recurring += amount(option["monthlyInfrastructure"])
    recurring += amount(option["monthlyLaborHours"]) * amount(option["hourlyLabor"])
    return recurring * 12 + amount(option["oneTimeMigration"])

def main():
    source = json.load(open(sys.argv[1], encoding="utf-8"))
    if source["currency"] != "USD":
        raise ValueError("convert both quotes into USD before comparison")
    before, after = annual(source["baseline"]), annual(source["candidate"])
    print(json.dumps({"scenario": source["scenario"], "synthetic": source["synthetic"],
      "baselineYearOneUSD": str(before), "candidateYearOneUSD": str(after),
      "modeledDifferenceUSD": str(before-after),
      "coverageAccepted": source.get("coverageAccepted") is True,
      "decision": "review coverage and actual quotes before purchasing"}, indent=2))

if __name__ == "__main__":
    try:
        main()
    except (ValueError, InvalidOperation, TypeError, KeyError, IndexError, OSError) as error:
        print(type(error).__name__ + ": " + str(error), file=sys.stderr)
        sys.exit(2)
