"""Check the fixed fictional example and meaningful boundaries. Python 3.9."""
import json
import sys
from decimal import Decimal as D
from pathlib import Path
from analyze import calculate, read_rows


def check(condition, message):
    if not condition:
        raise AssertionError(message)


def main():
    rows = read_rows(Path(__file__).with_name("scenarios.csv"))
    by_id = {row["scenario_id"]: row for row in rows}
    expected = {
        "base": ("800", "800", "560000", "0", "0", True),
        "A": ("600", "1000", "600000", "40000", "0", True),
        "B_full": ("650", "1250", "715000", "155000", "0", False),
        "B_limited_core": ("400", "1000", "540000", "-20000", "250", True),
    }
    check(set(by_id) == set(expected), "Unexpected fixed scenario IDs")
    output = {}
    for name, targets in expected.items():
        row = by_id[name]
        result = calculate(row)
        actual = (result["core_planned"], result["hours"],
                  result["result_after_launch"], result["delta_to_baseline"],
                  result["unmet_core"], result["feasible_hours"])
        target = tuple(D(value) for value in targets[:5]) + (targets[5],)
        check(actual == target, "Fixed example mismatch: " + name)
        # Independent incremental route: new contribution minus foregone Core contribution and launch cost.
        foregone = D(row["base_units"]) - result["core_planned"]
        independent_delta = (D(row["new_units"]) * D(row["new_contribution"])
                             - foregone * D(row["core_contribution"]) - D(row["setup_cost"]))
        check(independent_delta == result["delta_to_baseline"], "Incremental reconciliation failed")
        output[name] = {"hours": str(result["hours"]),
                        "result": str(result["result_after_launch"]),
                        "feasible_hours": result["feasible_hours"]}
    changed = dict(by_id["A"], switch_units="260")
    changed_result = calculate(changed)
    check(changed_result["result_after_launch"] == D("558000"), "Changed switching result")
    check(changed_result["hours"] == D("940"), "Changed switching hours")
    check(changed_result["delta_to_baseline"] == D("-2000"), "Changed switching delta")
    check(calculate(dict(by_id["A"], capacity_hours="1000"))["feasible_hours"], "Exact capacity")
    check(not calculate(dict(by_id["A"], capacity_hours="999"))["feasible_hours"], "Below capacity")
    zero = calculate(dict(by_id["A"], switch_units="0", new_units="0", setup_cost="0"))
    check(zero["result_after_launch"] == D("560000"), "Zero launch scenario")
    rejected = 0
    for updates in ({"switch_units": "401"}, {"base_units": "-1"},
                    {"new_units": "1.5"}, {"capacity_hours": "NaN"}):
        try:
            calculate(dict(by_id["A"], **updates))
        except ValueError:
            rejected += 1
    check(rejected == 4, "Invalid inputs must be rejected")
    print(json.dumps({"status": "PASS", "fixed_scenarios": output,
                      "changed_A": {"result": "558000", "hours": "940", "delta": "-2000"},
                      "boundary_checks": ["changed_switching", "exact_capacity", "below_capacity", "zero_new_product"],
                      "invalid_inputs_rejected": rejected},
                     indent=2))


if __name__ == "__main__":
    try:
        main()
    except (AssertionError, ValueError, KeyError) as error:
        print("FAIL: " + str(error), file=sys.stderr)
        sys.exit(1)

