"""Fictional, deterministic simulation. Python 3.10+, numpy. All records synthetic."""
import csv,calendar,datetime as dt, argparse
from pathlib import Path
import numpy as np
ROOT=Path(__file__).resolve().parent
C='wooden_train plush_bear doll puzzle board_game building_blocks toy_car model_rocket art_kit musical_toy science_kit storybook toy_robot handheld_game electronic_pet magic_wand snow_globe miniature_sleigh fidget_spinner craft_kit toy_dinosaur toy_airplane dress_up_kit aurora_projector enchanted_ai_toy'.split()
M='candy_canes maple_syrup hot_chocolate gingerbread marshmallows aurora_crystals enchanted_pinewood magic_dust candy_floss peppermint_fibers sugar_glass cinnamon star_thread snowflake_foil moonstone_beads polar_ink cocoa_powder ribbon_silk frost_resin bells'.split()
REG='Crimea|Sevastopol|Cherkasy|Chernihiv|Chernivtsi|Dnipropetrovsk|Donetsk|Ivano-Frankivsk|Kharkiv|Kherson|Khmelnytskyi|Kirovohrad|Kyiv city|Kyiv oblast|Luhansk|Lviv|Mykolaiv|Odesa|Poltava|Rivne|Sumy|Ternopil|Vinnytsia|Volyn|Zakarpattia|Zaporizhzhia|Zhytomyr'.split('|')
EVENT={2008:'Wish-list surge',2013:'Gingerbread factory automation',2017:'Fidget spinner boom',2020:'Candy cane supply crisis',2021:'Reindeer modernization',2022:'Maple syrup inflation',2023:'Operation Christmas Hope; AI toy debut',2024:'Hot chocolate shortage',2025:'Magic storage modernization'}
SC={
'recipes':'category material milliunits_per_toy', 'magic_recipes':'category jg_per_gross_toy', 'destinations':'code name synthetic_weight', 'events':'year event',
'wishlists':'year month code category baseline_requests hope_requests total_requests', 'country_spirit':'year month code spirit_index belief_index magic_generated_jg',
'production':'date category planned gross rejects accepted opening_inventory shipped closing_inventory', 'materials':'date material opening_milliunits receipts_milliunits consumed_milliunits closing_milliunits price_snf_per_unit',
'magic':'date opening_jg generated_jg leakage_jg factory_jg sleigh_jg closing_jg aurora_index capacity_jg curtailed_jg', 'workforce':'date department employed paid_hours cocoa_milli_liters happiness_index wages_snf',
'households':'year month population labor_force employed unemployed wages_snf consumption_snf opening_savings_snf closing_savings_snf housing_price_snf happiness_index',
'economy':'year month toy_output_snf intermediate_inputs_snf toy_value_added_snf services_value_added_snf gdp_snf cpi policy_rate_pct inventory_storage_cost_snf',
'deliveries':'year code category baseline_requested hope_requested baseline_delivered hope_delivered unfilled', 'ukraine_regions':'year region baseline_requested hope_requested baseline_delivered hope_delivered',
'reindeer':'year fleet_size flight_hours equivalent_distance_km payload_toys capacity_toys magic_jg carrots_kg', 'annual_summary':'year demand delivered hope_delivered gross accepted rejected inventory magic_generated magic_used magic_reserves gdp_snf'}
SC={k:v.split() for k,v in SC.items()}
def alloc(n,w):
 n=int(n);w=np.array(w,dtype=float)
 if n==0:return np.zeros(len(w),dtype='int64')
 a=n*w/w.sum();b=a.astype('int64');b[np.argsort(-(a-b),kind='stable')[:n-int(b.sum())]]+=1;return b
def gen(end,out,magic_supply=1.0):
 out=Path(out);out.mkdir(parents=True,exist_ok=True);dest=list(csv.DictReader((ROOT/'destinations.csv').open()));codes=[x['code'] for x in dest];D=len(dest);u=codes.index('UA');rng=np.random.default_rng(4811);weight=rng.lognormal(0,1.3,D);weight[u]=2.8;weight/=weight.sum();pref=rng.uniform(.55,1.45,(D,25));recipe=rng.integers(0,35,(25,20));recipe[:,2]=0;recipe[:,0]+=4;recipe[:,1]+=3;recipe[:,6]+=6;rates=rng.integers(2,7,25);price=rng.uniform(.8,6,20);rw=rng.uniform(.5,1.5,27)
 files={k:(out/(k+'.csv')).open('w',newline='',encoding='utf8') for k in SC};writers={k:csv.writer(f,lineterminator='\n') for k,f in files.items()};put=lambda k,r:writers[k].writerow(r)
 for k,cols in SC.items():put(k,cols)
 for i,x in enumerate(dest):put('destinations',[codes[i],x['name'],weight[i]])
 for i,c in enumerate(C):
  put('magic_recipes',[c,rates[i]])
  for j,m in enumerate(M):put('recipes',[c,m,recipe[i,j]])
 inv=np.zeros(25,dtype='int64');stock=np.zeros(20,dtype='int64');magic=0;savings=0.;cpi=100.;prior=84e6;service=.95;pop=24000;housing=70000.;season=np.array([.025,.025,.03,.035,.04,.05,.06,.07,.10,.15,.22,.195]);season/=season.sum();plan=np.array([.052,.058,.06,.065,.07,.075,.08,.085,.09,.12,.13,.115]);plan/=plan.sum()
 for y in range(2006,end+1):
  a=y-2006;rng=np.random.default_rng(731926+y);put('events',[y,EVENT.get(y,'Normal operations')]);dem=np.zeros((D,25),dtype='int64');hope=np.zeros_like(dem);sent=np.zeros_like(dem);hs=np.zeros_like(dem);gross=good=bad=generated=used_magic=0;gdp_total=0.;pop=round(pop*1.012);forecast=prior*1.023;start_inv=inv.copy();storage_capacity=round(forecast*(.85 if y>=2025 else .65));cw=np.array([0 if (c=='fidget_spinner' and y<2017 or c=='enchanted_ai_toy' and y<2023 or c=='aurora_projector' and y<2013) else 1+.7*(c=='fidget_spinner' and y==2017) for c in C]);
  for mo in range(1,13):
   days=calendar.monthrange(y,mo)[1];n=round(84e6*1.023**a*season[mo-1]*rng.uniform(.95,1.05)*(1.08 if y in (2008,2020) else 1));by=alloc(n,weight);new=np.array([alloc(by[i],pref[i]*cw) for i in range(D)]);extra=np.zeros_like(new)
   if y>=2023:extra[u]=alloc(round(new[u].sum()*1.75),pref[u]*cw)
   dem+=new;hope+=extra;spirit=np.clip(65+12*service+7*np.sin((mo-8)*np.pi/6)+rng.normal(0,6,D),20,100);belief=np.clip(60+rng.normal(0,8,D),20,95);mg=round(forecast/12*5.0*magic_supply*np.average(spirit*belief,weights=weight)/(75*60));cg=alloc(mg,weight*spirit*belief)
   for i,code in enumerate(codes):
    put('country_spirit',[y,mo,code,round(spirit[i],3),round(belief[i],3),cg[i]])
    for j,c in enumerate(C):put('wishlists',[y,mo,code,c,new[i,j],extra[i,j],new[i,j]+extra[i,j]])
   revised=max(forecast,(dem+hope).sum()/season[:mo].sum());target=round(max(0,revised*1.045-start_inv.sum())*plan[mo-1]+extra.sum()*.20);daily=alloc(target,np.ones(days));aurora=rng.uniform(.75,1.25,days);dg=alloc(mg,aurora);cpi*=1.0015*(1.018 if y==2022 and mo<=3 else 1);housing*=1.002;lf=round(pop*.61);un=round(lf*(.07 if y==2020 else .045));emp=lf-un;staff=alloc(emp,[.65,.1,.08,.07,.1]);wages=inputs=output=storage_cost=0.;morales=[];capacity=round(revised*1.18*(1.07 if y>=2021 else 1));
   for day in range(1,days+1):
    date=dt.date(y,mo,day).isoformat();xmas=mo==12 and day==24;pl=alloc(daily[day-1],cw);os=stock.copy();om=magic;g=int(dg[day-1]);magic+=g;curtailed=max(0,magic-storage_capacity);magic-=curtailed;leak=min(magic,round(magic*(.00012 if y>=2025 else .00030)));magic-=leak;hours=4 if mo==12 and day>=25 else 10 if mo>=10 else 8;cocoa_need=emp*hours*90;need=pl@recipe;need[2]=cocoa_need;factor=np.ones(20);factor[0]=.64 if y==2020 else 1;factor[2]=.63 if y==2024 else 1;rec=np.maximum(0,np.minimum(need*3-stock,np.where(factor<1,need*factor,need*3))).astype('int64');stock+=rec;cocoa=min(cocoa_need,int(stock[2]));morale=float(np.clip(90+6*(service-.95)-22*(1-cocoa/max(1,cocoa_need))-max(0,hours-8)*3+rng.normal(0,1.5),40,100));morales.append(morale);cap=round(staff[0]*hours*3.8*(1+.013*a+.04*(y>=2013))*morale/90);initial=alloc(min(daily[day-1],cap),cw);req=initial@recipe;budget=max(0,magic-round(capacity/3)) if xmas else magic;scale=min(1.,*[stock[j]/req[j] for j in range(20) if req[j]>0],budget/max(1,int(initial@rates)));gc=np.floor(initial*scale).astype('int64');cons=gc@recipe;cons[2]=cocoa;stock-=cons;man=int(gc@rates);magic-=man;rej=np.round(gc*(.012+.004*rng.random(25))).astype('int64');ok=gc-rej;oi=inv.copy();inv+=ok;ship=np.zeros(25,dtype='int64');sm=0
    if xmas:
     christmas_capacity=capacity
     avail=np.minimum(inv,(dem+hope).sum(axis=0));caps=alloc(min(int(avail.sum()),capacity,magic*3),avail) if avail.sum() else avail
     for j in range(25):
      q=min(int(caps[j]),int(hope[u,j]));hs[u,j]=q;sent[:,j]=alloc(min(int(caps[j])-q,int(dem[:,j].sum())),dem[:,j]) if dem[:,j].sum() else 0;ship[j]=sent[:,j].sum()+q
     sm=(int(ship.sum())+2)//3;magic-=sm;inv-=ship;sleigh_magic=sm
    prices=price*cpi/100;prices[0]*=1.9 if y==2020 else 1;prices[1]*=1.8 if y==2022 else 1;prices[2]*=1.7 if y==2024 else 1;daily_storage=float(oi.sum())*.2*cpi/100/365.25;storage_cost+=daily_storage;inputs+=float(cons@prices/1000)+daily_storage;output+=ok.sum()*4*cpi/100
    for j,c in enumerate(C):put('production',[date,c,pl[j],gc[j],rej[j],ok[j],oi[j],ship[j],inv[j]])
    for j,m in enumerate(M):put('materials',[date,m,os[j],rec[j],cons[j],stock[j],round(prices[j],6)])
    put('magic',[date,om,g,leak,man,sm,magic,round(aurora[day-1],3),storage_capacity,curtailed]);co=alloc(cocoa,staff)
    for j,dep in enumerate(['toy_factory','magic_research','logistics','public_services','local_business']):
     wage=round(staff[j]*hours*(9+j*.6)*cpi/100,2);wages+=wage;put('workforce',[date,dep,staff[j],staff[j]*hours,co[j],round(morale,3),wage])
    gross+=int(gc.sum());good+=int(ok.sum());bad+=int(rej.sum());generated+=g;used_magic+=man+sm
   income=round(wages,2);spend=round(income*.8,2);s0=savings;savings=round(savings+income-spend,2);va=round(round(output,2)-round(inputs,2),2);services=round(spend*.6,2);gdp=round(va+services,2);gdp_total+=gdp;put('households',[y,mo,pop,lf,emp,un,income,spend,s0,savings,round(housing,2),round(np.mean(morales),3)]);put('economy',[y,mo,round(output,2),round(inputs,2),va,services,gdp,round(cpi,5),round(2+(cpi/100-1)*.5,3),round(storage_cost,2)])
  for i,code in enumerate(codes):
   for j,c in enumerate(C):put('deliveries',[y,code,c,dem[i,j],hope[i,j],sent[i,j],hs[i,j],dem[i,j]+hope[i,j]-sent[i,j]-hs[i,j]])
  br=alloc(dem[u].sum(),rw);hr=alloc(hope[u].sum(),rw);bd=alloc(sent[u].sum(),br);hd=alloc(hs[u].sum(),hr) if hr.sum() else hr
  for i,r in enumerate(REG):put('ukraine_regions',[y,r,br[i],hr[i],bd[i],hd[i]])
  total=int(sent.sum()+hs.sum());put('reindeer',[y,round(8+.2*a),round(total/20000,3),round(total*.045,2),total,christmas_capacity,sleigh_magic,round(total*.00018,3)]);put('annual_summary',[y,(dem+hope).sum(),total,hs.sum(),gross,good,bad,inv.sum(),generated,used_magic,magic,round(gdp_total,2)]);prior=(dem+hope).sum();service=total/max(1,prior)
 for f in files.values():f.close()
if __name__=='__main__':
 p=argparse.ArgumentParser();p.add_argument('--end-year',type=int,default=2025);p.add_argument('--out',default=ROOT/'data');p.add_argument('--magic-supply',type=float,default=1.0);a=p.parse_args();assert a.magic_supply>0;gen(a.end_year,a.out,a.magic_supply)
