"""Reference solution for Revenue reconciliation project: tie contracts, invoices, cash and the ledger.
Original synthetic teaching data only. Python 3.10+, standard library.
Run python solve.py [path-to-project-inputs]. No network or credentials.
"""
from pathlib import Path
from datetime import datetime, date
import csv, json, math, statistics, sys

def read(root, name):
    with (Path(root)/name).open(newline='',encoding='utf-8') as f:
        reader=csv.DictReader(f)
        if not reader.fieldnames or len(reader.fieldnames)!=len(set(reader.fieldnames)):
            raise ValueError(f'{name}: missing or duplicate headers')
        rows=list(reader)
        if any(None in row or any(v is None for v in row.values()) for row in rows):
            raise ValueError(f'{name}: inconsistent row length')
        return rows

def rules(root): return json.loads((Path(root)/'rules.json').read_text())

def number(value):
    x=float(value)
    if not math.isfinite(x): raise ValueError('Non-finite input')
    return x

def nonnegative(value):
    x=number(value)
    if x<0:raise ValueError('Negative quantity or amount')
    return x

def flag(value):
    if value not in ('true','false'):raise ValueError('Boolean must be true or false')
    return value=='true'

def timestamp(value):
    d=datetime.fromisoformat(value.replace('Z','+00:00'))
    if d.tzinfo is None:raise ValueError('Timestamp requires an explicit time zone')
    return d

def unique(rows, keys, ignore=()):
    by={};duplicates=0
    for row in rows:
        key=tuple(row[k] for k in keys)
        if any(not k for k in key):raise ValueError('Missing record identity')
        if key in by:
            prior={k:v for k,v in by[key].items() if k not in ignore}
            new={k:v for k,v in row.items() if k not in ignore}
            if prior!=new:raise ValueError(f'Conflicting records at {key}')
            duplicates+=1
        else:by[key]=row
    return list(by.values()),duplicates

def rounded(value):
    if isinstance(value,float): return round(value,8)
    if isinstance(value,dict):return {k:rounded(v) for k,v in value.items()}
    if isinstance(value,list):return [rounded(v) for v in value]
    return value

def month_index(s):
    d=datetime.strptime(s,'%Y-%m')
    if d.strftime('%Y-%m')!=s:raise ValueError('Use YYYY-MM')
    return d.year*12+d.month

def revenue_rollforward(root):
    r=rules(root);contracts,_=unique(read(root,'contracts.csv'),['contract_id']);invoices,retries=unique(read(root,'invoices.csv'),['invoice_id']);receipts,_=unique(read(root,'receipts.csv'),['receipt_id']);booked,_=unique(read(root,'booked_revenue.csv'),['month'])
    ids={c['contract_id'] for c in contracts};imap={i['invoice_id']:i for i in invoices}
    if any(i['contract_id'] not in ids for i in invoices) or any(p['invoice_id'] not in imap for p in receipts):raise ValueError('Unmapped contract or invoice')
    expected={m:0. for m in r['months']}
    for c in contracts:
        start,end=month_index(c['service_start_month']),month_index(c['service_end_month'])
        if end<start:raise ValueError('Reversed service interval')
        monthly=nonnegative(c['transaction_price'])/(end-start+1)
        for m in expected:
            if start<=month_index(m)<=end:expected[m]+=monthly
    if {x['month'] for x in booked}!=set(expected):raise ValueError('Booked periods must match')
    schedule=[];deferred=ar=0.
    for m in r['months']:
        billed=sum(nonnegative(x['amount']) for x in invoices if x['month']==m);cash=sum(nonnegative(x['amount']) for x in receipts if x['month']==m)
        deferred+=billed-expected[m];ar+=billed-cash
        schedule.append({'month':m,'billed':billed,'cash':cash,'revenue':expected[m],'ending_contract_liability':deferred,'ending_receivable':ar})
    recognized=sum(expected.values());booked_total=sum(nonnegative(x['amount']) for x in booked)
    return {'invoice_retry_rows_removed':retries,'billed_total':sum(x['billed'] for x in schedule),'cash_total':sum(x['cash'] for x in schedule),'expected_revenue':recognized,'booked_revenue':booked_total,'booked_overstatement':booked_total-recognized,'ending_contract_liability':deferred,'ending_receivable':ar,'monthly':schedule}

def main():
    directory=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).resolve().parent
    try:
        result=revenue_rollforward(directory)
        print(json.dumps(rounded(result),indent=2,allow_nan=False))
    except (OSError,ValueError,KeyError,TypeError,ZeroDivisionError) as exc:
        print(f"Input could not be analyzed: {exc}",file=sys.stderr);return 2
    return 0
if __name__=='__main__':raise SystemExit(main())
