import hashlib
import json
from remote import ROOT, REMOTE, python

names=['manifest.json','built.json','isolated-tests.json','config-targets.json','settings-migration.json',
       'settings-commit.json','deployed.json','verified.json','verified-before-gateway.json',
       'stop-evidence.json','transition.json','support-r02.json']
code='''import hashlib,json,subprocess,sys
from pathlib import Path
root=Path(ROOT);sys.path.insert(0,str(root))
from fight_r5_install import FightR5Installer
i=FightR5Installer(root,'icerti-ai2');i.cb.inspect()
plan=json.loads((root/'plan.json').read_text());rows=i.rows()
summary=dict(services={k:dict(id=r['Id'],image=r['Image'],running=r['State']['Running'],
  health=r['State'].get('Health',{}).get('Status'),identity_unchanged=r['Id']==plan['before'][k]['id']) for k,r in rows.items()},
 trial_containers=subprocess.check_output(['docker','ps','-a','--filter','name=ct-r5-','--format','{{.Names}}'],text=True).splitlines(),
 camera_start_calls=0,automatic_rollback=False,web_test='USER_WAIT')
files={name:(root/name).read_text() for name in NAMES}
print(json.dumps(dict(summary=summary,files=files,hashes={n:hashlib.sha256(v.encode()).hexdigest() for n,v in files.items()})))
'''.replace('ROOT',repr(REMOTE),1).replace('NAMES',repr(names))
value=json.loads(python(code,sudo=True))
out=ROOT/'receipts';out.mkdir(exist_ok=True)
for name,text in value['files'].items():
    assert hashlib.sha256(text.encode()).hexdigest()==value['hashes'][name]
    (out/name).write_text(text)
(out/'SHA256SUMS').write_text(''.join(f'{value["hashes"][n]}  {n}\n' for n in names))
(ROOT/'deployment_readback.json').write_text(json.dumps(value['summary'],indent=2)+'\n')
print(json.dumps(value['summary']))
