"""Reference solution for Earnings analysis project: explain growth, margin pressure and adjusted results.
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 earnings_bridge(root):
    segments,_=unique(read(root,'segments.csv'),['segment']);opex,_=unique(read(root,'operating_expenses.csv'),['item']);adjustments,_=unique(read(root,'adjustments.csv'),['label'])
    revenue={p:sum(nonnegative(x[f'{p}_revenue']) for x in segments) for p in ('prior','current')};gross={p:revenue[p]-sum(nonnegative(x[f'{p}_cost_of_sales']) for x in segments) for p in revenue};expense={p:sum(nonnegative(x[p]) for x in opex) for p in revenue};profit={p:gross[p]-expense[p] for p in revenue};adj={p:sum(nonnegative(x[p]) for x in adjustments) for p in revenue}
    if revenue['prior']==0 or revenue['current']==0 or profit['prior']==0:raise ValueError('Growth or margin denominator is zero')
    volume=(revenue['current']-revenue['prior'])*gross['prior']/revenue['prior'];margin=gross['current']-gross['prior']-volume;spend=-(expense['current']-expense['prior'])
    if abs(profit['prior']+volume+margin+spend-profit['current'])>1e-8:raise ValueError('Operating bridge fails')
    return {'prior_revenue':revenue['prior'],'current_revenue':revenue['current'],'revenue_growth':revenue['current']/revenue['prior']-1,'prior_gross_profit':gross['prior'],'current_gross_profit':gross['current'],'prior_operating_profit':profit['prior'],'current_operating_profit':profit['current'],'operating_profit_growth':profit['current']/profit['prior']-1,'gross_margin_change_pp':100*(gross['current']/revenue['current']-gross['prior']/revenue['prior']),'revenue_scale_effect':volume,'gross_margin_rate_effect':margin,'expense_effect':spend,'prior_management_adjusted':profit['prior']+adj['prior'],'current_management_adjusted':profit['current']+adj['current'],'management_adjusted_growth':(profit['current']+adj['current'])/(profit['prior']+adj['prior'])-1}

def main():
    directory=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).resolve().parent
    try:
        result=earnings_bridge(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())
