"""Record a post-run environment observation, without authentication reads or inference."""
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime,timezone
import importlib.metadata
import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import sys

from download_evidence import digest
from publish_evidence import SUSPICIOUS


def cli(name):
 path=shutil.which(name)
 if not path:return {'name':name,'available':False}
 record={'name':name,'executable':path,'executable_sha256_at_observation':digest(path)}
 try:
  result=subprocess.run([path,'--version'],capture_output=True,text=True,encoding='utf-8',errors='replace',timeout=15,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0)
  record.update(return_code=result.returncode,version_output=result.stdout.strip()[:2000],stderr=result.stderr.strip()[:2000])
 except subprocess.TimeoutExpired:record['observation_error']='Version command exceeded 15 seconds.'
 return record


if __name__=='__main__':
 with ThreadPoolExecutor(max_workers=3) as pool:versions=list(pool.map(cli,['codex','claude','agy']))
 packages={name:importlib.metadata.version(name) for name in ['a2a-sdk','numpy','scipy','matplotlib','pytest']}
 data={'observed_at':datetime.now(timezone.utc).isoformat(),'scope':'Post-run observation, not evidence that CLI binaries were unchanged throughout every earlier call. No provider inference or authentication-file inspection. Requested model IDs and call-level command lines are in the individual records.','python':sys.version,'platform':platform.platform(),'cli_observations':versions,'selected_python_packages':packages}
 encoded=json.dumps(data,ensure_ascii=False,indent=2).encode('utf-8')
 if any(p.search(encoded) for p in SUSPICIOUS):raise RuntimeError('Unexpected credential pattern in environment observation')
 output=Path(__file__).resolve().parent/'analysis/environment-observation.json';output.write_bytes(encoded)
 print(json.dumps({'path':str(output),'observed_cli_versions':[{'name':r['name'],'version':r.get('version_output'),'return_code':r.get('return_code')} for r in versions]},ensure_ascii=False))
