"""Inventory Intelligence — deterministic synthetic study, not actual retailer data.
Run: python run_analysis.py --output .
Requires Python 3.10+, numpy and pandas. All database execution is local SQLite.
"""
from pathlib import Path
import argparse, json, sqlite3, math, hashlib
import numpy as np
import pandas as pd

SEED = 20261114
STORES, PRODUCTS, DAYS, TRAIN_DAYS = 5, 18, 60, 40
CARRY_RATE, ORDER_COST = .25, 8.0
NAMES = ['Cordless drill','Circular saw','Impact driver','Hammer','Socket set','Tape measure','Interior paint','Primer','Paint roller','Garden soil','Mulch','Hose','LED bulb','Extension cord','Outlet','PVC pipe','Faucet','Pipe fitting']
CATEGORIES = ['Tools']*6 + ['Paint']*3 + ['Garden']*3 + ['Electrical']*3 + ['Plumbing']*3

def generate(seed=SEED):
    rng = np.random.default_rng(seed)
    stores = pd.DataFrame([dict(store_id=s+1,store_name=f'Simulated Store {s+1}',region=['Northeast','Southeast','Midwest','Southwest','West'][s],store_type='Synthetic home improvement') for s in range(STORES)])
    products = pd.DataFrame([dict(product_id=p+1,sku=f'SKU-{p+1:03}',product_name=NAMES[p],category=CATEGORIES[p],unit_cost=round(5+((p*17)%90),2),selling_price=round((5+((p*17)%90))*1.55,2),unit_volume_cubic_ft=round(.05+(p%6)*.12,2),active_status=True) for p in range(PRODUCTS)])
    suppliers = pd.DataFrame([dict(supplier_id=s+1,supplier_name=f'Simulated Supplier {s+1}',expected_lead_time_days=3+s,lead_time_std_days=1.0) for s in range(3)])
    bridge = pd.DataFrame([dict(product_id=p+1,supplier_id=p%3+1,preferred_supplier_flag=True) for p in range(PRODUCTS)])
    demand = np.zeros((DAYS,STORES,PRODUCTS),dtype=int)
    lead = np.zeros_like(demand)
    start = pd.Timestamp('2026-01-01')
    for day in range(DAYS):
        for s in range(STORES):
            for p in range(PRODUCTS):
                base=(2+p%7)*( .8+s*.1)
                weekend=1.3 if (start+pd.Timedelta(days=day)).dayofweek>=5 else 1.0
                seasonal=1.15 if CATEGORIES[p]=='Garden' and day>=30 else 1.0
                demand[day,s,p]=rng.poisson(base*weekend*seasonal)
                lead[day,s,p]=max(1,int(round(rng.normal(3+p%3,1))))
    return stores,products,suppliers,bridge,demand,lead

def simulate(demand, lead, products, policy='Baseline', start_day=0, end_day=DAYS, means=None, stds=None):
    """Lost-sales system. Receipts before sales, orders after sales; no backorders.
    Compare policies with equal initial inventory, demand and per-order-day lead-time draws.
    Policies use inventory position (on hand + on order). No future demand informs targets.
    """
    if means is None:
        means=np.array([[(2+p%7)*(.8+s*.1) for p in range(PRODUCTS)] for s in range(STORES)])
        stds=np.sqrt(means)
    records, orders, settings=[],[],[]
    costs=products.unit_cost.to_numpy(); prices=products.selling_price.to_numpy()
    for s in range(STORES):
        for p in range(PRODUCTS):
            mu=float(means[s,p]); sd=float(stds[s,p]); lt=3+p%3
            safety=math.ceil(1.65*math.sqrt(lt*sd**2+mu**2))
            if policy=='Baseline':
                rop=math.ceil(mu*2); target=math.ceil(mu*9); review=7; buffer=0
            elif policy=='Reorder point':
                rop=math.ceil(mu*lt+safety); target=math.ceil(rop+mu*4); review=1; buffer=safety
            else:
                rop=math.ceil(mu*lt+safety); review=3; buffer=safety
                target=math.ceil(mu*(lt+review)+1.65*math.sqrt((lt+review)*sd**2+mu**2))
            settings.append(dict(store_id=s+1,product_id=p+1,policy_effective_date=str(pd.Timestamp('2026-01-01')+pd.Timedelta(days=start_day))[:10],reorder_point=rop,target_stock=target,safety_stock=buffer,review_period_days=review))
            onhand=math.ceil(mu*7); pending=[]
            for day in range(start_day,end_day):
                opening=onhand
                arrived=[o for o in pending if o['day']==day]
                receipts=sum(o['quantity'] for o in arrived)
                pending=[o for o in pending if o['day']>day]
                onhand+=receipts
                wanted=int(demand[day,s,p]); sold=min(wanted,onhand); unmet=wanted-sold; onhand-=sold
                date=str(pd.Timestamp('2026-01-01')+pd.Timedelta(days=day))[:10]
                records.append(dict(date=date,store_id=s+1,product_id=p+1,opening_inventory=opening,receipts=receipts,sales_units=sold,closing_inventory=onhand,observed_stockout_flag=unmet>0,demand_units=wanted,simulated_unmet_demand_units=unmet,policy=policy))
                position=onhand+sum(o['quantity'] for o in pending)
                check=((day-start_day)%review==0)
                should_order=check and (position<=rop if policy!='Periodic review' else True)
                if should_order:
                    qty=max(0,target-position)
                    if qty:
                        delivery=day+int(lead[day,s,p]); delivery_date=str(pd.Timestamp('2026-01-01')+pd.Timedelta(days=delivery))[:10]
                        pending.append(dict(day=delivery,quantity=qty))
                        received=delivery<end_day
                        orders.append(dict(purchase_order_id=len(orders)+1,store_id=s+1,product_id=p+1,supplier_id=p%3+1,order_date=date,expected_delivery_date=str(pd.Timestamp(date)+pd.Timedelta(days=lt))[:10],actual_delivery_date=delivery_date if received else None,ordered_quantity=qty,received_quantity=qty if received else 0,order_status='received' if received else 'open'))
    df=pd.DataFrame(records); po=pd.DataFrame(orders)
    cost=df.product_id.map(dict(enumerate(costs,1))); price=df.product_id.map(dict(enumerate(prices,1)))
    carrying=float((df.closing_inventory*cost).sum()*CARRY_RATE/365)
    metrics=dict(policy=policy,days=end_day-start_day,demand_units=int(df.demand_units.sum()),sales_units=int(df.sales_units.sum()),unmet_units=int(df.simulated_unmet_demand_units.sum()),fill_rate_pct=round(100*df.sales_units.sum()/df.demand_units.sum(),2),stockout_rate_pct=round(100*df.observed_stockout_flag.mean(),2),avg_inventory_value=round(float((df.closing_inventory*cost).sum()/(end_day-start_day)),2),carrying_cost=round(carrying,2),orders=len(po),ordering_cost=round(len(po)*ORDER_COST,2),operating_cost=round(carrying+len(po)*ORDER_COST,2),unmet_revenue_exposure=round(float((df.simulated_unmet_demand_units*price).sum()),2))
    return df,po,pd.DataFrame(settings),metrics

SQL = '''-- Executed locally with SQLite 3 through run_analysis.py; synthetic records only.
-- stockout flag means positive simulated unmet units, not hours unavailable.
SELECT s.store_name,p.sku,p.product_name,p.category,COUNT(*) AS observed_days,
 SUM(CASE WHEN i.observed_stockout_flag THEN 1 ELSE 0 END) AS stockout_days,
 ROUND(100.0*SUM(CASE WHEN i.observed_stockout_flag THEN 1 ELSE 0 END)/COUNT(*),2) AS stockout_rate_pct,
 SUM(d.simulated_unmet_demand_units) AS unmet_units,
 ROUND(SUM(d.simulated_unmet_demand_units*p.selling_price),2) AS unmet_revenue_exposure
FROM daily_inventory i JOIN stores s USING(store_id) JOIN products p USING(product_id)
JOIN daily_demand d USING(date,store_id,product_id)
GROUP BY s.store_name,p.sku,p.product_name,p.category
ORDER BY unmet_revenue_exposure DESC,p.sku,s.store_name;'''
CATEGORY_SQL='''SELECT p.category,SUM(i.sales_units) AS sales_units,
ROUND(100.0*SUM(i.sales_units)/SUM(d.observed_demand_units),2) AS fill_rate_pct,
ROUND(100.0*SUM(CASE WHEN i.observed_stockout_flag THEN 1 ELSE 0 END)/COUNT(*),2) AS stockout_rate_pct,
ROUND(SUM(i.closing_inventory*p.unit_cost)/60.0,2) AS avg_inventory_value,
ROUND(SUM(i.sales_units*p.unit_cost)/(SUM(i.closing_inventory*p.unit_cost)/60.0),3) AS period_turnover,
ROUND(SUM(d.simulated_unmet_demand_units*p.selling_price),2) AS unmet_revenue_exposure
FROM daily_inventory i JOIN products p USING(product_id) JOIN daily_demand d USING(date,store_id,product_id)
GROUP BY p.category ORDER BY stockout_rate_pct DESC;'''

def forecast(demand):
    """Fixed-origin 20-day forecast from first 40 days only, no tuning on test data."""
    out=[]; detail=[]
    for method in ['Seasonal naive','Trailing 14-day mean','Exponential smoothing']:
        predicted=[]
        for s in range(STORES):
            for p in range(PRODUCTS):
                history=demand[:TRAIN_DAYS,s,p].astype(float)
                smooth=history[0]
                for x in history[1:]: smooth=.3*x+.7*smooth
                for t in range(TRAIN_DAYS,DAYS):
                    if method=='Seasonal naive': y=history[TRAIN_DAYS-7+(t-TRAIN_DAYS)%7]
                    elif method=='Trailing 14-day mean': y=history[-14:].mean()
                    else: y=smooth
                    actual=int(demand[t,s,p]); predicted.append((actual,float(y)))
                    detail.append(dict(method=method,date=str(pd.Timestamp('2026-01-01')+pd.Timedelta(days=t))[:10],store_id=s+1,product_id=p+1,actual=actual,predicted=round(float(y),6)))
        a=np.array(predicted); err=a[:,1]-a[:,0]
        out.append(dict(method=method,mae=round(float(np.abs(err).mean()),3),rmse=round(float(np.sqrt((err**2).mean())),3),wape_pct=round(float(100*np.abs(err).sum()/a[:,0].sum()),2),bias_units=round(float(err.mean()),3),test_observations=len(a)))
    return out,pd.DataFrame(detail)

def validate(inv, demand, products, stores, orders):
    rules={
      'expected_rows': len(inv)==5400,
      'unique_daily_keys': not inv.duplicated(['date','store_id','product_id']).any(),
      'no_missing_inventory_fields': not inv.isna().any().any(),
      'nonnegative_quantities': bool((inv[['opening_inventory','receipts','sales_units','closing_inventory']]>=0).all().all()),
      'balanced_inventory': bool((inv.opening_inventory+inv.receipts-inv.sales_units==inv.closing_inventory).all()),
      'valid_foreign_keys': bool(inv.product_id.isin(products.product_id).all() and inv.store_id.isin(stores.store_id).all()),
      'fulfilled_plus_unmet_equals_demand': bool((inv.sales_units.to_numpy()+demand.simulated_unmet_demand_units.to_numpy()==demand.observed_demand_units.to_numpy()).all()),
      'stockout_flag_matches_unmet': bool((inv.observed_stockout_flag.to_numpy()==(demand.simulated_unmet_demand_units.to_numpy()>0)).all()),
      'continuous_daily_inventory': bool((inv.groupby(['store_id','product_id']).closing_inventory.shift(1).dropna().to_numpy()==inv.loc[inv.groupby(['store_id','product_id']).cumcount()>0,'opening_inventory'].to_numpy()).all()),
      'valid_order_dates': bool((pd.to_datetime(orders.expected_delivery_date)>=pd.to_datetime(orders.order_date)).all()),
    }
    if not all(rules.values()): raise ValueError(f'Validation failed: {rules}')
    return dict(rows=len(inv),rejected_rows=0,rules=rules,checks_passed=sum(rules.values()))

def run(output):
    output=Path(output); data_dir=output/'data'; result_dir=output/'results'
    data_dir.mkdir(parents=True,exist_ok=True); result_dir.mkdir(parents=True,exist_ok=True)
    stores,products,suppliers,bridge,demand,lead=generate()
    baseline,orders,policy,baseline_metrics=simulate(demand,lead,products)
    inv=baseline.drop(columns=['demand_units','simulated_unmet_demand_units','policy'])
    dem=baseline[['date','store_id','product_id','demand_units','simulated_unmet_demand_units']].rename(columns={'demand_units':'observed_demand_units'})
    dem['demand_source']='synthetic'
    quality=validate(inv,dem,products,stores,orders)
    frames=dict(stores=stores,products=products,suppliers=suppliers,product_suppliers=bridge,daily_inventory=inv,daily_demand=dem,purchase_orders=orders,inventory_policy=policy)
    db=output/'inventory.sqlite'; db.unlink(missing_ok=True)
    con=sqlite3.connect(db)
    for name,frame in frames.items():
        frame.to_csv(data_dir/f'{name}.csv',index=False); frame.to_sql(name,con,index=False)
    sku_results=pd.read_sql_query(SQL,con); cats=pd.read_sql_query(CATEGORY_SQL,con)
    con.close(); sku_results.to_csv(result_dir/'stockout_by_store_sku.csv',index=False); cats.to_csv(result_dir/'category_summary.csv',index=False)
    (output/'executed-analysis.sql').write_text(SQL+'\n\n'+CATEGORY_SQL+'\n')
    forecasts,forecast_rows=forecast(demand); forecast_rows.to_csv(result_dir/'forecast_predictions.csv',index=False)
    pd.DataFrame(forecasts).to_csv(result_dir/'forecast_scores.csv',index=False)
    means=demand[:TRAIN_DAYS].mean(axis=0); stds=demand[:TRAIN_DAYS].std(axis=0,ddof=1)
    comparison=[]; simulation_rows=[]; robustness=[]
    for name in ['Baseline','Reorder point','Periodic review']:
        df,po,settings,metric=simulate(demand,lead,products,name,TRAIN_DAYS,DAYS,means,stds)
        comparison.append(metric); simulation_rows.append(df)
        po.to_csv(result_dir/f'{name.lower().replace(" ","_")}_orders.csv',index=False)
        settings.to_csv(result_dir/f'{name.lower().replace(" ","_")}_settings.csv',index=False)
    pd.concat(simulation_rows).to_csv(result_dir/'policy_daily_records.csv',index=False)
    pd.DataFrame(comparison).to_csv(result_dir/'policy_comparison.csv',index=False)
    for seed in [101,202,303,404,505]:
        *_,rd,rl=generate(seed)
        for name in ['Baseline','Reorder point','Periodic review']:
            _,_,_,metric=simulate(rd,rl,products,name,TRAIN_DAYS,DAYS,means,stds)
            robustness.append(dict(seed=seed,**metric))
    pd.DataFrame(robustness).to_csv(result_dir/'robustness.csv',index=False)
    robustness_summary=pd.DataFrame(robustness).groupby('policy')[['fill_rate_pct','operating_cost','avg_inventory_value']].mean().round(2).reset_index().to_dict('records')
    daily=baseline.merge(products[['product_id','category','unit_cost','selling_price']],on='product_id')
    daily['inventory_value']=daily.closing_inventory*daily.unit_cost
    daily['sales_value']=daily.sales_units*daily.selling_price
    daily['exposure']=daily.simulated_unmet_demand_units*daily.selling_price
    grouped=daily.groupby(['date','store_id','category']).agg(demand_units=('demand_units','sum'),sales_units=('sales_units','sum'),unmet_units=('simulated_unmet_demand_units','sum'),stockout_days=('observed_stockout_flag','sum'),observations=('product_id','count'),inventory_value=('inventory_value','sum'),sales_value=('sales_value','sum'),exposure=('exposure','sum')).reset_index()
    grouped.to_csv(result_dir/'dashboard_daily.csv',index=False)
    inventory_risk=[]
    for (s,p),rows in daily.groupby(['store_id','product_id']):
        mu=rows.sales_units.mean(); closing=int(rows.closing_inventory.iloc[-1]); target=int(policy[(policy.store_id==s)&(policy.product_id==p)].target_stock.iloc[0])
        inventory_risk.append(dict(store_id=int(s),product_id=int(p),sku=f'SKU-{p:03}',closing_inventory=closing,days_of_supply=round(closing/mu,2) if mu else None,excess_units=max(0,closing-target),excess_value=round(max(0,closing-target)*float(products.unit_cost.iloc[p-1]),2)))
    pd.DataFrame(inventory_risk).to_csv(result_dir/'inventory_risk.csv',index=False)
    result=dict(provenance='Completed offline analysis of synthetic data; not actual Home Depot results.',analyst='Melvin Cuffee',seed=SEED,period='2026-01-01 to 2026-03-01',training_period='2026-01-01 to 2026-02-09',test_period='2026-02-10 to 2026-03-01',engine=f'SQLite {sqlite3.sqlite_version}',quality=quality,baseline=baseline_metrics,categories=cats.to_dict('records'),sku_results=sku_results.to_dict('records'),forecasts=forecasts,policies=comparison,robustness=robustness_summary,daily=grouped.to_dict('records'),inventory_risk=inventory_risk,table_counts={k:len(v) for k,v in frames.items()},assumptions=dict(annual_carrying_rate=CARRY_RATE,order_cost=ORDER_COST,lead_time_mean_days=[3,4,5],lead_time_std_days=1,safety_factor=1.65,backorders=False))
    (output/'results.json').write_text(json.dumps(result,indent=2,allow_nan=False)+'\n')
    manifest={str(f.relative_to(output)):hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted(output.rglob('*')) if f.is_file() and f.name!='manifest.json' and f.suffix not in ['.zip']}
    (output/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
    print(json.dumps({k:result[k] for k in ['quality','baseline','forecasts','policies','robustness']},indent=2))
    return result

if __name__=='__main__':
    parser=argparse.ArgumentParser(); parser.add_argument('--output',default=str(Path(__file__).parent)); args=parser.parse_args(); run(args.output)
