from common import *
import json
g,t=load();source=R.parent/'career-history-2026-09-06'
reviews=pd.read_parquet(source/'reviews.parquet');targets=pd.read_parquet(source/'targets.parquet')
targets=targets[targets.is_free.eq(0)]
reviews=reviews[reviews.appid.isin(targets.appid)].copy();reviews['created']=pd.to_datetime(reviews.timestamp_created,unit='s',utc=True)
rows=[]
for a,x in reviews.groupby('appid'):
    game=g.set_index('appid').loc[a];age=(x.created-game.date).dt.total_seconds()/86400
    q={'appid':a,'name':game['name'],'dev':game.dev,'date':game.date,'snapshot_count':game.reviews,'surviving_count':len(x),'price':game.price,'current_pct':x.voted_up.mean()*100,'median_playtime_hours':x.playtime_at_review_minutes.median()/60}
    for day in [1,7,14,30,90,365]:q['d'+str(day)]=int(age.lt(day).sum()) if game.date+pd.Timedelta(days=day)<=pd.Timestamp('2026-09-06',tz='UTC') else None
    # Contrast full day30 with the partial calendar launch month used in older m1 analyses.
    boundary=(game.date+pd.offsets.MonthBegin(1)).normalize()
    q['calendar_launch_month']=int(x.created.lt(boundary).sum());q['launch_month_days']=(boundary-game.date).total_seconds()/86400
    monthly=x.groupby(x.created.dt.strftime('%Y-%m')).size()
    q['first3_nonempty_months']=int(monthly.iloc[:3].sum())
    q['first3_nonempty_months_end']=str(monthly.index[min(2,len(monthly)-1)])
    q['month_to_day30_ratio']=q['calendar_launch_month']/q['d30'] if q['d30'] else None
    q['post90_to365']=q['d365']-q['d90'] if q['d365'] is not None else None
    rows.append(q)
h=pd.DataFrame(rows).sort_values(['dev','date']);save(rows,'history_windows.csv')
pairrows=[]
for dev,d in h.groupby('dev'):
    prior=[]
    for row in d.to_dict('records'):
        if prior:
            prev=prior[-1];ids=[r['appid'] for r in prior]
            before=reviews[reviews.appid.isin(ids)&reviews.created.lt(row['date'])]
            counts=before.groupby('appid').size().reindex(ids,fill_value=0)
            now=h.set_index('appid').loc[ids,'surviving_count']
            band=lambda x:'low' if x<50 else 'mid' if x<556 else 'hit'
            pairrows.append(dict(dev=dev,previous=prev['name'],next=row['name'],prior_now_best=int(now.max()),prior_then_best=int(counts.max()),prior_now_band=band(now.max()),prior_then_band=band(counts.max()),prior_then_sum=int(counts.sum()),d30=row['d30'],d90=row['d90'],d365=row['d365']))
        prior.append(row)
save(pairrows,'history_prior_context.csv')
print('History recomputation complete',len(h),'games',len(reviews),'reviews')
