"""Content-addressed source copies used to reproduce training and evaluation."""
from __future__ import annotations

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


def snapshot_source(output_root='outputs/source_snapshots'):
    root=Path(__file__).parent.parent
    paths=sorted(list((root/'pallet').rglob('*.py'))+list((root/'configs').glob('*.json'))+[root/'pyproject.toml'])
    manifest={str(path.relative_to(root)):hashlib.sha256(path.read_bytes()).hexdigest() for path in paths}
    identity=hashlib.sha256(json.dumps(manifest,sort_keys=True).encode()).hexdigest()
    output=Path(output_root);output.mkdir(parents=True,exist_ok=True)
    archive=output/f'{identity}.tar.gz'
    if not archive.exists():
        with tarfile.open(archive,'w:gz') as tar:
            for path in paths:tar.add(path,arcname=str(path.relative_to(root)),recursive=False)
        (output/f'{identity}.json').write_text(json.dumps(manifest,indent=2))
    result={'source_snapshot':str(archive.resolve()),'source_snapshot_id':identity}
    try:
        result['git_commit']=subprocess.check_output(
            ['git','rev-parse','HEAD'],cwd=root,text=True,stderr=subprocess.DEVNULL).strip()
        result['git_dirty']=bool(subprocess.check_output(
            ['git','status','--porcelain','--untracked-files=normal'],
            cwd=root,text=True,stderr=subprocess.DEVNULL).strip())
    except (OSError,subprocess.CalledProcessError):
        result['git_commit']=None
        result['git_dirty']=None
    return result


if __name__=='__main__':print(json.dumps(snapshot_source()))
