"""Source-scoped viewing axes without rotating XYZ or rewriting human history."""
from __future__ import annotations

import copy
import fcntl
import hashlib
import json
from pathlib import Path
import secrets

import numpy as np

from .cluster_targets import digest
from .pose_review_geometry import basis_for,canonical,pose_value,sensor_value

AXIS_FIELDS=('forward_axis','forward_sign','up_axis','up_sign')


class AxesPolicy:
    def __init__(self,config,sha256=None):
        self.config=copy.deepcopy(config)
        self.sha256=sha256 or hashlib.sha256(canonical(config)).hexdigest()
        self.id=config['policy_id']+':'+self.sha256[:16]
        a=config['axes']
        if a['forward_axis'] not in (0,1,2) or a['up_axis'] not in (0,1,2) or a['forward_axis']==a['up_axis']:
            raise ValueError('Invalid scoped viewing axes')
        if a['forward_sign'] not in (-1,1) or a['up_sign'] not in (-1,1):raise ValueError('Invalid axis signs')

    @classmethod
    def load(cls,path,dataset):
        path=Path(path)
        if not path.exists():return None
        config=json.loads(path.read_text())
        if config['formal_manifest_sha256']!=digest(Path(dataset)/'manifest.json'):return None
        return cls(config,digest(path))

    def applies(self,source):
        return source['sensor_policy']['policy_id']==self.config['source_policy_id'] and source['size']==self.config['source_size']

    def info(self,source=None):
        if source is not None and not self.applies(source):return None
        return dict(id=self.id,sha256=self.sha256,source_policy_id=self.config['source_policy_id'],
            axes=self.config['axes'],evidence=self.config['evidence'],XYZ_rotated=False,
            old_width_and_angle_require_review=True,robot_command_eligible=False)

    def sensor(self,value,source):
        sensor=sensor_value(value,source)
        if not self.applies(source):return sensor
        if any(sensor[k]!=self.config['axes'][k] for k in AXIS_FIELDS):
            sensor.update(self.config['axes'],axes_confirmed=False)
        if self.config['evidence'] not in sensor['evidence']:
            sensor['evidence']=sensor['evidence'][:600]+' '+self.config['evidence']
        return sensor_value(sensor,source)

    def geometry(self,engine,meta,source,sensor):
        """Rebase candidate metadata; copy measurement and preview bytes exactly."""
        if not self.applies(source):raise ValueError('Axis policy does not cover this source')
        if meta['sensor']==sensor:return meta
        if meta['sensor']['scale_to_m']!=sensor['scale_to_m']:raise ValueError('Normalize units before adapting axes')
        binding=dict(adapter='source_axes_preserve_measurements_v1',policy_id=self.id,parent=meta['token'],
            sensor=sensor,parent_points_sha256=meta['full_resolution_artifact_sha256'])
        token=hashlib.sha256(canonical(binding)).hexdigest();folder=engine.cache
        with engine.semaphore,(folder/(token+'.axes.lock')).open('a') as lock:
            fcntl.flock(lock,fcntl.LOCK_EX)
            if all((folder/(token+ext)).exists() for ext in ('.json','.npz','.bin')):return engine.load(token,meta['target_key'])
            if digest(folder/(meta['token']+'.npz'))!=meta['full_resolution_artifact_sha256']:
                raise ValueError('旧点云证据哈希变化，拒绝轴向转换')
            converted=copy.deepcopy(meta);converted.update(token=token,sensor=sensor,axes_conversion=binding)
            with np.load(folder/(meta['token']+'.npz'),allow_pickle=False) as data:
                xyz=data['xyz'];labels=data['face_ids']
                for c in [*converted['candidates'],converted['manual']]:
                    normal=c['normal'] if c['id'] else (np.eye(3)[sensor['forward_axis']]*sensor['forward_sign']).tolist()
                    b=basis_for(normal,sensor);p=xyz[labels==c['id']] if c['id'] else xyz
                    c['basis']=b.tolist()
                    if not c['id']:c['normal']=normal
                    if len(p):
                        local=p@b;lo,hi=np.quantile(local,[.01,.99],axis=0)
                        c['center']=(b@np.array([(lo[0]+hi[0])/2,np.median(local[:,1]),np.median(local[:,2])])).tolist()
                        c['half_width']=max(float((hi[0]-lo[0])/2),1e-8)
                    c['flags']=[v for v in c.get('flags',[]) if v not in ('possible_top_or_ground_face','grazing_view')]
                    if abs(np.dot(normal,np.eye(3)[sensor['up_axis']]))>.75:c['flags'].append('possible_top_or_ground_face')
                    c['axis_adapter_preserved_face_id']=True
            for ext in ('.npz','.bin'):
                raw=(folder/(meta['token']+ext)).read_bytes();tmp=folder/(token+'.'+secrets.token_hex(6)+'.tmp')
                tmp.write_bytes(raw);tmp.replace(folder/(token+ext))
            converted['full_resolution_artifact_sha256']=digest(folder/(token+'.npz'))
            tmp=folder/(token+'.'+secrets.token_hex(6)+'.tmp');tmp.write_bytes(canonical(converted));tmp.replace(folder/(token+'.json'))
            return converted

    def review(self,value,source,engine):
        if value is None or not self.applies(source):return copy.deepcopy(value)
        old_sensor=value['sensor'];sensor=self.sensor(old_sensor,source);result=copy.deepcopy(value)
        result['axes_policy']=self.info(source)
        if sensor==old_sensor:return result
        axes_changed=any(sensor[k]!=old_sensor[k] for k in AXIS_FIELDS)
        result['sensor']=sensor;meta=None
        if result.get('geometry_token'):
            meta=self.geometry(engine,engine.load(result['geometry_token'],result['target_key']),source,sensor)
            result['geometry_token']=meta['token']
        r=result.get('ruler')
        if axes_changed and r:
            b=np.asarray(r['basis']);center=np.asarray(r['origin'])+r['w']*b[:,0]+r['d']*b[:,1]
            candidate=next((c for c in (meta or {}).get('candidates',[]) if c['id'] in result.get('selected_faces',[])),None)
            new_basis=np.asarray(candidate['basis']) if candidate else basis_for(np.eye(3)[sensor['forward_axis']]*sensor['forward_sign'],sensor)
            half=candidate['half_width'] if candidate else (meta or {}).get('manual',{}).get('half_width',.5)
            if meta and result.get('selected_faces'):
                selected=engine.selected(meta,result['selected_faces'],result.get('exclusions',[]))
                p=selected['xyz'][selected['selected']]
                if len(p)>=3:
                    lo,hi=np.quantile(p@new_basis[:,0],[.01,.99]);half=max(float((hi-lo)/2),1e-8)
            result['ruler']=dict(origin=center.tolist(),basis=new_basis.tolist(),w=0.,d=0.,angle=0.,half_width=half,direction_sign=1)
            result['view']=dict(centerW=0.,centerD=0.,centerH=0.,span=max(2.65*half,.2))
        if result.get('pose') is not None and result.get('ruler'):result['pose']=pose_value(result['ruler'],sensor)
        if axes_changed:
            result.update(pose_status='pending',human_pose_confirmed=False,metric_pose_confirmed=False,
                automatic_training_eligible=False,robot_command_eligible=False,
                axes_interpretation=dict(policy_id=self.id,source_revision=value.get('revision'),
                    original_record_sha256=hashlib.sha256(canonical(value)).hexdigest(),old_sensor=old_sensor,
                    legacy_ruler=value.get('ruler'),legacy_view=value.get('view'),legacy_pose=value.get('pose'),
                    center_preserved_for_review_not_confirmed=True,width_and_angle_reinitialized_as_proposal=True,
                    exclusions_preserved_in_source_coordinates=True,selected_point_ids_preserved=True,historical_record_unchanged=True))
            if result.get('state')=='complete':result['state']='draft'
        return result
