"""Derive the 100-frame human worklist after independent batch verification."""
from contextlib import closing
import json
from pathlib import Path
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_requests_v1'
    batch=PROJECT/'outputs/pallet_mask_quota_100_v2'
    out=PROJECT/'outputs/pallet_mask_quota_100_requests_v2'
    deployment=PROJECT/'outputs/pallet_mask_quota_100_deployment_v1'
    if out.exists():raise ValueError('Preserve existing worklist publication')
    seal=json.loads((batch/'verification.json').read_text())
    if seal['state']!='passed' or seal['publication_version']!=7:raise ValueError('Expected verified publication 7')
    if seal['proposals_sha256']!=digest(batch/'proposals.jsonl'):raise ValueError('Batch proposal hash differs')
    verified=json.loads((source/'verification.json').read_text())
    if verified['state']!='passed' or digest(source/'requests.jsonl')!=verified['requests_sha256']:
        raise ValueError('Worklist verification differs')
    requests=list(map(json.loads,(source/'requests.jsonl').read_text().splitlines()))
    if len(requests)!=24 or len({r['target_key'] for r in requests})!=24:raise ValueError('Expected 24 unique 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 published frame')
    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['existing_pose_record'] or row[0]!=r['existing_pose_revision']:
                    raise ValueError('Manual request pose revision changed')
                import hashlib
                if hashlib.sha256(canonical(json.loads(row[1]))).hexdigest()!=r['existing_pose_payload_sha256']:
                    raise ValueError('Manual request pose payload changed')
            elif r['existing_pose_record']:raise ValueError('Manual request source missing')
    out.mkdir()
    for name,sha in verified['public_assets'].items():
        if digest(source/name)!=sha:raise ValueError('Worklist asset changed')
        dest=out/name;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source/name,dest)
    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()
    page=page.replace('每类100帧目标 · 独立人工模板请求 · 未激活','每类100帧目标 · 补充人工模板')
    start=page.index('<div class="notice">');end=page.index('</div>',start)+len('</div>')
    page=page[:start]+'''<div class="notice"><strong>新增84张候选已独立验证，先复核机器结果，再按需要描绘本页24张补充模板。</strong>
<p>当前累计378个不同帧：251份已保存人工轮廓、43份历史待复核机器候选、84份本轮新增待复核机器候选。
<a href="/?revision=7#new-batch">打开84张复核图册</a>。五类各100张的目标尚缺122张，不以失败匹配凑数。</p>
<p>本页24张仍未完成，不提前计入378张。Class 1、10各10张，Class 9、15各2张；Class 2不额外请求。
其中18张已有原矩形位姿记录，必须先查看现有位姿及备注，只有人工主动决定时才修改；其他目标和历史不删除。
完成后需保存，才能在后续核验中作为直接人工模板。已保存不等于确认GT，不能用冗余共线点凑顶点数。</p></div>'''+page[end:]
    (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('Incomplete Chinese font coverage')
    manifest=dict(state='active_manual_worklist_not_completed',request_count=24,target_per_class=100,
        published_frames=378,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=24,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=24,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']!=24:raise ValueError('Publication request count differs')
    print(json.dumps(dict(state='verified_worklist_ready_to_activate',directory=config['directory'],requests=24)))


if __name__=='__main__':main()
