#!/usr/bin/env python3
"""Учебная история HR: эффективная дата отдельно от даты записи. Python3.9+."""
import csv,json,sys
from pathlib import Path
from datetime import date,timedelta
from decimal import Decimal,ROUND_HALF_UP

def read_events(path):
    with path.open(encoding='utf-8') as f: rows=list(csv.DictReader(f,delimiter=';'))
    required=['event_id','version','recorded_at','person_id','contract_id','kind','effective_date','department','primary']
    seen={}; clean=[]; duplicates=0
    for row in rows:
        assert all(row.get(k) for k in required),'Missing required data'
        assert row['kind'] in ['hire','end','transfer'],'Unknown event kind'
        date.fromisoformat(row['recorded_at']);date.fromisoformat(row['effective_date'])
        key=(row['event_id'],int(row['version']))
        if key in seen:
            assert row==seen[key],'Conflicting event version';duplicates+=1;continue
        seen[key]=row;clean.append(row)
    return clean,duplicates

def report(events,cutoff):
    visible=[r for r in events if r['recorded_at']<=cutoff]
    latest={}
    for r in visible:
        k=r['event_id']
        if k not in latest or int(r['version'])>int(latest[k]['version']):latest[k]=r
    selected=list(latest.values());contracts={}
    for r in selected:
        if r['kind']=='hire':
            c=r['contract_id'];assert c not in contracts,'Multiple hire events for one episode'
            contracts[c]={'person':r['person_id'],'start':r['effective_date'],'end':'9999-12-31','primary':int(r['primary']),'department':r['department'],'contract_id':c}
    for r in selected:
        if r['kind'] in ['end','transfer']:
            assert r['contract_id'] in contracts,'Event without visible hire'
            if r['kind']=='end':contracts[r['contract_id']]['end']=r['effective_date']
    for c,v in contracts.items():assert v['start']<v['end'],'Invalid interval'
    daily=[]; month_people=set()
    for offset in range(31):
        day=(date(2026,3,1)+timedelta(days=offset)).isoformat()
        active=[v for v in contracts.values() if v['start']<=day<v['end']]
        people={v['person'] for v in active}; month_people.update(people)
        for person in people: assert sum(v['primary'] for v in active if v['person']==person)<=1,'Overlapping primary episodes'
        departments={}
        for person in people:
            candidates=[v for v in active if v['person']==person]
            main=[v for v in candidates if v['primary']]
            chosen=main[0] if main else candidates[0]
            transfers=[r for r in selected if r['kind']=='transfer' and r['contract_id']==chosen['contract_id'] and r['effective_date']<=day]
            dept=max(transfers,key=lambda r:r['effective_date'])['department'] if transfers else chosen['department']
            departments.setdefault(dept,set()).add(person)
        daily.append({'date':day,'people':len(people),'contracts':len(active),'departments':{k:len(v) for k,v in departments.items()}})
    departures=[]
    for c,v in contracts.items():
        d=v['end']
        if '2026-03-01'<=d<='2026-03-31':
            still_active=any(w['person']==v['person'] and w['start']<=d<w['end'] for w in contracts.values())
            if not still_active:departures.append({'person':v['person'],'first_inactive_day':d})
    person_days=sum(x['people'] for x in daily);contract_days=sum(x['contracts'] for x in daily)
    avg=Decimal(person_days)/31
    ratio=Decimal(len(departures))/avg*100 if person_days else None
    return {'as_of':cutoff,'unique_people_in_period':len(month_people),'person_days':person_days,'contract_days':contract_days,'average_daily_people':str(avg.quantize(Decimal('0.000001'))),'average_daily_contracts':str((Decimal(contract_days)/31).quantize(Decimal('0.000001'))),'person_departures':departures,'turnover_percent':str(ratio.quantize(Decimal('0.01'),rounding=ROUND_HALF_UP)) if ratio is not None else None,'department_person_days':{dept:sum(x['departments'].get(dept,0) for x in daily) for dept in ['Sales','Ops']},'daily':daily,'future_hires_excluded':[r['person_id'] for r in selected if r['kind']=='hire' and r['effective_date']>'2026-03-31']}

if __name__=='__main__':
    base=Path(__file__).resolve().parent
    source=Path(sys.argv[1]) if len(sys.argv)>1 else base/'events.csv'
    dest=Path(sys.argv[2]) if len(sys.argv)>2 else base/'result.json'
    events,dupes=read_events(source)
    result={'exact_duplicate_rows_removed':dupes,'snapshots':{d:report(events,d) for d in ['2026-04-01','2026-04-03']}}
    dest.write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
    latest=result['snapshots']['2026-04-03']
    public={'scope':'synthetic training example','status':'suppressed_small_group' if latest['unique_people_in_period']<5 else 'requires_separate_disclosure_review','metrics':None,'rule':'Учебный порог5 не является универсальной гарантией обезличивания.'}
    dest.with_name(dest.stem+'-public.json').write_text(json.dumps(public,ensure_ascii=False,indent=2),encoding='utf-8')
    with dest.with_suffix('.csv').open('w',encoding='utf-8',newline='') as f:
        w=csv.writer(f,delimiter=';');w.writerow(['as_of','date','people','contracts'])
        for d,r in result['snapshots'].items():
            for x in r['daily']:w.writerow([d,x['date'],x['people'],x['contracts']])
    print(json.dumps({k:{x:y for x,y in v.items() if x!='daily'} for k,v in result['snapshots'].items()},ensure_ascii=False))
