#!/usr/bin/env python3
"""scen.py LABEL FACTOR [--stale]  one fresh Kodi under throttle: start -> first row, sidebar jump, tour, mark"""
import json, os, subprocess, sys, time, re
ROOT='/Users/chudy/Library/Application Support/Kodi/addons/plugin.video.milionar'
sys.path[:0]=[ROOT+'/scripts/skin_harness',ROOT+'/scripts/dialog_harness',ROOT]
import types
for n in ('xbmc','xbmcgui'): sys.modules.setdefault(n,types.ModuleType(n))
import measure as M, kodi_live
HERE=os.path.dirname(os.path.abspath(__file__))
label,factor=sys.argv[1],float(sys.argv[2]); stale='--stale' in sys.argv
if stale: os.utime(ROOT+'/main.py')
M.stop_kodi()
th=subprocess.Popen([sys.executable,HERE+'/throttle.py',str(factor)]) if factor>1 else None
res={}
try:
    t0=time.time()
    M.start_kodi(slow=False)
    res['listener']=round(time.time()-t0,1)
    def wait(pat,timeout=120,since=0):
        end=time.time()+timeout
        while time.time()<end:
            for ts,txt in M.perf():
                if ts>=since and re.search(pat,txt): return ts
            time.sleep(.3)
        return None
    fy=wait(r'^cards foryou [1-9]',since=t0); res['first_row']=round(fy-t0,1) if fy else None
    allf=None
    # jump to Filmy right when the first row is there
    t_jump=time.time(); M.ops({'op':'builtin','cmd':'SetFocus(9000,1)'},timeout=120)
    fm=wait(r'^cards my_movies [1-9]',20,t0); res['jump_filmy_first']=round(max(0,fm-t_jump),2) if fm else None
    time.sleep(1)
    t_jump=time.time(); M.ops({'op':'builtin','cmd':'SetFocus(9000,2)'},timeout=120)
    fm=wait(r'^cards my_series [1-9]',20,t0); res['jump_series_first']=round(max(0,fm-t_jump),2) if fm else None
    res['perf_tail']=[ (round(a-t0,2),b[:110]) for a,b in M.perf() if a>=t0][:80]
    M.wait_quiet(quiet=6,cap=30)
    res['quiet_at']=round(time.time()-t0,1)
    res['cpu']=M.cpu_seconds()
finally:
    if th: th.terminate(); th.wait()
    subprocess.run(['pkill','-CONT','-x','Kodi'])
json.dump(res,open(HERE+'/perf/%s.json'%label,'w'),ensure_ascii=False,indent=0)
print({k:v for k,v in res.items() if k!='perf_tail'})
for a,b in res['perf_tail'][:60]: print(a,b)
