import hashlib
import json
import os
from pathlib import Path
import subprocess
import urllib.request

ROOT=Path(__file__).resolve().parents[1]
REV='823ca54bbf1446173f6906198a5e8b2a3e090890'
os.umask(0o077)
def digest(p):
    h=hashlib.sha256()
    with p.open('rb') as f:
        for block in iter(lambda:f.read(1024*1024),b''):h.update(block)
    return h.hexdigest()
meta=json.load(urllib.request.urlopen('https://huggingface.co/api/models/Awiros/person_and_head_detection/revision/'+REV+'?blobs=true',timeout=20))
entry=next(x for x in meta['siblings'] if x['rfilename']=='ckpts/rf-detrs/checkpoint_best_total.safetensors')
weight=ROOT/'source/checkpoint_best_total.safetensors'
assert digest(weight)==entry['lfs']['sha256'] and weight.stat().st_size==entry['size']
official=ROOT/'source/official';official.mkdir(exist_ok=False)
sources={}
for name in ('README.md','scripts/inference.py','scripts/convert_release_checkpoint.py'):
    data=urllib.request.urlopen('https://huggingface.co/Awiros/person_and_head_detection/resolve/'+REV+'/'+name,timeout=20).read()
    expected=next(x for x in meta['siblings'] if x['rfilename']==name)
    assert hashlib.sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()==expected['blobId']
    path=official/name;path.parent.mkdir(exist_ok=True)
    with path.open('xb') as f:f.write(data)
    sources[name]=digest(path)
env=Path('/data/contextra/model-artifacts/tool-envs/medium-193-20260909/venv/lib/python3.12/site-packages')
direct=json.loads((env/'rfdetr-1.9.3.dist-info/direct_url.json').read_text())
code={str(p.relative_to(env)):digest(p) for p in sorted((env/'rfdetr').rglob('*.py'))}
image=json.loads(subprocess.check_output(['docker','image','inspect','contextra-model-tooling:icerti-80ad438-20260919-r01']))[0]['Id']
gpu=subprocess.check_output(['nvidia-smi','--query-gpu=name,uuid,driver_version,memory.total,memory.used,utilization.gpu','--format=csv'],text=True)
containers=json.loads(subprocess.check_output(['docker','inspect',*subprocess.check_output(['docker','ps','-q'],text=True).split()]))
manifest=dict(status='SOURCE_VERIFIED_EXPORT_PENDING',source=dict(repository='Awiros/person_and_head_detection',
    verified_revision=REV,download_revision='UNKNOWN; uploaded file matches verified revision',
    path=str(weight),sha256=digest(weight),size=weight.stat().st_size,license_model_card='Apache-2.0',official_files=sources),
    exporter=dict(image=image,rfdetr_version='1.9.3',rfdetr_origin=direct,rfdetr_code_sha256=hashlib.sha256(json.dumps(code,sort_keys=True).encode()).hexdigest()),
    target_gpu=gpu,requested=dict(input_dtype='FP16',optimization='FP16',output_dtype='FP32',batch=[1,4,4]),
    accuracy='NOT_RUN_USER_VISUAL',runtime_registration='NOT_RUN')
for name,value in [('manifest.intake.json',manifest),('exporter-source-hashes.json',code),
                   ('containers.before.json',{c['Name']:{'id':c['Id'],'image':c['Image'],'started_at':c['State']['StartedAt']} for c in containers})]:
    with (ROOT/name).open('x') as f:json.dump(value,f,indent=2)
print(json.dumps({'source_verified':True,'revision':REV,'image':image}))
