"""Metre conversion preserves source identity, selected points and audit history."""
import copy
import io
import json
from pathlib import Path
from zipfile import ZipFile

import numpy as np
import pytest

from test_pose_review import dataset
from pallet.cluster_targets import digest
from pallet.pose_review import PoseApplication
from pallet.pose_review_geometry import canonical,sensor_value
from pallet.pose_review_units import MetrePolicy


def policy(root,overrides=None):
    return MetrePolicy(dict(policy_id='test_metres_v1',formal_manifest_sha256=digest(root/'manifest.json'),
        unknown_default_scale_to_m=1.,unknown_size_overrides=overrides or {'240x96':.001},authorization={}))


def raw_record(app,key):
    d=app.detail(key);s=dict(d['sensor'],axes_confirmed=True)
    meta=app.compute(key,dict(polygon=d['initial_polygon'],sensor=s));c=meta['candidates'][0]
    payload=dict(binding=app.binding,expected_revision=0,polygon=d['initial_polygon'],sensor=s,
        geometry_token=meta['token'],selected_faces=[c['id']],exclusions=[],reviewer='unit test',
        ruler=dict(origin=c['center'],basis=c['basis'],w=.1,d=.02,angle=3.,half_width=c['half_width']),
        mask_status='confirmed',pose_status='confirmed',view=dict(centerW=.1,centerD=.02,centerH=0,span=2.))
    return app.save(key,payload)


def test_unit_policy_keeps_registered_and_human_scales(dataset):
    root,source,_=dataset;p=policy(root)
    assert p.native_scale(source)==1.
    unknown=copy.deepcopy(source);unknown['sensor_policy']['scale_to_mm']=None
    assert p.native_scale(unknown)==1.
    unknown['size']=[240,96];assert p.native_scale(unknown)==.001
    s=p.sensor(None,unknown);assert s['scale_to_m']==.001 and s['unit_origin']=='human_supplied'
    assert not s['axes_confirmed'] and '用户明确确认' in s['evidence']
    explicit=sensor_value(dict(scale_to_m=.01,evidence='specific calibration'),unknown)
    assert p.sensor(explicit,unknown)==explicit
    assert p.sensor(None,source)['unit_origin']=='source_registered'


@pytest.mark.parametrize('new_scale',[1.,.001])
def test_geometry_and_ruler_scaled_with_all_indices_and_originals_preserved(dataset,tmp_path,new_scale):
    root,source,_=dataset;source['sensor_policy']['scale_to_mm']=None
    (root/'frames.jsonl').write_text(json.dumps(source)+'\n')
    old_app=PoseApplication(root,tmp_path/'reviews',protect=False);key=old_app.keys[0]
    old=raw_record(old_app,key);before=digest(old_app.engine.cache/(old['geometry_token']+'.npz'))
    p=policy(root,{'48x24':new_scale});new_app=PoseApplication(root,tmp_path/'reviews',protect=False,unit_policy=p)
    value=new_app.detail(key)['review']
    assert value['sensor']['scale_to_m']==new_scale and value['pose']['position_unit']=='m'
    assert value['pose']['z'] is None and not value['robot_command_eligible']
    np.testing.assert_allclose([value['pose']['x'],value['pose']['y']],np.array([old['pose']['x'],old['pose']['y']])*new_scale)
    np.testing.assert_allclose(value['ruler']['origin'],np.array(old['ruler']['origin'])*new_scale)
    assert value['ruler']['half_width']==old['ruler']['half_width']*new_scale
    assert value['ruler']['angle']==old['ruler']['angle']
    assert value['ruler']['basis']==old['ruler']['basis']
    assert value['selected_faces']==old['selected_faces']
    assert value['mask_status']=='confirmed' and value['pose_status']=='pending' and value['state']=='draft'
    assert value['view']['span']==old['view']['span']*new_scale
    assert old_app.store.get(key)==old and old_app.store.history(key)==[old]
    assert digest(old_app.engine.cache/(old['geometry_token']+'.npz'))==before
    with np.load(old_app.engine.cache/(old['geometry_token']+'.npz')) as a,np.load(new_app.engine.cache/(value['geometry_token']+'.npz')) as b:
        for field in ('source_indices','uv','face_ids','mask','polygon'):np.testing.assert_array_equal(a[field],b[field])
        np.testing.assert_allclose(b['xyz'],a['xyz']*new_scale)
    reused=new_app.compute(key,dict(polygon=value['polygon'],sensor=value['sensor'],geometry_token=value['geometry_token']))
    assert reused['token']==value['geometry_token']
    # Old local drafts may send their old token with the new resolved sensor.
    converted=new_app.compute(key,dict(polygon=value['polygon'],sensor=value['sensor'],geometry_token=old['geometry_token']))
    assert converted['token']==value['geometry_token']


def test_metre_handshake_prevents_old_client_saving_and_export_is_effective(dataset,tmp_path):
    root,source,_=dataset;source['sensor_policy']['scale_to_mm']=None
    (root/'frames.jsonl').write_text(json.dumps(source)+'\n')
    old_app=PoseApplication(root,tmp_path/'reviews',protect=False);key=old_app.keys[0];old=raw_record(old_app,key)
    p=policy(root);app=PoseApplication(root,tmp_path/'reviews',protect=False,unit_policy=p)
    value=app.detail(key)['review'];payload=copy.deepcopy(value)
    payload.update(expected_revision=old['revision'],reviewer='new UI')
    with pytest.raises(Exception,match='位置单位已统一为米'):app.save(key,payload)
    payload['unit_policy_id']=p.id
    saved=app.save(key,payload)
    assert saved['sensor']['scale_to_m']==1. and saved['pose']['position_unit']=='m'
    assert saved['revision']==old['revision']+1 and app.store.history(key)[-1]==old
    with ZipFile(io.BytesIO(app.export_zip())) as z:
        active=json.loads(z.read('annotations.jsonl').splitlines()[0])
        assert active['pose']['position_unit']=='m'
        assert json.loads(z.read('manifest.json'))['position_unit']=='m'
        assert 'source_review_payloads.jsonl' in z.namelist()


def test_bulk_unit_event_does_not_change_latest_human_target(dataset,tmp_path):
    root,_,_=dataset;app=PoseApplication(root,tmp_path/'reviews',protect=False)
    app.store.save('human-newest',0,dict(state='draft'))
    app.store.save('unit-only',0,dict(state='draft',event_kind='unit_normalization'))
    assert app.store.latest(['human-newest','unit-only'])=='human-newest'
    assert app.store.latest(['unit-only']) is None


def test_old_native_machine_suggestion_is_not_mislabelled_as_metres(dataset,tmp_path):
    root,source,_=dataset;source['sensor_policy']['scale_to_mm']=None
    (root/'frames.jsonl').write_text(json.dumps(source)+'\n')
    app=PoseApplication(root,tmp_path/'reviews',protect=False,unit_policy=policy(root))
    app.machine_suggestion=lambda key:dict(pose_estimate=dict(source_scale_to_m=None,x=1600,y=20))
    assert app.detail(app.keys[0])['machine_suggestion'] is None
