from pathlib import Path
import subprocess,sys,shutil,os,json,platform,sysconfig,hashlib
here=Path(__file__).resolve().parent
root=here/'working'/'project'
uv=shutil.which('uv')
UV_UNAVAILABLE_RC=23

def py_identity(exe):
    code='import sys,platform,sysconfig,json; print(json.dumps({"executable":sys.executable,"version":platform.python_version(),"implementation":platform.python_implementation(),"platform":sysconfig.get_platform(),"cache_tag":sys.implementation.cache_tag,"soabi":sysconfig.get_config_var("SOABI"),"base_prefix":sys.base_prefix}))'
    p=subprocess.run([str(exe),'-c',code],capture_output=True,text=True)
    if p.returncode != 0:
        return {'identity_error':p.stderr[-1000:],'rc':p.returncode}
    return json.loads(p.stdout)

def venv_python():
    a=root/'.venv'/'bin'/'python'
    b=root/'.venv'/'Scripts'/'python.exe'
    return a if a.exists() else b

def run_uv(args,cache):
    env={**os.environ,'UV_CACHE_DIR':str(cache)}
    cmd=[uv,*args]
    p=subprocess.run(cmd,cwd=root,env=env,capture_output=True,text=True)
    return {'rc':p.returncode,'command':cmd,'cache_dir':str(cache.resolve()),'stdout':p.stdout[-2000:],'stderr':p.stderr[-3000:]}

if not uv:
    print(json.dumps({'result':'UV_UNAVAILABLE','rc':UV_UNAVAILABLE_RC,'evidence_status':'MISSING_RUNTIME_EVIDENCE'}))
    raise SystemExit(UV_UNAVAILABLE_RC)

mode=sys.argv[1]
requested=sys.executable
if mode=='baseline':
    shutil.rmtree(root/'.venv',ignore_errors=True)
    cache=here/'working'/'cache-baseline'; shutil.rmtree(cache,ignore_errors=True)
    out=run_uv(['sync','--locked','--offline','--python',requested],cache)
    out['requested_python_identity']=py_identity(requested)
    vp=venv_python()
    out['selected_environment_python_identity']=py_identity(vp) if vp.exists() else None
    out['result']='BASELINE_SYNC_PASS' if out['rc']==0 else 'BASELINE_SYNC_FAIL'
    print(json.dumps(out,indent=2))
elif mode=='stale-locked':
    cache=here/'working'/'cache-stale'; shutil.rmtree(cache,ignore_errors=True)
    out=run_uv(['sync','--locked','--offline','--python',requested],cache)
    out['requested_python_identity']=py_identity(requested)
    out['result']='EXPECTED_STALE_LOCK_FAILURE' if out['rc']!=0 else 'UNEXPECTED_SUCCESS'
    print(json.dumps(out,indent=2))
elif mode=='warm-import':
    vp=venv_python()
    if not vp.exists():
        print(json.dumps({'result':'WARM_ENVIRONMENT_MISSING','rc':24})); raise SystemExit(24)
    p=subprocess.run([str(vp),'app.py'],cwd=root,capture_output=True,text=True)
    print(json.dumps({'rc':p.returncode,'result':'WARM_IMPORT_PASS' if p.returncode==0 else 'WARM_IMPORT_FAIL','selected_environment_python_identity':py_identity(vp),'stdout':p.stdout[-2000:],'stderr':p.stderr[-2000:]},indent=2))
elif mode=='clean-after-remove':
    shutil.rmtree(root/'.venv',ignore_errors=True)
    cache=here/'working'/'cache-missing'; shutil.rmtree(cache,ignore_errors=True)
    out=run_uv(['sync','--locked','--offline','--python',requested],cache)
    out['requested_python_identity']=py_identity(requested)
    out['result']='EXPECTED_MISSING_ARTIFACT_FAILURE' if out['rc']!=0 else 'UNEXPECTED_SUCCESS'
    print(json.dumps(out,indent=2))
else:
    raise SystemExit('baseline | stale-locked | warm-import | clean-after-remove')
