#!/usr/bin/env python3
"""Read-only CLI presence/version probe. Not an authorization or security audit.

The helper does not request installs, logins, model prompts or deployments.
Invoked CLIs or version manager shims may have their own side effects.
Run without sudo. Output omits raw command output, environment and credentials.
"""
from __future__ import annotations
import argparse,datetime,json,os,pathlib,re,shutil,socket,subprocess,sys,unittest
from unittest import mock
COMMANDS={
 'git':['git','--version'],'python':['python3','--version'],
 'node':['node','--version'],'docker':['docker','--version'],
 'compose':['docker','compose','version'],'claude':['claude','--version'],
 'codex':['codex','--version'],'gh':['gh','--version'],
 'netlify':['netlify','--version'],'wrangler':['wrangler','--version'],
 'deno':['deno','--version'],'tmux':['tmux','-V'],
}
VERSION=re.compile(r'(?<![0-9])v?([0-9]+\.[0-9]+(?:\.[0-9]+)?[a-z]?)(?![0-9])')

def inspect_command(name:str,timeout:int=15,cwd=None)->dict:
 argv=COMMANDS[name];path=shutil.which(argv[0])
 if path is None:return {'tool':name,'state':'missing','version':None}
 env=os.environ.copy();env.update(CI='1',NO_COLOR='1',DO_NOT_TRACK='1',NETLIFY_TELEMETRY_DISABLED='1',WRANGLER_SEND_METRICS='false',CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC='1')
 try:
  result=subprocess.run([path,*argv[1:]],capture_output=True,text=True,timeout=timeout,env=env,stdin=subprocess.DEVNULL,cwd=cwd)
  match=VERSION.search(result.stdout+'\n'+result.stderr)
  return {'tool':name,'state':'version-returned' if result.returncode==0 and match else 'check-failed','version':match.group(1) if match else None,'exit_code':result.returncode}
 except subprocess.TimeoutExpired:return {'tool':name,'state':'timed-out','version':None}
 except OSError:return {'tool':name,'state':'execution-error','version':None}

def save_new(path:pathlib.Path,data:dict)->None:
 # Refuse overwrite: a mistyped output must not destroy an existing file.
 fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
 with os.fdopen(fd,'w',encoding='utf-8') as output:json.dump(data,output,indent=2);output.write('\n')

class SelfTests(unittest.TestCase):
 def test_missing(self):
  with mock.patch('shutil.which',return_value=None):self.assertEqual(inspect_command('git')['state'],'missing')
 def test_version_without_raw_output(self):
  result=subprocess.CompletedProcess([],0,'git version 2.50.0\nPRIVATE_SENTINEL','')
  with mock.patch('shutil.which',return_value='/fixture/git'),mock.patch('subprocess.run',return_value=result):
   row=inspect_command('git');self.assertEqual(row['version'],'2.50.0');self.assertNotIn('PRIVATE_SENTINEL',json.dumps(row))
 def test_nonzero(self):
  with mock.patch('shutil.which',return_value='/fixture/git'),mock.patch('subprocess.run',return_value=subprocess.CompletedProcess([],1,'version 2.50.0','')):self.assertEqual(inspect_command('git')['state'],'check-failed')
 def test_timeout(self):
  with mock.patch('shutil.which',return_value='/fixture/git'),mock.patch('subprocess.run',side_effect=subprocess.TimeoutExpired(['git'],15)):self.assertEqual(inspect_command('git')['state'],'timed-out')
 def test_absent_version_not_success(self):
  with mock.patch('shutil.which',return_value='/fixture/git'),mock.patch('subprocess.run',return_value=subprocess.CompletedProcess([],0,'nothing','')):self.assertEqual(inspect_command('git')['state'],'check-failed')
 def test_no_shell(self):
  with mock.patch('shutil.which',return_value='/fixture/git'),mock.patch('subprocess.run',return_value=subprocess.CompletedProcess([],0,'git version 2.50.0','')) as run:
   inspect_command('git');self.assertNotIn('shell',run.call_args.kwargs);self.assertEqual(run.call_args.args[0],['/fixture/git','--version'])
 def test_refuse_overwrite(self):
  import tempfile
  with tempfile.TemporaryDirectory() as directory:
   path=pathlib.Path(directory)/'receipt.json';save_new(path,{'first':True})
   with self.assertRaises(FileExistsError):save_new(path,{'second':True})
   self.assertEqual(json.loads(path.read_text()),{'first':True})

def main()->int:
 parser=argparse.ArgumentParser(description=__doc__)
 parser.add_argument('--project',type=pathlib.Path,default=pathlib.Path.cwd())
 parser.add_argument('--output',type=pathlib.Path)
 parser.add_argument('--require',action='append',choices=sorted(COMMANDS),default=[])
 parser.add_argument('--self-test',action='store_true');args=parser.parse_args()
 if args.self_test:
  result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(SelfTests));return 0 if result.wasSuccessful() else 1
 if not args.project.is_dir():parser.error('Project must be an existing directory')
 results=[inspect_command(name,cwd=args.project.resolve()) for name in COMMANDS]
 required=all(row['state']=='version-returned' for row in results if row['tool'] in args.require)
 report={'checked_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'hostname':socket.gethostname(),'project':str(args.project.resolve()),'checks':results,'required_tools':args.require,'required_checks_passed':required,'state':'inventory-complete','not_tested':['provider authorization','every CLI function','billing','model inference','container health','application integration','production deployment','security certification','resilience','recovery after interruption','detached execution'],'model_prompts_sent':0,'credential_files_read_by_helper':False,'subcommand_side_effects_audited':False}
 if args.output:
  try:save_new(args.output,report)
  except OSError as error:parser.error('Cannot create a new private output file: '+str(error))
 print(json.dumps(report,indent=2));return 0 if required else 1
if __name__=='__main__':raise SystemExit(main())
