# -*- coding: utf-8 -*-
"""Run beside inputs with Python3.9+: python3 allocate.py. Writes result.json."""
import csv,json
from pathlib import Path
P=Path(__file__).resolve().parent
rows=list(csv.DictReader((P/'employees.csv').open()));policy=json.loads((P/'policy.json').read_text())
for r in rows:
 for k in ['salary','minimum','midpoint','maximum','proposed_salary','start_month','priority','eligible']:r[k]=int(r[k])
 if not(1<=r['start_month']<=12) or r['salary']<=0 or not(r['minimum']<=r['midpoint']<=r['maximum']):raise ValueError('invalid inputs')
if len({r['employee'] for r in rows})!=len(rows):raise ValueError('duplicate employee')
def calc(annual_limit,confirmed=False):
 data=[dict(r) for r in rows]
 if confirmed:
  r=next(r for r in data if r['employee']=='E11');r.update(role='analyst',eligible=1,priority=1.5,reason='confirmed_grade')
 used=full=0;out=[]
 for r in sorted(data,key=lambda x:(x['priority'],x['employee'])):
  delta=r['proposed_salary']-r['salary'];months=13-r['start_month'];cost=delta*months;annual=delta*12
  if delta<0:raise ValueError('not a salary reduction exercise')
  if r['eligible'] and not(r['minimum']<=r['proposed_salary']<=r['maximum']):raise ValueError('target outside range')
  accept=bool(r['eligible'] and delta>0 and used+cost<=policy['base_current_year_limit'] and full+annual<=annual_limit)
  status='accepted' if accept else ('budget_hold' if r['eligible'] and delta>0 else r['reason'])
  if accept:used+=cost;full+=annual
  out.append(dict(employee=r['employee'],status=status,delta=delta if accept else 0,new_salary=r['proposed_salary'] if accept else r['salary'],current_year_cost=cost if accept else 0,annualized_cost=annual if accept else 0,compa_before=r['salary']/r['midpoint'],compa_after=(r['proposed_salary'] if accept else r['salary'])/r['midpoint']))
 return dict(current_year=used,annualized=full,monthly_increment=full//12,remaining_current=policy['base_current_year_limit']-used,remaining_annualized=annual_limit-full,accepted=[r['employee'] for r in out if r['status']=='accepted'],employees=sorted(out,key=lambda r:r['employee']))
result={k:calc(v,c) for k,v,c in [('base',600000,False),('expanded',720000,False),('confirmed_grade',600000,True)]}
(P/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
print(json.dumps({k:{x:v[x] for x in ['current_year','annualized','monthly_increment','accepted']} for k,v in result.items()},ensure_ascii=False))
