"""Publish a separate 25-image manual worklist after the 475-frame seal passes."""
from collections import Counter
from contextlib import closing
import hashlib
import json
from pathlib import Path
import re
import shutil
import sqlite3
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest
from pallet.mask_template_requests import load_requests
from pallet.pose_review_geometry import canonical


def main():
    source=PROJECT/'outputs/pallet_mask_quota_100_final_requests_v1'
    batch=PROJECT/'outputs/pallet_mask_quota_100_continue_v1'
    out=PROJECT/'outputs/pallet_mask_quota_100_final_requests_v2'
    deployment=PROJECT/'outputs/pallet_mask_quota_100_continue_deployment_v1'
    if out.exists():raise ValueError('Preserve the frozen manual worklist')
    seal=json.loads((batch/'verification.json').read_text())
    if (seal['state']!='passed' or seal['publication_version']!=8 or seal['proposals_verified']!=475
            or seal['proposals_sha256']!=digest(batch/'proposals.jsonl')):
        raise ValueError('Expected independently verified 475-frame publication')
    verified=json.loads((source/'verification.json').read_text())
    if verified['state']!='passed' or digest(source/'requests.jsonl')!=verified['requests_sha256']:
        raise ValueError('Manual worklist verification differs')
    requests=list(map(json.loads,(source/'requests.jsonl').read_text().splitlines()))
    if len({r['target_key'] for r in requests})!=25 or Counter(r['class_id'] for r in requests)!={9:10,10:15}:
        raise ValueError('Expected Class 9 ten requests and Class 10 fifteen requests')
    published=list(map(json.loads,(batch/'proposals.jsonl').read_text().splitlines()))
    if {r['source']['frame_id'] for r in requests}&{p['source']['frame_id'] for p in published}:
        raise ValueError('Manual worklist repeats a published image')
    pose=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    with closing(sqlite3.connect(pose.as_uri()+'?mode=ro',uri=True)) as db:
        for r in requests:
            row=db.execute('SELECT revision,payload FROM annotations WHERE target_key=?',(r['target_key'],)).fetchone()
            if row:
                if (not r.get('existing_pose_record') or row[0]!=r['existing_pose_revision'] or
                        hashlib.sha256(canonical(json.loads(row[1]))).hexdigest()!=r['existing_pose_payload_sha256']):
                    raise ValueError('Manual source changed before activation')
            elif r.get('existing_pose_record'):raise ValueError('Manual source record missing')
    out.mkdir()
    for name,expected in verified['public_assets'].items():
        if digest(source/name)!=expected:raise ValueError('Manual worklist public asset changed')
        target=out/name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source/name,target)
    for r in requests:r['activation_state']='active_manual_worklist_not_completed'
    (out/'requests.jsonl').write_bytes(b''.join(canonical(r)+b'\n' for r in requests))
    page=(out/'report_zh.html').read_text()
    notice='''<div class="notice"><strong>最后25张人工补充任务尚未保存，不提前计入475张。</strong>
<p>当前Class 1、2、15各100张覆盖，Class 9为90张，Class 10为85张；本页为Class 9的10张和Class 10的15张。</p>
<p><a href="/?revision=8#new-batch">打开本轮66张机器候选复核</a>。475张中321张有人工保存轮廓、154张机器候选待复核；覆盖数不等于全部人工确认。
原84张候选中服务器已收到39张新保存记录，其余45张请核对本机草稿并点击保存修订，不能把翻页记录当作新修订。</p>
<p>请沿实际可见轮廓描绘并保存，不能只保存原矩形或添加无意义顶点。实际四边形保留四点，可计入人工图像覆盖，但不作超过四顶点的传播模板。
已有原矩形位姿记录的任务请先查看原位姿、面和标尺；只有人工主动决定时才修改，其它对象与历史保留。</p>
<p>这些25张完成保存并通过来源与图像去重核验后，可达到五类各100张覆盖；仍不自动升级GT或训练、机器人资格。</p></div>'''
    if re.search(r'<div class="notice">.*?</div>',page,flags=re.S):
        page=re.sub(r'<div class="notice">.*?</div>',lambda _:notice,page,count=1,flags=re.S)
    else:page=page.replace('<body>','<body>'+notice,1)
    page=page.replace('未激活','待人工描绘').replace('备用清单','人工任务清单')
    (out/'report_zh.html').write_text(page)
    from fontTools import subset
    from fontTools.ttLib import TTFont
    font=TTFont('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf');sub=subset.Subsetter();sub.populate(text=page);sub.subset(font);font.save(out/'report-font.otf')
    if not {ord(c) for c in page if '\u3400'<=c<='\u9fff'}<=set(TTFont(out/'report-font.otf').getBestCmap()):
        raise ValueError('Manual worklist Chinese font coverage incomplete')
    manifest=dict(state='active_manual_worklist_not_completed',request_count=25,requests_by_class={9:10,10:15},
        target_per_class=100,published_frames=475,parent=str(source.relative_to(PROJECT)),
        parent_verification_sha256=digest(source/'verification.json'),batch=str(batch.relative_to(PROJECT)),
        batch_verification_sha256=digest(batch/'verification.json'),production_annotation_writes=0,
        counts_as_completed_annotation=False)
    (out/'manifest.json').write_bytes(canonical(manifest)+b'\n')
    verification=dict(state='passed',request_count=25,requests_sha256=digest(out/'requests.jsonl'),
        public_assets={name:digest(out/name) for name in verified['public_assets']},counts_as_completed_annotation=False)
    (out/'verification.json').write_bytes(canonical(verification)+b'\n')
    config=dict(schema='manual_mask_template_worklist_v1',directory=str(out.relative_to(PROJECT)),
        manifest_sha256=digest(out/'manifest.json'),verification_sha256=digest(out/'verification.json'),
        request_count=25,completed_request_count=0,target_per_class=100,counts_as_completed_annotation=False,
        user_authorization='补充人工模板，继续补齐五类各100张')
    proposed=deployment/'proposed_active_manual_requests.json';proposed.write_bytes(canonical(config)+b'\n')
    if load_requests(proposed,PROJECT)['count']!=25:raise ValueError('Manual publication count differs')
    print(json.dumps(dict(state='verified_worklist_ready_to_activate',directory=config['directory'],requests=25)))


if __name__=='__main__':main()
