#!/usr/bin/env python3
"""Независимая сверка фиксированного примера: не импортирует calculate.py."""
import csv,json,sys
from decimal import Decimal
from pathlib import Path
p=Path(__file__).resolve().parent
result=json.loads((Path(sys.argv[1]) if len(sys.argv)>1 else p/'result.json').read_text(encoding='utf-8'))
expected={
 'group_loan':{'A':[1000000,2000000,1000000],'B':[1000000,1000000,4000000],'C':[1000000,1000000,2000000]},
 'separate_funding':{'A':[1000000,2000000,1000000],'B':[1000000,2000000,3980000],'C':[1000000,1000000,2000000]},
 'delayed_receipt':{'A':[1000000,1000000,1000000],'B':[1000000,1000000,3960000],'C':[1000000,1000000,2000000]}}
for scenario,entities in expected.items():
    for entity,balances in entities.items():
        actual=[r['free_RUB'] for r in result[scenario]['rows'] if r['entity']==entity]
        assert actual==balances,(scenario,entity,actual,balances)
# Другой путь: агрегированная сверка всей группы с исходными притоками/платежами.
with (p/'operating-flows.csv').open(encoding='utf-8') as f: flows=list(csv.DictReader(f,delimiter=';'))
net=sum(int(x['receipts_RUB'])-int(x['payments_RUB']) for x in flows)
assert net==-3000000
for scenario,fee in [('group_loan',0),('separate_funding',20000),('delayed_receipt',40000)]:
    closing=sum(r['free_RUB']+r['restricted_RUB'] for r in result[scenario]['rows'] if r['day']==3)
    assert closing==17000000+net-fee,(scenario,closing)
# Считаем цену из независимых сумм и длительности, не из результата debt rows.
interest_a3=Decimal(3000000)*Decimal('0.18')/365
interest_a2=Decimal(2000000)*Decimal('0.18')/365
interest_b=Decimal(2000000)*Decimal('0.24')*2/365
for scenario,expected_cost in [('group_loan',interest_a3+interest_b),('separate_funding',interest_a2+interest_b+20000),('delayed_receipt',interest_a3+interest_b+40000)]:
    actual=Decimal(result[scenario]['total_cost_RUB']); assert abs(actual-expected_cost)<Decimal('0.005'),(scenario,actual,expected_cost)
assert Decimal(result['group_loan']['total_cost_RUB'])==Decimal('4109.59')
assert Decimal(result['separate_funding']['total_cost_RUB'])==Decimal('23616.44')
assert Decimal(result['delayed_receipt']['total_cost_RUB'])==Decimal('44109.59')
print('PASS: 27 entity/day balances, group bridge, independent interest, all three scenarios.')
