import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import tarfile
import tempfile

os.umask(0o077)
repo=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
out=Path('/data/contextra/deployment-artifacts/model-config-fix-c44f3f8-r01')
out.mkdir(mode=0o700)
name='contextra-model-config-fix-r01'
files={'deployctl':(repo/'deployctl').read_bytes(),
       'GUIDE.ko.md':(repo/'docs/deployment/MODEL_CONFIG_REPAIR.ko.md').read_bytes()}
for p in sorted((repo/'deployment_kit').glob('*.py')):files['deployment_kit/'+p.name]=p.read_bytes()
sums=''.join(hashlib.sha256(data).hexdigest()+'  '+path+'\n' for path,data in sorted(files.items()))
files['SHA256SUMS']=sums.encode()
archive=out/(name+'.tar.gz')
with archive.open('xb') as raw,tarfile.open(fileobj=raw,mode='w:gz',compresslevel=1) as tar:
    for path,data in sorted(files.items()):
        info=tarfile.TarInfo(name+'/'+path);info.size=len(data);info.mode=0o755 if path=='deployctl' else 0o644
        tar.addfile(info,io.BytesIO(data))
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as td:
    with tarfile.open(archive) as tar:
        for m in tar:
            rel=m.name.removeprefix(name+'/')
            assert m.isfile() and rel in files and tar.extractfile(m).read()==files[rel]
        tar.extractall(td,filter='data')
    r=subprocess.run(['python3','-B',str(Path(td)/name/'deployctl'),'--help'],capture_output=True,timeout=10)
    assert r.returncode==0,r.stderr
digest=hashlib.sha256(archive.read_bytes()).hexdigest()
(out/(archive.name+'.sha256')).write_text(digest+'  '+archive.name+'\n')
result={'archive':str(archive),'bytes':archive.stat().st_size,'sha256':digest,'files':len(files),
        'source_head':subprocess.check_output(['git','-C',str(repo),'rev-parse','HEAD'],text=True).strip(),
        'snapshot':'exact worktree deployment_kit + deployctl; standalone repair tools, not a FULL release',
        'tests':'26 targeted PASS; actual protobuf12 configs PASS; archive members and standalone help PASS',
        'remote':'SSH read-only connected; sudo unavailable; no target mutation',
        'runtime_changes':0,'full_rebuilt':False,'image_rebuilt':False,'target_smoke':'NOT_RUN'}
(Path(__file__).parent/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2))
print(json.dumps(result,ensure_ascii=False,indent=2))
