import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import tarfile

os.umask(0o077)
ROOT=Path(__file__).parent
REPO=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
def cmd(args):return subprocess.check_output(args,text=True,timeout=20)
head=cmd(['git','-C',str(REPO),'rev-parse','HEAD']).strip()
assert head=='0f172d948cacf1e4444c40ecc09d583f29644c74'
assert not cmd(['git','-C',str(REPO),'status','--porcelain']).strip()
paths=cmd(['git','-C',str(REPO),'ls-files','-z','app','control_sidecar','tests','tools','docker','deploy']).strip('\x00').split('\x00')
for relative in paths:
    source=REPO/relative
    assert source.is_file() and not source.is_symlink()
    target=ROOT/'kit'/relative
    target.parent.mkdir(parents=True,exist_ok=True)
    shutil.copyfile(source,target)
files={str(p.relative_to(ROOT/'kit')):hashlib.sha256(p.read_bytes()).hexdigest() for p in (ROOT/'kit').rglob('*') if p.is_file()}
manifest=dict(head=head,files=files,base_images=json.loads((ROOT/'inventory.json').read_text())['images'])
with (ROOT/'kit/manifest.json').open('x') as f:json.dump(manifest,f,indent=2)
assert not cmd(['git','-C',str(REPO),'status','--porcelain']).strip()
archive=ROOT/'icerti-crowd-20260928-r01.tar.gz'
with tarfile.open(archive,'w:gz') as tar:tar.add(ROOT/'kit',arcname='kit')
print(json.dumps(dict(archive=str(archive),bytes=archive.stat().st_size,sha256=hashlib.sha256(archive.read_bytes()).hexdigest(),files=len(files))))
