"""Check packaged GPU inference and latency on original train examples only."""
import json
from pathlib import Path
import sys
import time

PROJECT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(PROJECT))
import numpy as np
import torch
from pallet.pose_benchmark import ROOT,load_data,atomic_json
from pallet.pose_benchmark_results import load_refit
from pallet.pose_benchmark_inference import BenchmarkPosePredictor
from pallet.pose_refinement import decoded
from pallet.cluster_targets import load_dataset
from pallet.pose_review_geometry import GeometryEngine,canonical


def main():
    predictor=BenchmarkPosePredictor(ROOT/'deployment',allow_native=True)
    selection=json.loads((ROOT/'selection_frozen.json').read_text())
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    _,sources=load_dataset(formal)
    engine=GeometryEngine(formal,ROOT/'inference_verification_registration')
    checks=[];latencies={}
    for branch,profile in selection['profiles'].items():
        specification=profile['best_learning']
        rows,arrays=load_data(branch,route=specification['route'])
        indices=np.linspace(0,len(rows)-1,6,dtype=int)
        model,frozen=load_refit(branch,specification)
        for i in indices:
            row=rows[i];source=sources[row['frame_id']]
            f,g=arrays['f'][i,0],arrays['g'][i,0]
            residual=predictor.residual(f,g,branch)
            ft=torch.tensor(f,device='cuda')[None];gt=torch.tensor(g,device='cuda')[None]
            with torch.no_grad():
                if frozen:
                    backbone=predictor.models[branch][0]
                    expected=model(torch.cat((backbone(ft),gt),-1)).cpu().numpy()[0]
                else:expected=model(ft,gt).cpu().numpy()[0]
            np.testing.assert_allclose(residual,expected,atol=1e-6)
            value=decoded(residual,arrays['base'][i],arrays['width'][i],arrays['direction'][i])
            points,mapping=engine.registered(canonical(source).decode())
            box=[row['bbox'][k] for k in ('x','y','width','height')]
            pose=predictor.pose(points,mapping,box,scale_to_m=row['sensor']['scale_to_m'],domain=row['domain'])
            np.testing.assert_allclose([pose['x'],pose['y']],value[:2],atol=1e-5)
            np.testing.assert_allclose(pose['theta_degrees'],np.degrees(np.arctan2(value[3],value[2])),atol=1e-4)
            assert pose['z'] is None and not pose['robot_command_eligible']
            checks.append(dict(target_key=row['target_key'],branch=branch,split='train',route=specification['route'],passed=True))
        del model
        torch.cuda.empty_cache()
        f,g=arrays['f'][indices[0],0],arrays['g'][indices[0],0]
        for _ in range(5):predictor.residual(f,g,branch)
        torch.cuda.reset_peak_memory_stats()
        times=[]
        for _ in range(30):
            torch.cuda.synchronize();start=time.perf_counter()
            predictor.residual(f,g,branch);torch.cuda.synchronize()
            times.append((time.perf_counter()-start)*1000)
        latencies[branch]=dict(network_single_target_ms_median=float(np.median(times)),
                              network_single_target_ms_p90=float(np.quantile(times,.9)),
                              includes_numpy_transfer=True,excludes_ROI_preprocessing=True,
                              peak_memory_bytes=torch.cuda.max_memory_allocated(),gpu=torch.cuda.get_device_name())
    atomic_json(ROOT/'inference_verification.json',dict(state='passed',checks=checks,latencies=latencies))
    print(json.dumps(dict(state='passed',checks=len(checks),latencies=latencies)),flush=True)


if __name__=='__main__':main()
