from common import *
import datetime
import hashlib
import shutil
import sys
import time
R.chmod(0o700)
assert not (R/'plan.json').exists()
assert g.sh(['git','-C',str(REPO),'rev-parse','HEAD']).strip()==HEAD
assert not g.sh(['git','-C',str(REPO),'status','--porcelain']).strip()
prior=json.loads((OLD/'plan.json').read_text())
sys.path.insert(0,str(REPO/'tools'))
from rtsp_test_manager import Manager
sender=next(s for s in Manager().status() if s['name']=='sample01')
streams=api('/api/v1/streams')['streams']
assert all(s['state']=='stopped' for s in streams if s['stream_id']!='rtsp-test-01')
status=api('/api/v1/streams/rtsp-test-01')
settings=api('/api/v1/streams/rtsp-test-01/settings')
key='contextra:metadata:v1:camera:'+hashlib.sha256(b'rtsp-test-source-01').hexdigest()+':frames'
save('before-frames.json',redis('reader','XREVRANGE',key,'+','-','COUNT','2'))
save('before-state.json',dict(stream=status,settings=settings,sender=sender,publisher=api('/api/v1/metadata/status')))
plan=dict(prior,head=HEAD,started=datetime.datetime.now(datetime.timezone.utc).isoformat(),analytics=g.inspect(),
          other_containers=g.others(),streams=streams,settings=settings['configured'],sender=sender)
for name,path in [('env',g.ENV),('active',Path(prior['active'])),('overlay',Path(prior['overlay'])),
                  ('registry',Path(prior['registry'])),('redis_config',C/'redis.conf')]:
    plan[name+'_hash']=g.sha(path)
    shutil.copyfile(path,R/(name+'.before'))
assert all(g.sha(Path(p))==h for p,h in plan['model_hashes'].items())
plan['disk_free']=shutil.disk_usage(plan['docker_root']).free
assert plan['disk_free']>15*1024**3
save('plan.json',plan)
save('ledger.json',dict(started=plan['started'],user_stop=0,conversion=0,build=0,ai_start=0,ai_stop=0,capacity_errors=0,
    caps=dict(preparation_minutes=20,runtime_minutes=35,conversion_seconds=180,conversion_threads=2,conversion_file_gib=1,
              windows_probe_seconds=12,measurement_seconds=15,live_total_seconds=90,gpu_delta_mib=8192)))
if status['state']!='stopped':
    ledger=json.loads((R/'ledger.json').read_text());ledger['user_stop']=1;save('ledger.json',ledger)
    save('stop-response.json',api('/api/v1/streams/rtsp-test-01/stop','POST'))
    end=time.monotonic()+45
    while time.monotonic()<end:
        after=api('/api/v1/streams/rtsp-test-01')
        if after['state']=='stopped' and not after.get('cleanup_pending'):break
        time.sleep(.3)
    save('after-user-stop.json',after)
    assert after['state']=='stopped' and not after.get('cleanup_error'),'USER_STOP_FAILED'
print(json.dumps(dict(gate='PASS',user_trial_stopped=True,sender_retained=True,disk_gib=round(plan['disk_free']/1024**3,1))))
