"""Updated-model remaining drafts; initial class K, flexible human refinements."""
import json
from pathlib import Path
import re

from .cluster_targets import digest
from .mask_annotation_update_requests import SCHEMA,NAMESPACE,DRAFT_PREFIX
from .mask_class_keypoints import corner_geometry,SETTINGS,VERSION
from .mask_model_worklist import FLAGS
from .mask_model_review import ModelMaskGallery
from .mask_gallery import ASSETS
from .pose_review_geometry import polygon_value


def editor_js():
    text=(ASSETS/'editor.js').read_text().replace("'mask-gallery-v1:'",repr(DRAFT_PREFIX))
    text=text.replace("'机器建议 · 尚未人工保存'","'更新M2关键点预标注 · 人工微调可增点'")
    text=text.replace("$('mgTarget').textContent=`Class ${value.class_id}",
        "$('mgTarget').textContent=`标准 ${value.class_keypoint_constraint.standard_count} 点（初始草稿） · Class ${value.class_id}")
    text=text.replace(' · 原图像素坐标（非米）`;',
        ' · 类别标准 ${detail.class_keypoint_constraint.standard_count} 点（初始草稿） · 原图像素坐标（非米）`;')
    return text


def validate(p,standard,standard_sha,checkpoint_sha):
    k=standard['classes'][str(p['class_id'])]['standard_count'];constraint=p.get('class_keypoint_constraint',{})
    proof=p.get('model_provenance',{})
    if not (p.get('schema')==SCHEMA and p.get('origin')=='updated_M2_prediction' and
            p.get('status')=='model_preannotated_pending_human_review' and all(p.get(f) is False for f in FLAGS)
            and re.fullmatch('[0-9a-f]{24}',p['target_key']) and p['source']['target_key']==p['target_key']
            and p['class_id']==p['source']['final_class_id'] and len(p['polygon'])==p['vertex_count']==k
            and constraint.get('class_id')==p['class_id'] and constraint.get('standard_count')==k
            and constraint.get('standard_sha256')==standard_sha and constraint.get('method')=='unique_class_saved_polygon_vertex_count_mode'
            and proof.get('model_family')=='RF-DETR-Seg Small' and proof.get('checkpoint_sha256')==checkpoint_sha
            and proof.get('human_saved') is False and proof.get('quality_gate_passed') is False
            and proof.get('corner_conversion',{}).get('algorithm')==VERSION):raise ValueError('Updated model source/class-count/provenance binding differs')
    polygon_value(p['polygon'],*p['source']['size']);geometry=corner_geometry(p['polygon'])
    if (geometry['minimum_edge_length']<SETTINGS['minimum_edge_length_pixels'] or
            geometry['minimum_abs_turn_degrees']<SETTINGS['minimum_corner_turn_degrees'] or
            geometry['minimum_corner_deviation']<SETTINGS['minimum_corner_deviation_pixels']):raise ValueError('Unsupported points cannot pad the class standard')


class UpdatedKeypointGallery(ModelMaskGallery):
    verification_state='passed_updated_M2_sources_new_images_classK_exports_not_accuracy'
    publication_namespace=NAMESPACE
    allow_class_keypoint_count_changes=True

    def __init__(self,root,reviews,key):
        root=Path(root);manifest=json.loads((root/'manifest.json').read_text())
        self.standard=json.loads((root/'class_keypoint_standard.json').read_text());self.standard_sha256=digest(root/'class_keypoint_standard.json')
        self.checkpoint_sha256=manifest['checkpoint_sha256']
        if self.standard_sha256!=manifest['class_standard_sha256']:raise ValueError('Initial class standards changed')
        super().__init__(root,reviews,key)
        text=self.edited_page.decode().replace('</html>',
            '<style>body,.mg-dialog,.mg-public-note,.mg-toast{font-family:Review,GalleryEditorSans,sans-serif}</style></html>')
        self.edited_page=text.encode()

    def validate(self,p):validate(p,self.standard,self.standard_sha256,self.checkpoint_sha256)
