from pathlib import Path
import hashlib,json,os,shutil,subprocess,tarfile
os.umask(0o077)
here=Path(__file__).parent;repo=Path('/workspace/contextra-analytics-runtime-lifecycle-refactor')
pack=here/'kit';pack.mkdir(mode=0o755)
paths=subprocess.check_output(['git','ls-files','app','control_sidecar','native/frame_metadata','deployment_kit','tests'],cwd=repo,text=True).splitlines()
paths+=subprocess.check_output(['git','ls-files','--others','--exclude-standard','app','deployment_kit','tests'],cwd=repo,text=True).splitlines()
paths+=['docker/secure-gateway-entrypoint.sh','docker/secure-gateway.conf.template']
for name in sorted(set(paths)):
    source=repo/name;assert source.is_file() and not source.is_symlink()
    dest=pack/name;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,dest);dest.chmod(0o644)
for name in ('Analytics.Dockerfile','Sidecar.Dockerfile'):shutil.copyfile(here/name,pack/name)
for p in pack.rglob('*'):
    if p.is_dir():p.chmod(0o755)
manifest=dict(head=subprocess.check_output(['git','rev-parse','HEAD'],cwd=repo,text=True).strip(),
    files={str(p.relative_to(pack)):dict(size=p.stat().st_size,sha256=hashlib.sha256(p.read_bytes()).hexdigest()) for p in pack.rglob('*') if p.is_file()},
    source_patch_sha256=hashlib.sha256(subprocess.check_output(['git','diff','--binary'],cwd=repo)).hexdigest())
(pack/'manifest.json').write_text(json.dumps(manifest,indent=2));(pack/'manifest.json').chmod(0o644)
archive=here/'icerti-provider-20260927-r01.tar.gz'
with tarfile.open(archive,'w:gz') as tar:tar.add(pack,arcname='kit')
result=dict(archive=str(archive),sha256=hashlib.sha256(archive.read_bytes()).hexdigest(),size=archive.stat().st_size,files=len(manifest['files']))
(here/'package.json').write_text(json.dumps(result,indent=2));print(json.dumps(result))
