"""Fixed answers and independent arithmetic; exits 1 on any mismatch."""
import copy
import json
import sys
from decimal import Decimal
from fractions import Fraction
from pathlib import Path
from analyze import evaluate

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

def main():
    data = json.loads(Path(__file__).with_name("projects.json").read_text(encoding="utf-8"))
    rows = {r["id"]: r for r in evaluate(data)}
    expected = {"A": ("1.93688955672426746806912096", "28", "2.8", "6", "4", False, True),
                "B": ("0.46581517655897821187077385", "23", "2.3", "5", "3", True, True)}
    for identifier, values in expected.items():
        row = rows[identifier]
        keys = ("npv", "total_debt", "debt_ratio", "closing_cash", "stressed_cash", "debt_pass", "reserve_pass")
        for key, value in zip(keys, values):
            if isinstance(value, bool):
                check(row[key] == value, "Fixed decision mismatch: " + identifier + "/" + key)
            elif key == "npv":
                check(abs(Decimal(row[key]) - Decimal(value)) < Decimal("0.000000001"), "Fixed NPV mismatch")
            else:
                check(Decimal(row[key]) == Decimal(value), "Fixed number mismatch: " + identifier + "/" + key)
    # Independent exact rational annuity value, not a call to the model's NPV formula.
    factor = Fraction(3310, 1331)
    for identifier, investment, flow in (("A", 10, Fraction(24, 5)), ("B", 6, Fraction(13, 5))):
        exact = flow * factor - investment
        independent = Decimal(exact.numerator) / Decimal(exact.denominator)
        check(abs(Decimal(rows[identifier]["npv"]) - independent) < Decimal("0.000000001"), "Independent NPV mismatch")
    # Independent financing interval: no debt satisfies both A conditions.
    debt_ceiling = Decimal("2.5") * Decimal("10") - Decimal("20")
    loan_floor = Decimal("3") + Decimal("2") + Decimal("10") - Decimal("8")
    check(debt_ceiling == 5 and loan_floor == 7 and loan_floor > debt_ceiling, "Funding interval")
    alt = copy.deepcopy(data);alt["projects"] = [alt["projects"][0]];alt["projects"][0]["loan"] = "5"
    row = evaluate(alt)[0]
    check(row["debt_pass"] and not row["reserve_pass"] and Decimal(row["stressed_cash"]) == 1, "A reduced debt")
    alt["projects"][0]["equity"] = "2";row = evaluate(alt)[0]
    check(row["both_pass"] and Decimal(row["debt_ratio"]) == Decimal("2.5") and Decimal(row["stressed_cash"]) == 3, "Exact limits with equity")
    changed = copy.deepcopy(data);changed["stress_delay"] = "3"
    row = evaluate(changed)[1]
    check(not row["reserve_pass"] and row["debt_pass"] and Decimal(row["stressed_cash"]) == 2, "Delay boundary")
    changed = copy.deepcopy(data);changed["ebitda"] = "8"
    row = evaluate(changed)[1]
    check(not row["debt_pass"] and Decimal(row["debt_ratio"]) == Decimal("2.875"), "EBITDA boundary")
    changed = copy.deepcopy(data);changed["discount_rate"] = "0"
    check(Decimal(evaluate(changed)[0]["npv"]) == Decimal("4.4"), "Zero discount")
    invalid = []
    for field, value in (("ebitda", "0"), ("opening_cash", "-1"), ("discount_rate", "NaN")):
        bad = copy.deepcopy(data);bad[field] = value;invalid.append(bad)
    bad = copy.deepcopy(data);bad["projects"][0]["cash_flows"] = ["4.8"];invalid.append(bad)
    for bad in invalid:
        try:
            evaluate(bad)
        except (ValueError, ArithmeticError):
            pass
        else:
            raise AssertionError("Invalid input accepted")
    print(json.dumps({"fixed_projects": 2, "independent_rational_check": True,
                      "edges": ["loan interval", "exact debt and cash bounds", "delay 3", "EBITDA 8", "zero discount"],
                      "invalid_inputs_rejected": len(invalid)}))

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