#!/usr/bin/env python3
import json,pathlib,subprocess,sys,time,urllib.request,urllib.error
s=json.loads(pathlib.Path('/tmp/highload-current-auth-retest.json').read_text())
assert s['project'].startswith('highload-auth-retest-')
base=['docker','compose','-p',s['project'],'--project-directory',s['root'],'-f',s['root']+'/compose.yaml','-f',s['tmp']+'/compose.test.yaml']
action=pathlib.Path(sys.argv[0]).stem.split('-')[-1]
assert action in ('restart','failure','recovery')
def snapshot():
 result={}
 for service in ('api','postgres'):
  p=subprocess.run(base+['ps','-aq',service],capture_output=True,text=True,check=True)
  ident=p.stdout.strip()
  raw=json.loads(subprocess.run(['docker','inspect',ident],capture_output=True,text=True,check=True).stdout)[0]
  result[service]={'id':ident,'started_at':raw['State']['StartedAt'],'running':raw['State']['Running'],'volumes':[m['Name'] for m in raw['Mounts'] if m['Type']=='volume']}
 return result
before=snapshot()
tail={'restart':['restart','api','postgres'],'failure':['stop','postgres'],'recovery':['start','postgres']}[action]
p=subprocess.run(base+tail,capture_output=True,text=True,timeout=65)
pathlib.Path(s['tmp'],action+'-hook-docker.log').write_text(p.stdout+p.stderr)
if p.returncode:raise SystemExit(p.returncode)
if action!='failure':
 deadline=time.monotonic()+20
 while True:
  try:
   with urllib.request.urlopen(s['base_url']+'/health/ready',timeout=3) as response:
    if response.status==200:break
  except (OSError,urllib.error.URLError):pass
  if time.monotonic()>deadline:raise SystemExit(2)
  time.sleep(.2)
proof={'action':action,'before':before,'after':snapshot()}
with pathlib.Path(s['tmp'],'hook-proof.jsonl').open('a') as f:f.write(json.dumps(proof)+'\n')
