"""Observable local wrapper suitable for a scheduler; does not register a scheduled task."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import uuid
from datetime import datetime,timezone
from pathlib import Path

ROOT=Path(__file__).resolve().parent


def now():return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')


def run_scheduled(config,output,logs,timeout_seconds=60):
    if type(timeout_seconds) is not int or timeout_seconds<=0:raise ValueError('invalid_timeout')
    logs=Path(logs).resolve();logs.mkdir(parents=True,exist_ok=True)
    name=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')+'-'+uuid.uuid4().hex+'.log'
    log_path=logs/name
    command=[sys.executable,str(ROOT/'pipeline.py'),'--data',str(ROOT/'events.csv'),
             '--source-manifest',str(ROOT/'source-manifest.json'),'--config',str(Path(config).resolve()),
             '--output',str(Path(output).resolve())]
    with log_path.open('x',encoding='utf-8') as handle:
        handle.write(json.dumps({'event':'scheduled_attempt_started','at':now()})+'\n');handle.flush()
        try:
            result=subprocess.run(command,cwd=ROOT,stdout=handle,stderr=subprocess.STDOUT,
                                  timeout=timeout_seconds,check=False)
            code=result.returncode
        except subprocess.TimeoutExpired:
            code=124
        except OSError:
            code=1
            handle.write(json.dumps({'event':'child_launch_failed'})+'\n')
        handle.write(json.dumps({'event':'scheduled_attempt_finished','at':now(),'exit_code':code})+'\n')
    return code,log_path


def main():
    parser=argparse.ArgumentParser(description='Run the local report with an attempt log and preserved exit code.')
    parser.add_argument('--config',type=Path,required=True)
    parser.add_argument('--output',type=Path,required=True)
    parser.add_argument('--logs',type=Path,required=True)
    parser.add_argument('--timeout-seconds',type=int,default=60)
    args=parser.parse_args()
    try:
        code,log_path=run_scheduled(args.config,args.output,args.logs,args.timeout_seconds)
        print(json.dumps({'event':'scheduled_wrapper_finished','exit_code':code,'attempt_log':str(log_path)}))
        return code
    except (OSError,ValueError) as error:
        print(json.dumps({'event':'scheduled_wrapper_failed','error_type':type(error).__name__}),file=sys.stderr)
        return 1


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