"""Freeze the final thirteen manual requests after the 237-frame audit passes."""
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.pose_review_geometry import canonical
from pallet.mask_template_requests import load_requests


def main():
    parent=PROJECT/'outputs/pallet_mask_class10_manual_supplement_v1'
    batch=PROJECT/'outputs/pallet_mask_quota_completion_v2'
    out=PROJECT/'outputs/pallet_mask_class10_manual_supplement_v2'
    seal=json.loads((batch/'verification.json').read_text())
    assert seal['state']=='passed' and seal['proposals_verified']==237
    assert seal['classes']['10']['shortfall']==13
    if out.exists():raise ValueError('Preserve prior worklist publication')
    verification=json.loads((parent/'verification.json').read_text())
    assert verification['state']=='passed' and digest(parent/'requests.jsonl')==verification['requests_sha256']
    requests=list(map(json.loads,(parent/'requests.jsonl').read_text().splitlines()))
    existing=list(map(json.loads,(batch/'proposals.jsonl').read_text().splitlines()))
    assert len(requests)==len({r['target_key'] for r in requests})==13
    assert not ({r['source']['frame_id'] for r in requests}&{r['source']['frame_id'] for r in existing})
    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:
            assert r['class_id']==10 and not r['counts_as_completed_annotation']
            assert not db.execute('SELECT 1 FROM annotations WHERE target_key=?',(r['target_key'],)).fetchone()
            assert not db.execute('SELECT 1 FROM events WHERE target_key=?',(r['target_key'],)).fetchone()
    out.mkdir()
    for name,sha in verification['public_assets'].items():
        assert digest(parent/name)==sha
        dest=out/name;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(parent/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('Class 10 人工补充备用清单 · 13 帧 · 未激活','Class 10 最后13张人工描绘任务')
    page=page.replace('Class 10 人工模板补充：13 帧备用清单','Class 10：最后13张人工描绘任务')
    start=page.index('<div class="notice">');end=page.index('<h2>选择原则与边界</h2>',start)
    notice='''<div class="notice"><strong>本页13张仍需人工描绘保存，未提前计入完成数量。</strong>
<p>最新图册已覆盖237张不同图像：Class 1、2、9、15各50张，Class 10为37张，还缺13张。</p>
<p>24张补充模板均已保存并计入；另6份既有Class 10人工轮廓已独立核验纳入。所有原始数据和修订历史保留。
本页13张目前没有位姿保存记录或历史。逐张点击“打开位姿标注”，沿实际托盘面轮廓描绘并保存，即可使Class 10达到50张。</p>
<p>请不要只保存原始矩形，不为凑数添加冗余顶点。类别或结构可疑时先说明，不自动确认为GT。
<a href="/">返回237张图册</a>。原97条精调、30份人工源及110份待复核机器候选分开统计。</p></div>'''
    page=page[:start]+notice+page[end:]
    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')
    required={ord(c) for c in page if '\u3400'<=c<='\u9fff'}
    assert required<=set(TTFont(out/'report-font.otf').getBestCmap())
    manifest=dict(state='active_manual_worklist_not_completed',requests=13,class_id=10,current_class_total=37,
        current_published_total=237,manual_work_required=True,parent=str(parent.relative_to(PROJECT)),
        parent_verification_sha256=digest(parent/'verification.json'),verified_batch=str(batch.relative_to(PROJECT)),
        verified_batch_sha256=digest(batch/'verification.json'),production_annotation_writes=0)
    (out/'manifest.json').write_bytes(canonical(manifest)+b'\n')
    sealed=dict(state='passed',request_count=13,requests_sha256=digest(out/'requests.jsonl'),
        public_assets={name:digest(out/name) for name in verification['public_assets']},counts_as_completed_annotation=False)
    (out/'verification.json').write_bytes(canonical(sealed)+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=13,
        completed_request_count=0,counts_as_completed_annotation=False,user_authorization='补充人工模板，继续补齐五类各50张')
    proposed=PROJECT/'outputs/pallet_mask_quota_deployment_v1/proposed_manual_requests.json'
    proposed.write_bytes(canonical(config)+b'\n');assert load_requests(proposed,PROJECT)['count']==13
    print(json.dumps(dict(state='verified_ready_to_activate',directory=config['directory'],request_count=13)))


if __name__=='__main__':main()
