"""Configure existing host inputs; make new operational secrets privately, no trading ledger."""
import argparse,json,os,secrets,sys
from pathlib import Path
from infinbot_common import private_dir,atomic_json,readonly_db,Rejected,private_read
from risk_state import RiskState


def secret(path):
    if path.exists():private_read(path,1024);return
    fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
    with os.fdopen(fd,'w') as f:f.write(secrets.token_urlsafe(48)+'\n');f.flush();os.fsync(f.fileno())


def configure(project,db_path,export_path,credentials_file,worker_scope,backup_dir=None):
    project=Path(project).absolute();db=Path(db_path).absolute()
    with readonly_db(db):pass
    private=private_dir(project/'private');receipt_dir=private_dir(private/'receipts')
    state=private/'infinbot-risk-state.sqlite3'
    if not state.exists():RiskState(state,initialize=True)
    else:RiskState(state).status()
    token=private/'infinbot-gateway-token.txt';password=private/'infinbot-archive-password.txt'
    secret(token);secret(password)
    output=private/'infinbot-host.json'
    config={'product':'InFinBot','schema_version':1,'db_path':str(db),'export_path':str(Path(export_path).absolute()),
            'credentials_file':str(Path(credentials_file).absolute()),'worker_scope':worker_scope,
            'risk_state':str(state),'gateway_token_file':str(token),'archive_password_file':str(password),
            'risk_config_out':str(private/'infinbot-risk-policy.json'),
            'receipt_dir':str(receipt_dir),'backup_dir':str(Path(backup_dir).absolute()) if backup_dir else str(private/'encrypted-backups'),
            'notification_receipt_file':str(private/'notification-delivery-receipt.json'),
            'live_execution_enabled':False,'entry_allocation':'0.0000'}
    if output.exists():
        previous=json.loads(private_read(output))
        if previous!=config:raise Rejected('Existing host configuration differs; preserved for review')
    else:atomic_json(output,config)
    return output


def choose_file(title):
    # Host-only Finder selection avoids guessing a ledger/credential path.
    import subprocess
    script='POSIX path of (choose file with prompt '+json.dumps(title)+')'
    p=subprocess.run(['osascript','-e',script],capture_output=True,text=True)
    if p.returncode:raise Rejected('File selection cancelled')
    return p.stdout.strip()


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--project',default=str(Path(__file__).resolve().parent))
    p.add_argument('--db-path');p.add_argument('--export-path');p.add_argument('--credentials-file')
    p.add_argument('--worker-scope');p.add_argument('--backup-dir');args=p.parse_args()
    try:
        if sys.version_info<(3,10):raise Rejected('Python 3.10 or newer required for the tested gateway dependencies')
        values=[args.db_path,args.export_path,args.credentials_file]
        if any(x is None for x in values):
            if sys.platform!='darwin' or not sys.stdin.isatty():raise Rejected('Supply paths or use Finder setup in a Mac terminal')
            titles=['Select your CURRENT persistent simulation ledger (not a test snapshot)',
                    'Select the CURRENT exported disposition JSON (do not create mock rows)',
                    'Select your PRIVATE PAPER credentials file (not a folder)']
            values=[value or choose_file(title) for value,title in zip(values,titles)]
        scope=args.worker_scope
        if not scope:
            if not sys.stdin.isatty():raise Rejected('Explicit recorded worker scope required')
            scope=input('Recorded worker execution tag (exact value): ').strip()
        if not scope:raise Rejected('Nonempty recorded scope required')
        result=configure(args.project,*values,scope,args.backup_dir)
        print(json.dumps({'status':'HOST_PATHS_CONFIGURED','product':'InFinBot','config_path':str(result),
                          'broker_credentials_created':False,'operational_secrets_created_privately':True,
                          'ledger_seeded':False,'live_execution_enabled':False,'schedules_installed':False},indent=2));return 0
    except Exception:
        print(json.dumps({'status':'SETUP_BLOCKED','reason':'Check existing files, private directory permissions and explicit worker scope; no ledger created or reset'}));return 1


if __name__=='__main__':raise SystemExit(main())
