"""Keep the completed 25-image worklist online as history, not fresh requests."""
from contextlib import closing
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():
    batch=PROJECT/'outputs/pallet_mask_quota_100_complete_v1'
    source=PROJECT/'outputs/pallet_mask_quota_100_final_requests_v2'
    out=PROJECT/'outputs/pallet_mask_quota_100_final_requests_v4'
    deployment=PROJECT/'outputs/pallet_mask_quota_100_complete_deployment_v1'
    if out.exists():raise ValueError('Preserve completed worklist history')
    seal=json.loads((batch/'verification.json').read_text())
    if (seal['state']!='passed' or seal['publication_version']!=9 or seal['proposals_verified']!=500
            or seal['manual_verified']!=25 or seal['proposals_sha256']!=digest(batch/'proposals.jsonl')):
        raise ValueError('Expected verified 25 actual manual sources in the 500-frame release')
    verified=json.loads((source/'verification.json').read_text())
    if verified['state']!='passed' or verified['requests_sha256']!=digest(source/'requests.jsonl'):
        raise ValueError('Original request history differs')
    requests=list(map(json.loads,(source/'requests.jsonl').read_text().splitlines()))
    manual={p['target_key']:p for p in map(json.loads,(batch/'manual_proposals.jsonl').read_text().splitlines())}
    if len(requests)!=25 or {r['target_key'] for r in requests}!=set(manual):
        raise ValueError('Actual human masks and worklist target keys differ')
    pose=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    with closing(sqlite3.connect(pose.as_uri()+'?mode=ro',uri=True)) as db:
        for key,p in manual.items():
            row=db.execute('SELECT payload FROM annotations WHERE target_key=?',(key,)).fetchone()
            if not row or json.loads(row[0])['polygon']!=p['polygon']:
                raise ValueError('Actual saved manual mask changed before worklist completion')
    out.mkdir()
    for name,expected in verified['public_assets'].items():
        if digest(source/name)!=expected:raise ValueError('Original worklist public asset changed')
        target=out/name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source/name,target)
    shutil.copyfile(source/'requests.jsonl',out/'requests.jsonl')
    page=(out/'report_zh.html').read_text()
    notice='''<div class="notice"><strong>25 / 25 张人工任务已保存并完成来源核验。本页是历史清单，无需重复标注。</strong>
<p>Class 9十张、Class 10十五张均已计入最终图册，五类各100张不同图像，共500张覆盖。
<a href="/?revision=9">打开最终500张图册及在线修改界面</a>。</p>
<p>本轮66张复核均已保存。此前45张已核实全部来自上一轮84张，按用户明确说明登记为“已复核、无需修改”，不重复请求。
此说明不伪造数据库保存事件，不标成人工编辑，也不升级GT或训练、机器人资格。</p>
<p>原任务图片和标注链接仍保留以便查看修订历史。如需继续精调，请先查看服务器最新记录；
不覆盖旧修订、其它对象、正式划分或原GT。</p></div>'''
    page=re.sub(r'<div class="notice">.*?</div>',lambda _:notice,page,count=1,flags=re.S)
    page=page.replace('待命待人工描绘','已保存历史清单').replace('待人工描绘','已保存历史清单')
    page=page.replace('待命未激活','已保存历史清单').replace('待命已保存历史清单','已保存历史清单')
    table='<table><tr><th>类别</th><th>最终不同图像</th><th>距100缺额</th><th>本批已保存</th></tr>'
    table+=''.join(f'<tr><td>{c}</td><td>100</td><td>0</td><td>{10 if c==9 else 15 if c==10 else 0}</td></tr>' for c in (1,2,9,10,15))+'</table>'
    page=re.sub(r'<table>.*?</table>',lambda _:table,page,count=1,flags=re.S)
    page=page.replace('<h2>选择与保护边界</h2>','<h2>原任务选择与保护边界（以下为选择时的历史快照，并非当前待办）</h2>')
    page=page.replace('needs_manual_tracing · 已保存历史清单 · 不计入475。','saved_manual_worklist_history · 已保存历史清单 · 已按实际保存计入最终500张。')
    (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('Completed worklist Chinese font coverage incomplete')
    manifest=dict(state='completed_manual_worklist_history',request_count=25,completed_request_count=25,
        requests_by_class={9:10,10:15},published_frames=500,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,
        worklist_not_additional_candidates=True)
    (out/'manifest.json').write_bytes(canonical(manifest)+b'\n')
    verification=dict(state='passed',request_count=25,completed_request_count=25,
        requests_sha256=digest(out/'requests.jsonl'),
        public_assets={name:digest(out/name) for name in verified['public_assets']},
        source_batch_verification_sha256=digest(batch/'verification.json'))
    (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=25,target_per_class=100,counts_as_completed_annotation=False,
        user_authorization='最后25项已实际保存并通过独立来源核验，保留历史清单，不重复请求')
    proposed=deployment/'proposed_completed_manual_requests.json';proposed.write_bytes(canonical(config)+b'\n')
    loaded=load_requests(proposed,PROJECT)
    if loaded['count']!=25 or loaded['completed']!=25:raise ValueError('Completed worklist summary differs')
    print(json.dumps(dict(state='completed_worklist_ready',directory=config['directory'],completed=25,production_annotation_writes=0)))


if __name__=='__main__':main()
