"""Only for pipeline tests: synthesize raw AQ-style CSVs from test fixture."""
from pathlib import Path
import numpy as np
import pandas as pd
from tests.make_synthetic import generate,SEM,ORIGINS

def generate_raw(root):
    root=Path(root);generate(root)
    out=root.parent/'database';out.mkdir(parents=True,exist_ok=True)
    roster=pd.read_csv(root/'data'/'asof_rosters'/'roster_asof.csv',dtype=str)
    semdate={s:pd.Timestamp(d) for s,d in zip(SEM,ORIGINS)}
    regs=[];ss=[]
    for j,r in enumerate(roster.itertuples(index=False)):
        dt=semdate[r.semester]
        # A minority intentionally post-cutoff to test uncertainty.
        late=j%17==0
        d=dt+(pd.Timedelta(days=8) if late else -pd.Timedelta(days=3))
        regs.append(dict(NHHK=r.semester,IDKQDK=str(j+1),IDSV=r.student_id,IDToHoc=r.section_id,NgayThem=str(d),NgayDoiNhom=str(dt+pd.Timedelta(days=3)) if j%101==0 else '',IDDVPC=r.source_faculty))
        ss.append(dict(NHHK=r.semester,IDToHoc=r.section_id,IDMH=r.course_id,NgayThem=str(dt-pd.Timedelta(days=12))))
    pd.DataFrame(regs).to_csv(out/'MKQDK.csv',index=False)
    pd.DataFrame(ss).drop_duplicates(['NHHK','IDToHoc']).to_csv(out/'KToHoc.csv',index=False)
    pd.DataFrame([dict(NHHK=s,NgayBDHK=d) for s,d in zip(SEM,ORIGINS)]).to_csv(out/'HDMNHHK.csv',index=False)
    gp=[]
    for (student,semester),f in roster.groupby(['student_id','semester']):
        at=semdate[semester]+pd.Timedelta(days=24)
        val=float(f.prior_gpa.dropna().iloc[0]) if f.prior_gpa.notna().any() else 3.0
        gp.append(dict(NHHK=semester,IDSV=student,DTBHK=val,NgayThem=str(at)))
    pd.DataFrame(gp).to_csv(out/'DDTBHK.csv',index=False)
    return root,out

if __name__=='__main__':
    import sys
    print(generate_raw(sys.argv[1]))
