"""Derive a ready-to-publish task page while retaining its original inspection pack."""
from pathlib import Path
import json
import shutil
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


def main():
    source=PROJECT/'outputs/pallet_mask_remaining_direct_requests_v1'
    out=PROJECT/'outputs/pallet_mask_remaining_direct_requests_v2'
    if out.exists():raise ValueError('Preserve the derived public task pack')
    seal=json.loads((source/'independent_verification.json').read_text())
    if seal['state']!='passed' or seal['manifest_sha256']!=digest(source/'manifest.json'):
        raise ValueError('First independently verify the frozen inspection pack')
    manifest=json.loads((source/'manifest.json').read_text());out.mkdir()
    names=set(manifest['public_assets'])|{'requests.jsonl','input_manifest.json',
        'internal/source_visual_decisions.json','internal/protected_formal_after.json'}
    for name in names:
        target=out/name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source/name,target)
    page=(out/'report_zh.html').read_text()
    page=page.replace('未激活的待办草稿；本页任务尚未保存，不是新增标签。',
        '本批50张直接人工任务尚未保存，不提前计入1,061张覆盖；上一批51张已保存，不重复请求。')
    page=page.replace('任务数量不计入已完成覆盖；需独立验收后再决定是否上线。',
        '请按实际可见轮廓描绘并保存；任务数量不计入已完成覆盖。<a href="/?revision=10#new-batch">复核本轮369张机器候选</a>。')
    (out/'report_zh.html').write_text(page)
    from fontTools import subset
    from fontTools.ttLib import TTFont
    with TTFont('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf') as font:
        sub=subset.Subsetter();sub.populate(text=page);sub.subset(font);font.save(out/'report-font.otf')
    manifest.update(public_assets={name:digest(out/name) for name in manifest['public_assets']},
        source_inspection_pack=str(source.relative_to(PROJECT)),source_inspection_manifest_sha256=digest(source/'manifest.json'),
        source_inspection_independent_verification_sha256=digest(source/'independent_verification.json'),
        derived_public_page_script_sha256=digest(__file__))
    (out/'manifest.json').write_bytes(canonical(manifest)+b'\n')
    print('Derived 50-task page ready for its own independent seal; source inspection and histories retained',flush=True)


if __name__=='__main__':main()
