"""One owner-host command for schedule installation and an authorized push test.

No broker token loading, market orders, ledger writes or trial activation.
Installed schedules and actual device delivery are separate observations.
"""
import argparse,importlib,json,subprocess,sys
from pathlib import Path
from datetime import datetime
from infinbot_common import private_read,strict_json,atomic_json,timestamp
from infinbot_schedule import install_schedule

def main(argv=None):
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--config',required=True)
    parser.add_argument('--install-schedules',action='store_true')
    parser.add_argument('--send-test',action='store_true')
    parser.add_argument('--notification-credentials',help='Existing private notifier file; no inline secrets')
    args=parser.parse_args(argv)
    report={'product':'InFinBot','observed_at':timestamp(),'schedules':'NOT_ATTEMPTED' if args.install_schedules else 'NOT_REQUESTED',
            'device_delivery':'NOT_ATTEMPTED' if args.send_test else 'NOT_REQUESTED','broker_orders_submitted':0,
            'schedules_requested':args.install_schedules,'notification_test_requested':args.send_test,
            'private_broker_credentials_loaded':False,'first_scheduled_run_verified':False}
    try:
        if sys.platform!='darwin':raise ValueError('Intended Mac host required')
        config_path=Path(args.config).absolute();config=strict_json(private_read(config_path))
        root=Path(__file__).resolve().parent
        if args.install_schedules:
            try:
                # Verify that this exact interpreter can import each scheduled job.
                for module in ('infinbot_backup','infinbot_acceptance','infinbot_archive_job'):importlib.import_module(module)
                report['scheduled_job_imports_verified']=True
                report['schedule_result']=install_schedule(config_path);report['schedules']='INSTALLED_AND_READ_BACK'
            except Exception:report['schedules']='BLOCKED_OR_UNCONFIRMED'
        if args.send_test:
            credentials=args.notification_credentials or config.get('notification_credentials_file') or str(root/'notification_credentials.json')
            # A timeout after provider acceptance is never automatically retransmitted.
            process=subprocess.run([sys.executable,str(root/'infinbot_notify_check.py'),
                '--config',str(config_path),'--credentials',credentials,'--send-test'])
            if process.returncode==0:
                result=strict_json(private_read(config['notification_receipt_file']))
                if (result.get('device_delivery')=='OWNER_CONFIRMED' and result.get('api_status')=='API_ACCEPTED'
                    and datetime.fromisoformat(result['observed_at'])>=datetime.fromisoformat(report['observed_at'])):
                    report['device_delivery']='OWNER_CONFIRMED';report['notification_result']=result
                else:report['device_delivery']='UNVERIFIED'
            else:report['device_delivery']='BLOCKED_OR_UNCONFIRMED'
        if not args.install_schedules and not args.send_test:
            report['status']='NO_OPERATION_REQUESTED'
        else:
            ok=(not args.install_schedules or report['schedules']=='INSTALLED_AND_READ_BACK') and (not args.send_test or report['device_delivery']=='OWNER_CONFIRMED')
            report['status']='REQUESTED_HOST_OPERATIONS_VERIFIED' if ok else 'HOST_OPERATIONS_UNVERIFIED'
        from uuid import uuid4
        atomic_json(Path(config['receipt_dir'])/('infinbot_operations_'+uuid4().hex+'.json'),report)
    except Exception:report['status']='HOST_OPERATIONS_UNAVAILABLE';report['reason']='Intended Mac configuration or receipt location unavailable; no success inferred'
    print(json.dumps(report,indent=2))
    return 0 if report['status']=='REQUESTED_HOST_OPERATIONS_VERIFIED' else 1

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