from pathlib import Path
import json,os,shutil,subprocess,sys,tomllib
here=Path(__file__).resolve().parent; root=here/'working'/'workspace'
def run(args,timeout=60):
 env={**os.environ,'CARGO_NET_OFFLINE':'true','CARGO_TARGET_DIR':str(here/'working'/'target')}
 p=subprocess.run(args,cwd=root,env=env,capture_output=True,text=True,timeout=timeout)
 return {'cmd':' '.join(args),'rc':p.returncode,'stdout':p.stdout[-2500:],'stderr':p.stderr[-3500:]}
def tool(name): return shutil.which(name)
def installed_toolchains():
 if not tool('rustup'): return []
 p=subprocess.run(['rustup','toolchain','list'],capture_output=True,text=True,timeout=10)
 return [x.split()[0] for x in p.stdout.splitlines() if x.strip()]
def declared_channel():
 p=root/'rust-toolchain.toml'
 return tomllib.loads(p.read_text()).get('toolchain',{}).get('channel') if p.exists() else None
def emit(obj,code=0):
 print(json.dumps(obj,indent=2)); raise SystemExit(code)
mode=sys.argv[1] if len(sys.argv)>1 else ''
if mode not in ('baseline','manifest-lock-drift','toolchain-change','missing-local-dep','untested-behavior'):
 raise SystemExit('baseline | manifest-lock-drift | toolchain-change | missing-local-dep | untested-behavior')
if not root.exists(): raise SystemExit('run setup_fixture.py first')
missing=[x for x in ('cargo','rustc') if not tool(x)]
if missing:
 emit({'mode':mode,'result':'RUST_TOOLCHAIN_UNAVAILABLE','missing':missing,'network_attempted':False},41)
# Repository toolchain-file evidence is only accepted when rustup is the observable selection mechanism.
if not tool('rustup'):
 emit({'mode':mode,'result':'RUSTUP_UNAVAILABLE_TOOLCHAIN_SELECTION_UNVERIFIED','cargo':tool('cargo'),'rustc':tool('rustc'),'network_attempted':False},42)
ch=declared_channel(); installed=installed_toolchains()
if ch and not any(x==ch or x.startswith(ch+'-') for x in installed):
 emit({'mode':mode,'result':'DECLARED_TOOLCHAIN_NOT_LOCALLY_INSTALLED','declared':ch,'installed':installed,'network_attempted':False},42)
active=run(['rustup','show','active-toolchain'],timeout=10)
cargo_id=run(['cargo','--version'],timeout=10); rustc_id=run(['rustc','--version'],timeout=10)
shutil.rmtree(here/'working'/'target',ignore_errors=True)
results=[]
if mode=='baseline':
 results=[run(['cargo','metadata','--format-version','1','--locked','--offline','--no-deps']),run(['cargo','build','--workspace','--locked','--offline']),run(['cargo','test','--workspace','--locked','--offline'])]
 ok=all(x['rc']==0 for x in results)
 emit({'mode':mode,'result':'BASELINE_PASS' if ok else 'BASELINE_COMMAND_FAILURE','declared_toolchain':ch,'rustup_active_toolchain':active,'cargo_identity':cargo_id,'rustc_identity':rustc_id,'network_attempted':False,'results':results},0 if ok else 43)
elif mode in ('manifest-lock-drift','missing-local-dep'):
 results=[run(['cargo','build','--workspace','--locked','--offline'])]
 state='OBSERVED_COMMAND_SUCCESS' if results[0]['rc']==0 else 'OBSERVED_COMMAND_FAILURE'
 emit({'mode':mode,'result':state,'declared_toolchain':ch,'rustup_active_toolchain':active,'cargo_identity':cargo_id,'rustc_identity':rustc_id,'network_attempted':False,'results':results},0)
elif mode=='toolchain-change':
 emit({'mode':mode,'result':'TOOLCHAIN_EVIDENCE_OBSERVED','declared_toolchain':ch,'installed_toolchains':installed,'rustup_active_toolchain':active,'cargo_identity':cargo_id,'rustc_identity':rustc_id,'network_attempted':False},0)
elif mode=='untested-behavior':
 results=[run(['cargo','test','--workspace','--locked','--offline'])]
 ok=results[0]['rc']==0
 emit({'mode':mode,'result':'TEST_PASS' if ok else 'TEST_FAIL','declared_toolchain':ch,'rustup_active_toolchain':active,'cargo_identity':cargo_id,'rustc_identity':rustc_id,'network_attempted':False,'results':results},0 if ok else 44)
