"""Synthetic mechanism/cost probe; excludes IO, pretraining, coadaptation and grids.

Not an academic performance benchmark. Use a small pilot on actual caches to
estimate production cost. This probe exercises the real path-conditioned reader
and native grower rather than substituting a fixed-memory feature matrix.
"""
import argparse
import json
import resource
import time
from pathlib import Path
import numpy as np
import torch
from data import Table,Preprocessor,build_history
from memory import Reader,EvidenceProvider
from native import Booster,BoostConfig
from protocol import faculty_weights
from runtime import atomic_json,seed_all,versions


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--rows',type=int,default=20000)
    p.add_argument('--trees',type=int,default=4)
    p.add_argument('--device',default='cpu')
    p.add_argument('--out-file')
    a=p.parse_args()
    if a.rows<1000 or a.trees<1: p.error('rows>=1000 and trees>=1 required')
    if a.out_file and Path(a.out_file).exists(): raise FileExistsError(a.out_file)
    torch.set_num_threads(1); seed_all(27); rng=np.random.default_rng(27)
    n=a.rows; student=np.arange(n)%1000; sem=np.arange(n)//1000; course=(student+sem)%24
    x=rng.normal(size=(n,153)).astype(np.float32); ability=rng.normal(size=1000)
    risk=1/(1+np.exp(-(.5*x[:,0]+1.4*ability[student]+.3*(course%2))))
    y=(rng.random(n)<risk).astype(np.int8); grade=np.where(y,3.,8.)
    meta=rng.normal(size=(24,17)).astype(np.float32)[course]
    table=Table(x,meta,y,grade,sem,np.asarray([f's{i}' for i in student]),np.asarray([f'c{i}' for i in course]),
                student%14,np.asarray([f'e{i}' for i in range(n)]),np.full(n,np.nan),
                tuple(f'faculty_{i}' for i in range(14)),tuple(f'x{i}' for i in range(153)))
    pre=Preprocessor.fit(table,np.arange(n)); prepared=pre.transform(table)
    history=build_history(table,table,32); reader=Reader(pre.n_courses)
    start=time.perf_counter(); provider=EvidenceProvider(prepared,prepared,history,reader,path_strength=1.5,device=a.device)
    cache_seconds=time.perf_counter()-start
    start=time.perf_counter(); forest=Booster(BoostConfig(trees=a.trees,depth=4)).fit(provider,y,faculty_weights(table))
    fit_seconds=time.perf_counter()-start
    start=time.perf_counter(); scores=forest.predict_proba(provider); predict_seconds=time.perf_counter()-start
    summary,_=forest.diagnostics()
    result={'fixture':'synthetic 153 numeric inputs +153 presence +14 faculty; untrained frozen reader',
            'rows':n,'prepared_features':prepared.x.shape[1],'history_width':32,'device':a.device,
            'cache_seconds':cache_seconds,'fit_seconds':fit_seconds,'predict_seconds':predict_seconds,
            'lifetime_peak_host_rss_mb':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024,
            'finite_scores':bool(np.isfinite(scores).all()),'tree_diagnostics':summary,'versions':versions(),
            'excludes':'input IO, preprocessing timing, reader pretraining, coadaptation, full origins/grid and real academic performance'}
    if a.out_file: atomic_json(a.out_file,result)
    print(json.dumps(result,indent=2))


if __name__=='__main__': main()
