"""Start the installed local owner gateway and bounded zero-entry observer processes."""
import argparse,json,os,subprocess,sys,uuid
from pathlib import Path
from infinbot_common import private_read,strict_json,private_dir,Rejected,atomic_json,timestamp
from risk_state import RiskState


def start(config):
    root=Path(__file__).resolve().parent;state=RiskState(config['risk_state']).status()
    if state['deadline_expired']:raise Rejected('Observation window expired; explicit review required; entries stay frozen')
    logs=private_dir(Path(config['receipt_dir']).parent/'runtime-logs')
    processes=[]
    commands=[['consigliere_server.py','--token-file',config['gateway_token_file'],'--state-path',config['risk_state'],'--db-path',config['db_path']],
              ['infinbot_dashboard_server.py']]
    for worker in ('bot-worker-crypto','bot-worker-futures'):
        commands.append(['runtime/worker.py','--worker',worker,'--db-path',config['db_path'],'--state-path',config['risk_state']])
    receipt=Path(config['receipt_dir'])/('infinbot_runtime_'+uuid.uuid4().hex+'.json')
    try:
        for command in commands:
            log=logs/(Path(command[0]).stem+'_'+uuid.uuid4().hex+'.log')
            fd=os.open(log,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
            with os.fdopen(fd,'w') as f:
                process=subprocess.Popen([sys.executable,str(root/command[0]),*command[1:]],stdout=f,stderr=f,start_new_session=True)
            processes.append(process)
        # Poll startup, without claiming services are ready just because PIDs exist.
        import time
        time.sleep(.5)
        if any(p.poll() is not None for p in processes):raise Rejected('A component exited during startup')
        result={'status':'LOCAL_PROCESSES_STARTED_READINESS_UNVERIFIED','product':'InFinBot','observed_at':timestamp(),
                'pids':[p.pid for p in processes],'gateway_bind':'127.0.0.1:8765','console_bind':'127.0.0.1:8766',
                'live_execution_enabled':False,'entry_allocation':'0.0000','persistent_market_stream_verified':False,
                'scope':'Owner gateway and ledger observers; not a trading trial'}
        atomic_json(receipt,result);return result
    except Exception:
        for p in processes:
            if p.poll() is None:p.terminate()
        raise


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--config',required=True);args=p.parse_args()
    try:print(json.dumps(start(strict_json(private_read(args.config))),indent=2))
    except Exception:print(json.dumps({'status':'LOCAL_RUNTIME_START_BLOCKED','live_execution_enabled':False}));raise SystemExit(1)
