"""Class-standard machine keypoints, with user-editable human vertex counts."""
import json
from pathlib import Path

from .cluster_targets import digest
from .mask_class_keypoints import VERSION,corner_geometry,SETTINGS
from .mask_model_review import ModelMaskGallery,HUMAN_KEYPOINT_EDIT_POLICY
from .mask_model_worklist import validate_proposal
from .mask_gallery import ASSETS

EXTENSION=Path(__file__).resolve().parents[1]/'outputs/pallet_mask_class_keypoint_edit_extension_v1'
EDIT_NOTICE='初始预标注仍按类别标准点数。人工微调可点击边增点、拖动点或删选中点（3–128点）；增点后可以保存，类别标准和原机器草稿不变。'


def editor_js():
    """Historical fixed-K generator, kept for frozen package reproducibility."""
    text=(ASSETS/'editor.js').read_text().replace("'mask-gallery-v1:'","'mask-class-keypoints-v3:'")
    text=text.replace("'机器建议 · 尚未人工保存'","'类别固定点数关键点草稿 · 尚未人工复核'")
    text=text.replace("$('mgDeleteVertex').disabled=!editable||selected<0||polygon.length<=3;",
        "$('mgDeleteVertex').disabled=!!detail?.class_keypoint_constraint||!editable||selected<0||polygon.length<=3;")
    text=text.replace('function deleteVertex(){',"function deleteVertex(){if(detail?.class_keypoint_constraint){toast('类别关键点数量固定，请拖动现有点，不增删点');return;}")
    text=text.replace('if(edge>=0){if(polygon.length>=128)',
        "if(edge>=0){if(detail.class_keypoint_constraint){toast('类别关键点数量固定，请拖动现有点，不增删点');return;}if(polygon.length>=128)")
    text=text.replace("$('mgTarget').textContent=`Class ${value.class_id}",
        "$('mgTarget').textContent=`固定 ${value.class_keypoint_constraint.standard_count} 点 · Class ${value.class_id}")
    return text


def editable_editor_js():
    """Restore the original edge-insertion/deletion/undo code and draft key."""
    text=(ASSETS/'editor.js').read_text().replace("'mask-gallery-v1:'","'mask-class-keypoints-v3:'")
    text=text.replace("'机器建议 · 尚未人工保存'","'类别标准点数预标注 · 人工微调可增点'")
    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_keypoints(p,standard,standard_sha):
    validate_proposal(p);constraint=p.get('class_keypoint_constraint',{})
    k=standard['classes'][str(p['class_id'])]['standard_count']
    if (type(k) is not int or len(p['polygon'])!=k or p['vertex_count']!=k or constraint.get('standard_count')!=k
            or constraint.get('class_id')!=p['class_id'] or constraint.get('standard_sha256')!=standard_sha
            or constraint.get('method')!='unique_class_saved_polygon_vertex_count_mode'
            or p['model_provenance'].get('corner_conversion',{}).get('algorithm')!=VERSION):
        raise ValueError('Class keypoint count/standard/provenance mismatch')
    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('Redundant or unsupported corners cannot pad class keypoint counts')


class ClassKeypointGallery(ModelMaskGallery):
    verification_state='passed_class_modes_exact_K_model_conversion_exports_protection_not_accuracy'
    publication_namespace='model-class-keypoints-v3'
    allow_class_keypoint_count_changes=True

    def __init__(self,root,reviews,key):
        self.standard=json.loads((Path(root)/'class_keypoint_standard.json').read_text())
        self.standard_sha256=digest(Path(root)/'class_keypoint_standard.json')
        m=json.loads((Path(root)/'manifest.json').read_text())
        if m['class_standard_sha256']!=self.standard_sha256:raise ValueError('Class count standard changed')
        super().__init__(root,reviews,key)
        extension=json.loads((EXTENSION/'editor_extension_manifest.json').read_text())
        if (extension.get('policy')!=HUMAN_KEYPOINT_EDIT_POLICY or extension.get('initial_worklist_manifest_sha256')!=self.manifest_sha256
                or extension.get('class_standard_sha256')!=self.standard_sha256):raise ValueError('Human editing extension is not bound to this frozen worklist')
        if set(extension['assets'])!={'editor.js','report-font.otf','FONT_LICENSE.txt'}:raise ValueError('Unexpected editor-extension resource')
        for name,expected in extension['assets'].items():
            path=EXTENSION/name
            if path.is_symlink() or not path.is_file() or digest(path)!=expected:raise ValueError('Editor-extension resource changed')
        self.assets['/review-ui/editor.js']=(EXTENSION/'editor.js','text/javascript; charset=utf-8',extension['assets']['editor.js'])
        self.assets['/review-ui/human-edit-font.otf']=(EXTENSION/'report-font.otf','font/otf',extension['assets']['report-font.otf'])
        self.assets['/review-ui/human-edit-FONT_LICENSE.txt']=(EXTENSION/'FONT_LICENSE.txt','text/plain; charset=utf-8',extension['assets']['FONT_LICENSE.txt'])
        self.editor_extension_sha256=digest(EXTENSION/'editor_extension_manifest.json')
        text=self.edited_page.decode()
        # New class-count wording includes glyphs absent from the historical
        # editor font subset. Use the verified report subset first, with the
        # original editor font as fallback for older controls.
        text=text.replace('</html>','<style>@font-face{font-family:ClassHumanEdit;src:url("/review-ui/human-edit-font.otf")}body,.mg-dialog,.mg-public-note,.mg-toast{font-family:ClassHumanEdit,Review,GalleryEditorSans,sans-serif}</style></html>')
        text=text.replace('全部满足所属类别点数；不再展示密集边界。拖动现有关键点，点数固定，不增删点。',
            '全部初始预标注满足所属类别点数；不再展示密集边界。'+EDIT_NOTICE)
        text=text.replace(' · 固定', ' · 初始标准')
        text=text.replace('/review-ui/editor.js?v=mask-gallery-editor-v1','/review-ui/editor.js?v=class-keypoint-human-edit-v1')
        self.edited_page=text.encode()

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