"""Reference solution for Sales pipeline analysis project: reconcile the export before forecasting.
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 sales_pipeline(root):
    r=rules(root);asof=timestamp(r['as_of']);raw=read(root,'opportunities.csv')
    stage_rows,_=unique(read(root,'stage_rules.csv'),['stage'])
    stage={x['stage']:(nonnegative(x['probability']),flag(x['is_open'])) for x in stage_rows}
    if any(p>1 for p,_ in stage.values()):raise ValueError('Probability outside [0,1]')
    eligible=[x for x in raw if timestamp(x['snapshot_at'])<=asof]
    dedup,retries=unique(eligible,['opportunity_id','snapshot_at'],['export_row'])
    current={}
    for x in dedup:
        if x['currency']!=r['currency']:raise ValueError('Currency outside defined scope')
        nonnegative(x['amount'])
        if x['stage'] not in stage:raise ValueError('Unknown stage')
        oid=x['opportunity_id']
        if oid not in current or timestamp(x['snapshot_at'])>timestamp(current[oid]['snapshot_at']):current[oid]=x
    opened=[x for x in current.values() if stage[x['stage']][1]]
    quarter=[x for x in opened if asof.date()<=date.fromisoformat(x['expected_close'])<=date.fromisoformat(r['quarter_end'])]
    stale=[x['opportunity_id'] for x in opened if (asof.date()-date.fromisoformat(x['last_activity'])).days>r['stale_after_days']]
    return {'raw_rows':len(raw),'future_rows_excluded':len(raw)-len(eligible),'retry_rows_removed':retries,'latest_opportunities':len(current),'open_opportunities':len(opened),'open_pipeline':sum(number(x['amount']) for x in opened),'weighted_open_pipeline':sum(number(x['amount'])*stage[x['stage']][0] for x in opened),'quarter_pipeline':sum(number(x['amount']) for x in quarter),'weighted_quarter_pipeline':sum(number(x['amount'])*stage[x['stage']][0] for x in quarter),'stale_open_ids':sorted(stale),'latest_total_all_statuses':sum(number(x['amount']) for x in current.values())}

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