"""Append-only class graph review; never changes original class or human contours."""
from collections import Counter
from contextlib import closing
import csv
import hashlib
import hmac
import io
import json
from pathlib import Path
import re

from .mask_class_correction import ROOT,STATE,NAMESPACE,majority_mapping
from .mask_gallery import Handler
from .mask_gallery_review import MaskReviewStore,ReviewError
from .mask_model_training_data import PROJECT,read,jsonl,require
from .mask_quality_recovery import fingerprint
from .cluster_targets import digest
from .pose_review_geometry import canonical


def initial_state(root):
    return dict(assignments=read(root/'assignments.json'),new_ids=read(root/'new_class_registry.json'),anchor_choices={},group_status={},reason='initial_candidate_graph')


def raw_groups(records,state):return majority_mapping(records,state['assignments'],state['new_ids'],state['anchor_choices'])


def old_class_available(records,groups,face,cls):
    return type(cls)is int and 1<=cls<=22 and groups[face]['K'] in {r['actual_K'] for r in records if r['old_class_id']==cls} and not any(
        f!=face and (g['proposed_class_id']==cls or g['proposed_class_id'] is None and cls in g['tied_majority_anchors']) for f,g in groups.items())


def compute(records,state):
    groups,newids=raw_groups(records,state)
    for g in groups.values():
        g.update(majority_proposed_class_id=g['proposed_class_id'],majority_decision=g['decision'],
            class_assignment_method='strict_majority' if g['majority_anchors'] else 'new_class_candidate',manual_class_id=None)
    for face,choice in state.get('manual_class_choices',{}).items():
        require(face in groups and isinstance(choice,dict),'人工指定旧Class的面型组不存在')
        g=groups[face];cls=choice.get('class_id')
        require(not g['majority_anchors'],'已有旧类严格过半归属，不能以人工旧类分配覆盖多数规则')
        require(choice.get('K')==g['K'] and old_class_available(records,groups,face,cls),'人工指定旧Class已占用、平票待定或实际K不兼容')
        require(isinstance(choice.get('reason'),str) and 1<=len(choice['reason'])<=2000,'人工指定旧Class须保留理由')
        g.update(proposed_class_id=cls,decision='manual_old_class_assignment',class_assignment_method='manual_old_class_assignment',manual_class_id=cls,
            manual_assignment_reason=choice['reason'])
    return groups,newids


def prune_manual_choices(records,state,groups):
    choices=state.get('manual_class_choices')
    if choices is None:return
    kept={}
    for face,choice in choices.items():
        if face in groups and not groups[face]['majority_anchors'] and choice['K']==groups[face]['K'] and old_class_available(records,groups,face,choice['class_id']):
            kept[face]=choice
    state['manual_class_choices']=kept


TOPOLOGY_ACTIONS=('merge','split','move','move_class')


def review_signatures(state,groups,include_class=True):
    members={face:[] for face in groups}
    for key,face in state['assignments'].items():members[face].append(key)
    fields=['K','old_class_counts','majority_support','majority_anchors','tied_majority_anchors']
    if include_class:fields+=['proposed_class_id','decision']
    return {face:hashlib.sha256(canonical(dict(members=sorted(members[face]),evidence={k:g[k] for k in fields}))).hexdigest() for face,g in groups.items()}


def recoverable_confirmations(records,history,current):
    """Carry original confirmations only across continuously unchanged evidence.

    Never revive a changed-away-and-back group, explicit defer/reject, or a
    confirmation omitted by an intentional full-history restoration.
    """
    candidates={};previous={}
    for event in sorted(history,key=lambda h:h['revision']):
        state=event['state'];groups,_=compute(records,state);signatures=review_signatures(state,groups)
        action=event['action']
        if action not in (*TOPOLOGY_ACTIONS,'confirm','defer','reject','anchor','recover_confirmations','reuse_old_class'):
            candidates={}
        candidates={face:proof for face,proof in candidates.items() if signatures.get(face)==proof['evidence_sha256'] and state['group_status'].get(face,'pending') not in ('defer','reject')}
        for face,status in state['group_status'].items():
            if face not in groups or status!='confirm' or groups[face]['proposed_class_id'] is None:continue
            if face not in candidates or previous.get(face)!='confirm':
                candidates[face]=dict(source_revision=event['revision'],source_action=action,source_reviewer=event['reviewer'],source_updated_at=event['updated_at'],
                    evidence_sha256=signatures[face],class_id=groups[face]['proposed_class_id'],K=groups[face]['K'],targets=groups[face]['targets'])
        previous=state['group_status']
    groups,_=compute(records,current);signatures=review_signatures(current,groups)
    return {face:proof for face,proof in candidates.items() if face not in current['group_status'] and signatures.get(face)==proof['evidence_sha256']}


def transition(records,state,action,data):
    state=json.loads(json.dumps(state));groups,_=compute(records,state);keys={r['target_key'] for r in records};known=set(groups)
    original_signatures=review_signatures(state,groups);original_evidence=review_signatures(state,groups,False)
    if action in ('confirm','defer','reject'):
        face=data.get('face_id');require(face in known,'Unknown face group')
        if action=='confirm':require(groups[face]['proposed_class_id'] is not None,'Resolve tied majority anchor first')
        state['group_status'][face]=action
    elif action=='anchor':
        face=data.get('face_id');choice=data.get('class_id');require(face in known and type(choice)is int and choice in groups[face]['tied_majority_anchors'],'Choice must be tied strict-majority class')
        state['anchor_choices'][face]=choice;state['group_status'].pop(face,None)
    elif action=='reuse_old_class':
        face=data.get('face_id');require(face in known,'Unknown source face group')
        cls=data.get('destination_class_id');require(not groups[face]['majority_anchors'],'本组已有严格过半旧类归属，不适用人工复用旧Class')
        require(old_class_available(records,groups,face,cls),'请选择未被其它面型占用、无待裁决平票且实际K兼容的旧Class1–22')
        require(groups[face]['proposed_class_id']!=cls,'本组已经归入该旧Class')
        state.setdefault('manual_class_choices',{})[face]=dict(class_id=cls,K=groups[face]['K'],reason=data.get('note','').strip())
        state['group_status'].pop(face,None)
    elif action in TOPOLOGY_ACTIONS:
        face=data.get('face_id');require(face in known,'Unknown source face group')
        if action=='merge':
            dest=data.get('destination_face');require(dest in known and dest!=face,'Choose another existing group')
            require(groups[face]['K']==groups[dest]['K'],'Different actual keypoint counts cannot be merged')
            selected=[key for key,g in state['assignments'].items() if g==face]
        else:
            selected=data.get('target_keys');require(isinstance(selected,list) and selected and len(set(selected))==len(selected) and set(selected)<=keys,'Select valid unique targets')
            require(all(state['assignments'][key]==face for key in selected),'Only selected source-group targets can move')
            if action=='split':
                require(len(selected)<groups[face]['targets'],'Cannot split entire group into an identical new group')
                token=hashlib.sha256(canonical(dict(source=face,selected=sorted(selected),graph=state['assignments']))).hexdigest()[:12];dest='H'+str(groups[face]['K'])+'-'+token
            elif action=='move_class':
                cls=data.get('destination_class_id');require(type(cls)is int and cls>0,'请选择有效的目标Class')
                matches=[g for g in groups.values() if g['proposed_class_id']==cls]
                require(len(matches)==1,'目标Class没有唯一的当前面型组；请先在面型组中处理归属或平票')
                dest=matches[0]['face_id']
                require(dest!=face,'选中目标已经属于此Class对应的面型组')
                require(groups[face]['K']==groups[dest]['K'],'不同实际点数不能移入同一Class')
            else:
                dest=data.get('destination_face');require(dest in known and dest!=face and groups[face]['K']==groups[dest]['K'],'Destination must be a different same-K group')
        for key in selected:state['assignments'][key]=dest
        # Preserve decisions only when the exact members and full vote evidence
        # remain unchanged. Duplicate vote splits can also affect indirect groups.
        old_anchors=state['anchor_choices'];state['anchor_choices']={}
        moved,_=raw_groups(records,state);new_evidence=review_signatures(state,moved,False)
        state['anchor_choices']={f:c for f,c in old_anchors.items() if f in moved and c in moved[f]['tied_majority_anchors'] and new_evidence[f]==original_evidence.get(f)}
        moved,_=raw_groups(records,state);prune_manual_choices(records,state,moved)
        if action=='move_class':
            moved,_=compute(records,state)
            if cls in moved[dest]['tied_majority_anchors']:state['anchor_choices'][dest]=cls
            moved,_=compute(records,state)
            require(moved[dest]['proposed_class_id']==cls,'移入后重新计票将改变目标Class；本次未保存，请使用面型组操作核对多数归属')
        moved,_=compute(records,state);signatures=review_signatures(state,moved)
        state['group_status']={f:s for f,s in state['group_status'].items() if f in signatures and signatures[f]==original_signatures.get(f)}
    else:raise ValueError('Unsupported review action')
    groups,newids=compute(records,state);state['new_ids']=newids
    state['reason']=data.get('note','').strip();require(1<=len(state['reason'])<=2000,'Provide a review reason')
    return state


class ClassReviewer:
    def __init__(self,gallery,directory,key):
        self.gallery=gallery;self.access_key=key.strip();require(len(self.access_key)>=20,'Original access credential required')
        self.cookie_token=hmac.new(self.access_key.encode(),NAMESPACE.encode(),hashlib.sha256).hexdigest();self.binding=gallery.manifest_sha256
        self.store=MaskReviewStore(directory,self.binding)
        with closing(self.store.connect()) as db:
            for name,value in [('namespace',NAMESPACE),('class_graph_binding',self.binding)]:
                previous=db.execute('SELECT value FROM metadata WHERE key=?',(name,)).fetchone();require(not previous or previous[0]==value,'Do not rebind class review store')
                db.execute('INSERT OR IGNORE INTO metadata VALUES (?,?)',(name,value))

    def version(self):
        with closing(self.store.connect()) as db:row=db.execute("SELECT revision FROM reviews WHERE target_key='class_graph'").fetchone()
        return dict(binding=self.binding,revision=row[0] if row else 0)

    def get(self):
        saved=self.store.get('class_graph');state=saved['state'] if saved else initial_state(self.gallery.root);groups,_=compute(self.gallery.records,state)
        for face,g in groups.items():g['review_status']=state['group_status'].get(face,'pending')
        return dict(binding=self.binding,revision=saved['revision'] if saved else 0,state=state,groups=groups,
            history=[dict(revision=r['revision'],reviewer=r['reviewer'],action=r['action'],note=r['note'],updated_at=r['updated_at']) for r in self.history()],
            targets=read(self.gallery.root/'targets.json'),source_current=self.sources_current(),provisional_only=True)

    def history(self):
        with closing(self.store.connect()) as db:return [json.loads(raw) for raw, in db.execute(
            "SELECT payload FROM events WHERE target_key='class_graph' ORDER BY revision DESC")]

    def sources_current(self):
        return all(fingerprint(PROJECT/path)==expected for path,expected in self.gallery.inputs['source_fingerprints'].items())

    def recover_confirmations(self,expected_revision):
        if not self.sources_current():raise ReviewError(409,'源标注变化，禁止恢复旧确认')
        saved=self.store.get('class_graph')
        if not saved or saved['revision']!=expected_revision:raise ReviewError(409,'类别图版本变化，请重新核对恢复计划')
        history=self.history()
        if not history or history[0]['revision']!=expected_revision:raise ReviewError(409,'历史版本变化，请重新核对恢复计划')
        proof=recoverable_confirmations(self.gallery.records,history,saved['state']);require(proof,'没有可安全恢复的历史确认')
        state=json.loads(json.dumps(saved['state']));state['group_status'].update({face:'confirm' for face in proof})
        state['reason']='修复全局清空确认：仅恢复历次成员和归属证据持续未变的人工确认'
        value=dict(state=state,reviewer='system:recover-existing-human-confirmations',action='recover_confirmations',note=state['reason'],binding=self.binding,
            source_records_sha256=self.gallery.manifest['source_records_sha256'],old_classes_overwritten=False,human_polygons_modified=False,
            automatic_training_or_GT_promotion=False,recovered_confirmations=proof,new_semantic_confirmations=False,
            confirmation_policy='invalidate_only_changed_members_or_vote_evidence_v1')
        return self.store.save('class_graph',expected_revision,value)

    def save(self,data):
        if data.get('binding')!=self.binding or not self.sources_current():raise ReviewError(409,'源标注或任务已变化；未保存，本机草稿保留')
        revision=data.get('expected_revision');reviewer=data.get('reviewer','').strip();require(type(revision)is int and revision>=0 and 1<=len(reviewer)<=80,'Valid revision and reviewer required')
        saved=self.store.get('class_graph');current=saved['state'] if saved else initial_state(self.gallery.root)
        if (saved['revision'] if saved else 0)!=revision:raise ReviewError(409,'其它窗口已更新类别图；未保存，本机草稿保留，请刷新比较')
        if data.get('action')=='restore':
            restore=data.get('restore_revision');history={r['revision']:r for r in self.history()};require(restore in history,'Restoration revision not found')
            state=history[restore]['state'];require(data.get('note','').strip(),'Restore reason required');compute(self.gallery.records,state)
        else:state=transition(self.gallery.records,current,data.get('action'),data)
        value=dict(state=state,reviewer=reviewer,action=data['action'],note=data['note'].strip(),binding=self.binding,
            source_records_sha256=self.gallery.manifest['source_records_sha256'],old_classes_overwritten=False,human_polygons_modified=False,
            restored_from_revision=data.get('restore_revision'),automatic_training_or_GT_promotion=False)
        value.update(face_id=data.get('face_id'),confirmation_policy='invalidate_only_changed_members_or_vote_evidence_v1',
            invalidated_confirmations=sorted(f for f,s in current['group_status'].items() if s=='confirm' and state['group_status'].get(f)!='confirm') if data['action'] in (*TOPOLOGY_ACTIONS,'reuse_old_class') else [])
        if data['action']=='move_class':value.update(requested_destination_class_id=data['destination_class_id'],selected_target_keys=data['target_keys'])
        if data['action']=='reuse_old_class':value.update(requested_destination_class_id=data['destination_class_id'],whole_face_group=True,
            assignment_method='manual_old_class_assignment',majority_rule_overridden=False)
        return self.store.save('class_graph',revision,value)

    def export(self,confirmed):
        value=self.get();groups=value['groups'];records={r['target_key']:r for r in self.gallery.records};result=[]
        if confirmed and not value['source_current']:raise ReviewError(409,'源轮廓已变化，旧类别确认不可套用到新版轮廓')
        for key,face in value['state']['assignments'].items():
            g=groups[face];r=records[key];approved=g['review_status']=='confirm' and g['proposed_class_id'] is not None
            result.append(dict(target_key=key,original_class_id=r['old_class_id'],actual_keypoint_count=r['actual_K'],face_group=face,
                proposed_class_id=g['proposed_class_id'],corrected_class_id=g['proposed_class_id'] if approved else None,
                review_status=g['review_status'],published_class_id=g['proposed_class_id'] if approved else r['old_class_id'],
                effective_label_is_human_confirmed=approved,source_polygon_sha256=hashlib.sha256(canonical(r['polygon'])).hexdigest(),
                class_assignment_method=g['class_assignment_method'],majority_proposed_class_id=g['majority_proposed_class_id'],
                majority_decision=g['majority_decision'],manual_class_id=g['manual_class_id']))
        # Confirmed overlay exports only changes with explicit human confirmation;
        # complete proposal export labels every unresolved record as pending.
        if confirmed:result=[r for r in result if r['effective_label_is_human_confirmed']]
        return dict(schema=NAMESPACE,revision=value['revision'],binding=self.binding,records=result,
            export_scope='confirmed_overlay_only' if confirmed else 'all_proposals_not_approved_dataset',
            source_current=value['source_current'],all2200_groups_human_confirmed=all(g['review_status']=='confirm' for g in groups.values()),
            no_training_no_GT_no_original_label_writes=True)


class ClassGallery:
    def __init__(self,root=ROOT,reviews=STATE,key=None):
        self.root=Path(root);self.manifest=read(self.root/'manifest.json');self.manifest_sha256=digest(self.root/'manifest.json')
        seal=read(self.root/'verification.json');require(seal['manifest_sha256']==self.manifest_sha256 and seal['state']=='passed2200_class_candidates_source_K_majority_not_semantic_accuracy','Independent seal required')
        self.inputs=read(self.root/'input_manifest.json');self.records=jsonl(self.root/'private/records.jsonl');self.count=len(self.records);self.publication_version=NAMESPACE
        self.assets={};self.edited_page=None;self.request_page=None
        for name,h in self.manifest['public_assets'].items():
            path=(self.root/name).resolve();require(path.is_relative_to(self.root) and not path.is_symlink() and digest(path)==h,'Public asset changed')
            mime={'.png':'image/png','.html':'text/html; charset=utf-8','.js':'application/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.otf':'font/otf','.txt':'text/plain; charset=utf-8'}[path.suffix]
            self.assets['/'+name]=(path,mime,h)
        self.csp="default-src 'none'; img-src 'self'; font-src 'self'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"
        extension=PROJECT/'outputs/pallet_mask_class_correction_checks_v1/ui_extension_v5'
        ui_version='v5'
        if not (extension/'manifest.json').exists():
            extension=PROJECT/'outputs/pallet_mask_class_correction_checks_v1/ui_extension_v4';ui_version='v4'
        if not (extension/'manifest.json').exists():
            extension=PROJECT/'outputs/pallet_mask_class_correction_checks_v1/ui_extension_v3';ui_version='v3'
        if not (extension/'manifest.json').exists():
            extension=PROJECT/'outputs/pallet_mask_class_correction_checks_v1/ui_extension_v2';ui_version='v2'
        if (extension/'manifest.json').exists():
            spec=read(extension/'manifest.json');require(spec['worklist_manifest_sha256']==self.manifest_sha256,'Review UI belongs to another worklist')
            for name,h in spec['public_assets'].items():
                path=extension/name;require(path.resolve().is_relative_to(extension) and not path.is_symlink() and digest(path)==h,'Review UI asset changed')
                mime={'.html':'text/html; charset=utf-8','.js':'application/javascript; charset=utf-8','.otf':'font/otf','.txt':'text/plain; charset=utf-8'}[path.suffix]
                self.assets['/review-ui/'+ui_version+'/'+name]=(path,mime,h)
            self.edited_page=(extension/'page.html').read_bytes()
            self.ui_extension_sha256=digest(extension/'manifest.json')
        else:
            self.ui_extension_sha256=None
        extension=PROJECT/'outputs/pallet_mask_class_correction_checks_v1/ui_extension'
        if self.edited_page is None and (extension/'manifest.json').exists():
            spec=read(extension/'manifest.json');require(spec['worklist_manifest_sha256']==self.manifest_sha256,'Comparison UI belongs to another worklist')
            require(digest(extension/'comparison.js')==spec['comparison_js_sha256'],'Comparison UI asset changed')
            self.assets['/review-ui/comparison.js']=(extension/'comparison.js','application/javascript; charset=utf-8',spec['comparison_js_sha256'])
            page=(self.root/'report_zh.html').read_text().replace('<div id="cards"',
                '<section id="comparison"><h3>旧类及拟合入面型对照</h3><div id="referenceCards" class="cards"></div></section><div id="cards"')
            page=page.replace('</style>','pre{font-family:Review,monospace}</style>')
            page=page.replace('</html>','<script src="/review-ui/comparison.js"></script></html>');self.edited_page=page.encode()
        self.editor=ClassReviewer(self,reviews,key)


class ClassHandler(Handler):
    def route(self):
        from urllib.parse import urlsplit
        if urlsplit(self.path).path=='/healthz' and self.command in ('GET','HEAD'):
            return self.json(dict(status='ok',service=NAMESPACE,targets=self.server.gallery.count,editing_enabled=True,class_only_review=True,old_services_modified=False))
        return super().route()

    def review_route(self,path):
        e=self.server.gallery.editor;reading=self.command in ('GET','HEAD')
        if path in ('/api/review/login','/api/review/logout'):return super().review_route(path)
        if path=='/api/review/bootstrap' and reading:return self.json(dict(authenticated=self.authenticated(),binding=e.binding))
        if not self.authenticated():raise ReviewError(401,'沿用原访问码，登录后复核类别')
        if path=='/api/review/graph' and reading:return self.json(e.get())
        if path=='/api/review/version' and reading:return self.json(e.version())
        if path=='/api/review/action' and self.command=='POST':return self.json(dict(saved=e.save(self.body())))
        if path in ('/api/review/export/confirmed.json','/api/review/export/proposals.json') and reading:return self.json(e.export('confirmed' in path))
        if path in ('/api/review/export/confirmed.csv','/api/review/export/proposals.csv') and reading:
            value=e.export('confirmed' in path);stream=io.StringIO();fields=['target_key','original_class_id','actual_keypoint_count','face_group','proposed_class_id','corrected_class_id','review_status','published_class_id','effective_label_is_human_confirmed','source_polygon_sha256','class_assignment_method','majority_proposed_class_id','majority_decision','manual_class_id']
            writer=csv.DictWriter(stream,fieldnames=fields);writer.writeheader();writer.writerows(value['records'])
            return self.respond(200,stream.getvalue().encode('utf-8-sig'),'text/csv; charset=utf-8',headers={'Content-Disposition':'attachment; filename="class-correction.csv"'})
        raise ReviewError(404,'Unknown class review endpoint')


def write_assets(root):
    assets=Path(__file__).with_name('assets')/'mask_class_correction'
    for source,dest in [('page.html','report_zh.html'),('review.js','review.js')]:(root/dest).write_bytes((assets/source).read_bytes())
    from scripts.build_mask_remaining_direct_requests import build_font
    build_font(root,(root/'report_zh.html').read_text()+(root/'review.js').read_text())
