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

def h(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def 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)
    return json.loads(p.stdout) if p.returncode==0 else {'identity_error':p.stderr[-1000:],'rc':p.returncode}

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

wheels=sorted((root/'wheelhouse').glob('*.whl')) if root.exists() else []
artifacts=[{'name':p.name,'sha256':h(p)} for p in wheels]
canonical=''.join(f"{x['name']}\t{x['sha256']}\n" for x in artifacts).encode('utf-8')
uv=shutil.which('uv')
vp=venv_python()
out={
 'launcher_python_identity':identity(sys.executable),
 'selected_environment_python_identity':identity(vp) if vp.exists() else None,
 'uv_executable':uv,
 'uv_version':subprocess.run([uv,'--version'],capture_output=True,text=True).stdout.strip() if uv else 'UV_UNAVAILABLE',
 'pyproject_hash':h(root/'pyproject.toml') if root.exists() else None,
 'uv_lock_hash':h(root/'uv.lock') if root.exists() else None,
 'artifact_inventory_algorithm':'sha256(sorted UTF-8 lines: name<TAB>sha256<LF>)',
 'artifact_inventory_hash':hashlib.sha256(canonical).hexdigest(),
 'artifacts':artifacts
}
print(json.dumps(out,indent=2))
