"""Neutral engineering probes only. Never include these as behavioral observations."""
import concurrent.futures
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import time

ROOT = Path(__file__).resolve().parent
PROFILES = {
    'astra': ('codex', 'gpt-6-astra', 'medium'),
    'mini': ('codex', 'gpt-5.4-mini', 'medium'),
    'fable': ('claude', 'claude-fable-5-1', 'medium'),
    'haiku': ('claude', 'claude-haiku-4-5', 'medium'),
    'pro': ('agy', 'gemini-3.1-pro-high', 'high'),
    'flash': ('agy', 'gemini-3.8-flash-low', 'low'),
}
PROMPT = 'This is a connectivity test, not a research observation. Do not use any tools, read files, or perform external actions. Reply with exactly this JSON object: {"ready":true}'

def write(path, data):
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')

def commands(profile, directory):
    provider, model, effort = PROFILES[profile]
    if provider == 'codex':
        args = [shutil.which('codex'), 'exec', '--model', model, '--ignore-user-config', '--ephemeral', '--json', '--skip-git-repo-check', '--sandbox', 'read-only', '--cd', str(directory), '--output-last-message', str(directory/'answer.txt')]
        for setting in [f'model_reasoning_effort="{effort}"', 'features.shell_tool=false', 'features.multi_agent=false', 'agents.enabled=false', 'features.apps=false', 'features.hooks=false', 'features.memories=false', 'web_search="disabled"', 'project_doc_max_bytes=0', f'model_instructions_file={json.dumps(str(ROOT/"agent-instructions.txt"))}']:
            args += ['-c', setting]
        return args + ['-']
    if provider == 'claude':
        return [shutil.which('claude'), '--print', '--model', model, '--output-format', 'json', '--safe-mode', '--tools', '', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--permission-prompts', 'none', '--no-chrome', '--no-session-persistence', '--effort', effort, '--system-prompt', (ROOT/'agent-instructions.txt').read_text(encoding='utf-8')]
    return [shutil.which('agy'), '--print', PROMPT, '--model', model, '--effort', effort, '--mode', 'plan', '--disable-slash-commands', '--output-format', 'json', '--print-timeout', '90s', '--log-file', str(directory/'agy-private.log')]

def probe(profile):
    directory=ROOT/'private'/'engineering'/profile
    directory.mkdir(parents=True, exist_ok=False)
    args=commands(profile,directory)
    (directory/'input.txt').write_text(PROMPT,encoding='utf-8')
    meta={'phase':'engineering-only','profile':profile,'provider':PROFILES[profile][0],'requested_model':PROFILES[profile][1],'command':args,'started_at':dt.datetime.now(dt.timezone.utc).isoformat()}
    write(directory/'started.json',meta)
    env=os.environ.copy()
    env['PYTHONIOENCODING']='utf-8'
    started=time.monotonic()
    try:
        p=subprocess.run(args,input='' if PROFILES[profile][0]=='agy' else PROMPT,encoding='utf-8',errors='replace',capture_output=True,cwd=directory,env=env,timeout=115)
        (directory/'stdout.txt').write_text(p.stdout,encoding='utf-8')
        (directory/'stderr.txt').write_text(p.stderr,encoding='utf-8')
        meta.update(exit_code=p.returncode,status='returned',elapsed_seconds=time.monotonic()-started)
        if PROFILES[profile][0]=='codex':
            answer=(directory/'answer.txt').read_text(encoding='utf-8') if (directory/'answer.txt').exists() else ''
            events=[]
            for line in p.stdout.splitlines():
                try: events.append(json.loads(line))
                except ValueError: pass
            meta['events']=events
        else:
            try:
                data=json.loads(p.stdout)
                meta['response_metadata']=data
                answer=data.get('result',data.get('response',''))
            except ValueError: answer=''
        meta['answer']=answer
        meta['ready']=p.returncode==0 and 'true' in str(answer).lower() and 'ready' in str(answer).lower()
    except subprocess.TimeoutExpired as e:
        for name,val in [('stdout.txt',e.stdout),('stderr.txt',e.stderr)]:
            (directory/name).write_text(val.decode('utf-8',errors='replace') if isinstance(val,bytes) else val or '',encoding='utf-8')
        meta.update(status='timeout',ready=False,elapsed_seconds=time.monotonic()-started)
    meta['ended_at']=dt.datetime.now(dt.timezone.utc).isoformat()
    write(directory/'result.json',meta)
    return {k:meta.get(k) for k in ['profile','requested_model','ready','status','elapsed_seconds','answer']}

if __name__=='__main__':
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
        jobs={pool.submit(probe,key):key for key in PROFILES}
        for job in concurrent.futures.as_completed(jobs):
            try: print(json.dumps(job.result(),ensure_ascii=False),flush=True)
            except Exception as e: print(json.dumps({'profile':jobs[job],'error':repr(e)}),flush=True)
