from common import *
import json
g,t=load();cut=pd.Timestamp('2026-07-01',tz='UTC')
d=g[g.valid&g.dev.ne('')&g.date.le(cut)].sort_values(['dev','date','appid']).copy();d['index']=d.groupby('dev').cumcount()+1;d['debut']=d.groupby('dev').date.transform('min')
second=d[d['index'].eq(2)].set_index('dev').date
first=d[d['index'].eq(1)&d.date.ge(pd.Timestamp('2015-01-01',tz='UTC'))&d.date.le(cut-pd.Timedelta(days=365.25*3))].copy()
first['next3']=first.dev.map(second).le(first.date+pd.Timedelta(days=365.25*3));first['band']=pd.cut(first.reviews,[-1,49,555,np.inf],labels=['low','mid','hit']).astype(str)
rows=[]
for band,a in first.groupby('band'):
    rows.append(dict(band=band,n=len(a),next3=int(a.next3.sum()),next3_rate=a.next3.mean(),**compare(a,first[first.band.ne(band)],cols=('year','price_band','primary'),outcomes=('next3',))))
save(rows,'continuation_outcome_adjusted.csv')
hits=d[d.reviews.ge(556)&d.debut.ge(pd.Timestamp('2015-01-01',tz='UTC'))&d.date.le(pd.Timestamp('2025-07-01',tz='UTC'))].drop_duplicates('dev',keep='first')
hits[hits['index'].ge(8)][['dev','appid','name','date','index','reviews']].to_csv(R/'late_first_hits.csv',index=False)
d[d.dev.isin(['sokpop collective','gagonfe','a327ex'])][['dev','appid','name','date','index','reviews']].to_csv(R/'named_career_sequences.csv',index=False)
print('Continuation tests complete; late first hits',sum(hits['index']>=8))
