"""Check source scope and corrected automatic candidates using isolated caches."""
import json
from pathlib import Path
import sys

import numpy as np

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import load_dataset,digest
from pallet.pose_review_axes import AxesPolicy
from pallet.pose_review_geometry import GeometryEngine
from pallet.pose_review_units import MetrePolicy
from pallet.pose_refinement import atomic_json


def main():
    out=PROJECT/'outputs/pallet_pose_review_validation_v13';out.mkdir(parents=True,exist_ok=True)
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    aa,ss=load_dataset(formal);rows={a['frame_id']:a for a in aa}
    units=MetrePolicy.load(PROJECT/'configs/pallet_pose_review_units_v1.json',formal)
    axes=AxesPolicy.load(PROJECT/'configs/pallet_pose_review_axes_v1.json',formal);assert axes and units
    affected=0;unaffected=0
    for s in ss.values():
        old=units.sensor(None,s);new=axes.sensor(old,s)
        if axes.applies(s):
            affected+=1
            assert new['forward_axis']==2 and new['up_axis']==1 and new['scale_to_m']==.001 and not new['axes_confirmed']
        else:assert new==old;unaffected+=1
    assert affected==300 and unaffected==10074
    audit=json.loads((out/'axis_audit.json').read_text());engine=GeometryEngine(formal,out/'corrected_sample_geometry');results=[]
    for example in audit['examples']:
        source=ss[example['frame_id']];box=rows[source['frame_id']]['boxes'][0]
        x,y,w,h=(box[k] for k in ('x','y','width','height'));poly=[[x,y],[x+w,y],[x+w,y+h],[x,y+h]]
        meta=engine.compute('axes-isolated-check',source,poly,axes.sensor(units.sensor(None,source),source))
        c=meta['candidates'][0];b=np.array(c['basis']);assert c['half_width']>.25
        np.testing.assert_allclose(b[:,2],[0,1,0],atol=1e-10)
        assert b[0,0]<-.9 and b[2,1]>.9
        assert abs(c['normal'][2])>.9 and 'possible_top_or_ground_face' not in c['flags']
        with np.load(engine.cache/(meta['token']+'.npz')) as z:
            p=z['xyz'][z['face_ids']==c['id']];local=p@b
        spread=np.quantile(local,.99,axis=0)-np.quantile(local,.01,axis=0)
        assert spread[0]>spread[2]*2
        assert digest(source['source_paths']['pcd'])==source['source_anchor_hash']
        results.append(dict(frame_id=source['frame_id'],source_pcd_sha256=source['source_anchor_hash'],
            candidate_id=c['id'],candidate_basis=c['basis'],candidate_normal=c['normal'],
            total_width_m=c['half_width']*2,front_width_over_height=float(spread[0]/max(spread[2],1e-10))))
    atomic_json(out/'axes_scope_and_geometry.json',dict(state='passed',affected_frames=affected,unaffected_frames_verified=unaffected,
        affected_targets=sum(len(a['boxes']) for a in aa if axes.applies(ss[a['frame_id']])),samples=results,
        production_database_writes=0,source_files_modified=False,isolated_geometry_cache=True))
    print(json.dumps(dict(state='passed',affected=affected,unaffected=unaffected,samples=len(results))))


if __name__=='__main__':main()
