#!/usr/bin/env python3
"""Finite integer pilot portfolio; Python3.9+ standard library."""
from pathlib import Path
import json,sys
p=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).resolve().parent
case=json.loads((p/'case.json').read_text(encoding='utf-8'));a,b=case['segments'];out={}
for scenario in case['scenarios']:
 assert scenario['implementation_hours']>=0 and case['sales_hours']>=0
 feasible=[]
 for na in range(a['eligible_committed_accounts']+1):
  for nb in range(b['eligible_committed_accounts']+1):
   sales=na*a['sales_h']+nb*b['sales_h'];impl=na*a['implementation_h']+nb*b['implementation_h'];contribution=na*(a['pilot_fee']-a['variable_cost'])+nb*(b['pilot_fee']-b['variable_cost'])
   if sales<=case['sales_hours'] and impl<=scenario['implementation_hours']:feasible.append({'A':na,'B':nb,'sales_h':sales,'implementation_h':impl,'contribution_RUB':contribution})
 best=max(x['contribution_RUB'] for x in feasible);leaders=[x for x in feasible if x['contribution_RUB']==best]
 out[scenario['name']]={'feasible':feasible,'max_contribution_RUB':best,'leaders':leaders,'launch_allowed':scenario.get('implementation_owner_confirmed',True),'decision':'capacity plan only; no launch without confirmed owner' if not scenario.get('implementation_owner_confirmed',True) else 'ready subject to all supplied gates'}
(p/'result.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8');print(json.dumps({k:{'best':v['leaders'],'launch_allowed':v['launch_allowed']} for k,v in out.items()},ensure_ascii=False))
