import hashlib, json, os, subprocess
from pathlib import Path

SLICE = Path(__file__).resolve().parent
ROOT = SLICE.parents[3]
PRIVATE = SLICE/'private-evidence'
assert PRIVATE.is_dir() and not PRIVATE.is_symlink()
assert not (PRIVATE/'manifest.json').exists(), 'Do not overwrite sealed preflight'
os.chmod(PRIVATE,0o700)
files = ['p/controller/NutritionSet.php','p/controller/NutritionTime.php','p/logic/Nutrition.php','p/logic/NutritionTime.php','model/NutritionSet.php','model/NutritionTime.php','model/Nutrition.php','model/BaseModel.php','base/AdminController.php','p/logic/MealConfig.php','model/Config.php','p/logic/Login.php','common.php','route.php','config.php']
source = {f:hashlib.sha256((ROOT.parent/'zhctproject/store/application'/f).read_bytes()).hexdigest() for f in files}
(PRIVATE/'source-sha.json').write_text(json.dumps(source,indent=2)+'\n')
dedupe = subprocess.check_output(['python3',str(SLICE/'dedupe.py')],text=True)
(SLICE/'dedupe-result.json').write_text(dedupe)
manifest = {}
for f in sorted(PRIVATE.iterdir()):
    assert f.is_file() and not f.is_symlink()
    os.chmod(f,0o600)
    if f.name == 'manifest.json': continue
    manifest[f.name]={'bytes':f.stat().st_size,'sha256':hashlib.sha256(f.read_bytes()).hexdigest()}
(PRIVATE/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
os.chmod(PRIVATE/'manifest.json',0o600)
print(json.dumps({'files':len(manifest),'manifest_sha256':hashlib.sha256((PRIVATE/'manifest.json').read_bytes()).hexdigest(),'HTTP':0,'DML':0,'DDL':0}))
