from collections import Counter
from copy import deepcopy
import math

import cv2
import numpy as np
import pytest
import torch

from pallet import mask_annotation_update_v2_data as data
from pallet import mask_annotation_update_v2_train as training
from pallet.mask_annotation_full_train import epoch_indices


def test_new_freeze_is2041_and246_with_both_prior_sources_not_rebound():
    assert data.TOTAL==2041 and data.COMPONENTS==246
    assert [b[-1] for b in data.REVIEW_BATCHES]==[337,145]
    assert data.ROOT!=data.PREVIOUS and data.ROOT.name.endswith('_v2')
    assert data.START_SHA=={
        'm1':'153e572357a886783b8a4d9449ada1290dc4b74efd63f3d27a943ac05115db03',
        'm2':'3eb7d659daccd424c2b47b0b70b098f8041273ba8b0f407bc10a57caaa29c524'}


def test_fixed10_epochs_fullpool_exposure_and_real5110_update_budget():
    records=[dict(component=i%246) for i in range(2041)];indices=epoch_indices(records,0)
    assert len(indices)==4082 and set(indices)==set(range(2041)) and min(Counter(indices).values())>=1
    assert math.ceil(len(indices)/8)*10==5110
    assert training.CONFIGS['m1']['epochs']==training.CONFIGS['m2']['epochs']==10
    assert training.CONFIGS['m2']['microbatch']==2 and training.CONFIGS['m2']['batch']==8


def test_input_pixels_not_human_point_count_class_pose_or_component(tmp_path,monkeypatch):
    monkeypatch.setattr(training,'ROOT',tmp_path)
    grey=np.arange(40*100,dtype=np.uint8).reshape(40,100);mask=np.zeros((40,100),np.uint8);mask[5:35,5:95]=255
    for name,image in [('image.png',grey),('mask.png',mask),('valid.png',np.ones_like(mask)*255)]:cv2.imwrite(str(tmp_path/name),image)
    r=dict(image='image.png',native_mask='mask.png',valid_mask='valid.png',polygon=[[0,0]]*16,class_id=9,component=5,pose='hidden',ruler='hidden')
    a=training.Inputs([r],[576,576]);other=deepcopy(r);other.update(polygon=[[1,1]]*4,class_id=1,component=245,pose='changed')
    b=training.Inputs([other],[576,576]);assert torch.equal(a.items[0][0],b.items[0][0])
    images,targets,valid,canvas=a.batch([0],'cpu');assert images.shape==(1,3,576,576) and targets.shape==valid.shape==(1,576,576)


def test_bad_duplicate_or_missing_real_review_never_implicitly_counts_machine(tmp_path,monkeypatch):
    from scripts import audit_mask_model_reviews
    monkeypatch.setattr(audit_mask_model_reviews,'audit',lambda *_:dict(new_distinct_saved_images=144))
    tasks=tmp_path/'tasks';tasks.mkdir();(tasks/'proposals.jsonl').write_text('')
    with pytest.raises(ValueError,match='actual human save'):data.model_sources('test',tasks,tmp_path/'absent.sqlite3',145,{},tmp_path)


def test_events_raw_UTF8_preserved_not_reformatted():
    import hashlib,json
    from pallet.pose_review_geometry import canonical
    raw='{"revision": 1, "note": "审核"}'
    assert data.raw_sha(raw)==hashlib.sha256(raw.encode()).hexdigest()
    assert data.raw_sha(raw)!=hashlib.sha256(canonical(json.loads(raw))).hexdigest()


def test_new2041_review_validator_requires_its_namespace_schema_checkpoint_and_K():
    from pallet.mask_annotation_update_v2_review import validate,editor_js,Updated2041KeypointGallery
    from pallet.mask_annotation_update_v2_requests import SCHEMA,NAMESPACE,DRAFT_PREFIX
    from test_mask_model_worklist import proposal
    from pallet.mask_class_keypoints import VERSION
    p=proposal();p.update(schema=SCHEMA,origin='updated_M2_prediction');p['source']['final_class_id']=p['class_id']
    p['model_provenance'].update(checkpoint_sha256='new2041-final-EMA',corner_conversion=dict(algorithm=VERSION),quality_gate_passed=False)
    p['class_keypoint_constraint']=dict(class_id=4,standard_count=8,standard_sha256='standard',method='unique_class_saved_polygon_vertex_count_mode')
    standard=dict(classes={'4':dict(standard_count=8)});original=deepcopy(p)
    validate(p,standard,'standard','new2041-final-EMA');assert p==original
    with pytest.raises(ValueError):validate(p,standard,'standard','old1896-final-EMA')
    p['schema']='updated1896_M2_class_standard_keypoint_preannotation_v1'
    with pytest.raises(ValueError):validate(p,standard,'standard','new2041-final-EMA')
    assert DRAFT_PREFIX in editor_js() and 'mask-annotation-update-remaining-v1:' not in editor_js()
    assert Updated2041KeypointGallery.publication_namespace==NAMESPACE and Updated2041KeypointGallery.allow_class_keypoint_count_changes


def test_new2041_human_extra_point_export_is_actual_count_not_standard(tmp_path):
    import json
    from test_mask_model_worklist import editor,payload
    from pallet.mask_annotation_update_v2_requests import NAMESPACE
    e,p=editor(tmp_path)
    p['class_keypoint_constraint']=dict(class_id=4,standard_count=8,standard_sha256='standard',method='unique_class_saved_polygon_vertex_count_mode')
    e.gallery.publication_version=NAMESPACE;e.gallery.allow_class_keypoint_count_changes=True
    value=payload(p);value['polygon']=[p['polygon'][0],[35,10]]+p['polygon'][1:];saved=e.save(p['target_key'],value)
    result=json.loads(e.export(p['target_key'],'labelme.json')[0])
    assert saved['proposal_publication']==NAMESPACE and result['num_keypoints']==9 and result['initial_standard_keypoint_count']==8
    assert saved['human_keypoint_editing']['delta_from_standard']==1 and not saved['automatic_training_eligible']


def test_new_endpoint_cannot_rebind_old337_or145_stores():
    from scripts import serve_mask_annotation_update_v2_requests as service
    assert service.PORT==3408 and service.REVIEWS.name=='pallet_mask_model_reviews_v5'
    assert service.ROOT.name=='pallet_mask_annotation_update_requests_v2' and service.STATE.name=='pallet_mask_annotation_update_managed_v2'


def test_browser_check_allows_one_remaining_class_without_fake_class1_or2_tasks():
    import inspect
    from scripts.check_mask_model_requests_ui import check
    sig=inspect.signature(check)
    assert sig.parameters['editing_class'].default==1 and sig.parameters['image_retry_class'].default==2
    text=inspect.getsource(check)
    assert "select_option(str(editing_class))" in text and "p['target_key']!=target" in text
