"""Usage: python reproduce_sba_analysis.py /path/to/official-source.csv
Use the exact linked June 30, 2026 snapshot. Outputs aggregates only.
"""
from pathlib import Path
from decimal import Decimal
import csv,json,hashlib,statistics,collections,sys
EXPECTED='6c1e9132b5141a19f82bdc8ccafb86c9a01662461cad41ddb36a3cf409d8a4fe'

def analyze(path):
    path=Path(path)
    digest=hashlib.sha256(path.read_bytes()).hexdigest()
    if digest!=EXPECTED:raise ValueError('Source hash differs; assess version before comparing results')
    with path.open(encoding='utf-8-sig',newline='') as f:rows=list(csv.DictReader(f))
    results=[]
    for fy in [2025,2026]:
        start=f'{fy-1}-10-01';end=f'{fy}-06-30'
        chosen=[r for r in rows if start<=r['ApprovalDate']<=end and r['LoanStatus']!='CANCLD' and r['BusinessAge']=='Change of Ownership']
        amounts=[int(Decimal(r['GrossApproval'])) for r in chosen]
        result={'fiscal_year':fy,'start':start,'end':end,'count':len(chosen),'gross_approval_sum':sum(amounts),'median_gross_approval':statistics.median(amounts),'undisbursed_count':sum(r['LoanStatus']=='COMMIT' for r in chosen),'exact_duplicate_excess':len(chosen)-len(set(tuple(r.values()) for r in chosen))}
        result['undisbursed_share']=result['undisbursed_count']/result['count']
        results.append(result)
    return results

if __name__=='__main__':
    if len(sys.argv)!=2:raise SystemExit(__doc__)
    result=analyze(sys.argv[1]);here=Path(__file__).resolve().parent
    with (here/'sba-change-of-ownership-comparison.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=result[0]);w.writeheader();w.writerows(result)
    print(json.dumps(result,indent=2))
