"""Fast read/save adapter; legacy bound reviewers, tasks and history stay intact."""
from .mask_gallery_review import ReviewError
from .mask_model_training_data import FALSE_FLAGS, sha
from .mask_taxonomy_review import TaxonomyEditor
from .pose_review_geometry import polygon_value


class FastTaxonomyEditor(TaxonomyEditor):
    def __init__(self, existing, guard):
        # The existing editor has already validated the isolated store, namespace,
        # manifest, credential and cookie. Reuse them without rebinding the DB.
        for name in ('gallery','access_key','binding','cookie_token','store','proposals'):
            setattr(self,name,getattr(existing,name))
        self.source_guard=guard

    def detail(self,key):
        p=self.proposal(key);current=self.store.get(key)
        return dict(proposal=p,review=current,history=self.store.history(key),binding=self.binding,
            source_binding=sha(p),source_current=self.source_guard.current())

    def save(self,key,data):
        p=self.proposal(key)
        if data.get('binding')!=self.binding or data.get('source_binding')!=sha(p):raise ReviewError(409,'任务版本已改变，本机草稿保留，不覆盖旧修订')
        if not self.source_guard.current():raise ReviewError(409,'来源类别／原人工历史有新版本，本机草稿保留，需重新整合任务')
        expected=data.get('expected_revision');reviewer=data.get('reviewer');note=data.get('note','');action=data.get('action')
        if type(expected)is not int or expected<0 or not isinstance(reviewer,str) or not 1<=len(reviewer.strip())<=80 or not isinstance(note,str) or len(note)>2000 or action not in ('draft','correct','defer'):
            raise ReviewError(400,'请填写标注人、有效操作与修订版本；备注为选填')
        cls=data.get('class_id');info=self.gallery.classes.get(str(cls))
        if type(cls)is not int or not info or not info['train_enabled']:raise ReviewError(400,'请选择有效细类；Class37/47暂未解决')
        try:polygon=polygon_value(data.get('polygon'),*p['source']['size'])
        except (TypeError,ValueError) as e:raise ReviewError(400,str(e)) from e
        if action=='correct' and len(polygon)!=info['K']:raise ReviewError(400,f'改为Class{cls}后必须为K{info["K"]}，当前{len(polygon)}点；本机草稿保留，可先存草稿')
        restored=data.get('restored_from_revision')
        if restored is not None and (type(restored)is not int or restored not in {h['revision'] for h in self.store.history(key)}):raise ReviewError(400,'恢复历史不存在')
        value=dict(target_key=key,binding=self.binding,source_binding=sha(p),base_proposal_id=sha(p),
            class_id=cls,expected_K=info['K'],polygon=polygon,vertex_count=len(polygon),class_K_matches=len(polygon)==info['K'],
            original_formal_class_id=p['original_formal_class_id'],initial_proposed_class_id=p['class_id'],
            action=action,reviewer=reviewer.strip(),note=note.strip(),restored_from_revision=restored,
            event_kind='human_new_fine_class_mask_review',source=p['source'],checkpoint_sha256=p['checkpoint_sha256'],
            human_review_action=True,formal_class_or_polygon_written=False,original_proposal_modified=False,
            automatic_GT_training_or_robot_promotion=False,propagation_seed_eligible=False,**FALSE_FLAGS)
        # Probe again after validation, immediately before the original atomic
        # revision compare-and-append. Never rebase a stale client revision.
        if not self.source_guard.current():raise ReviewError(409,'来源在保存前发生变化，本机草稿保留，不覆盖历史')
        return self.store.save(key,expected,value)
