"""Build filter patch without altering frozen pages, policy or review values."""
from pathlib import Path
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.mask_model_training_data import read,write,require
from pallet.cluster_targets import digest
from pallet.mask_class_note_integration import snapshot_db
from pallet.pallet_description_round6_release import REVIEW_SETS
from serve_pallet_review_description_first import validate,RELEASE as LAYOUT
from serve_pallet_review_filter_sync import RELEASE
from build_mask_remaining_direct_requests import build_font


def prepare():
    from fontTools.ttLib import TTFont
    base=validate('existing');require(not RELEASE.exists(),'Preserve prior filter release');RELEASE.mkdir(mode=0o700)
    page=(LAYOUT/'page.html').read_text();anchor='<div id="cards"></div>'
    require(page.count(anchor)==1,'Unexpected list anchor')
    page=page.replace(anchor,'<p id="activeReviewFilters" role="status"></p><p id="filterFeedback" role="status" aria-live="polite"></p><button id="showLastCompleted" type="button" hidden>查看刚完成的已复核记录</button>'+anchor)
    (RELEASE/'page.html').write_text(page)
    source=(base/'review.js').read_text();anchor='window.taxonomyDiagnostics=()=>';require(source.count(anchor)==1,'Unexpected UI hook')
    script=source.replace(anchor,(PROJECT/'pallet/assets/pallet_review_filter_sync.js').read_text()+'\n'+anchor);(RELEASE/'review.js').write_text(script)
    with TTFont(base/'report-font.otf') as font:chars=''.join(chr(c) for c in font.getBestCmap())
    build_font(RELEASE,page+script+chars)
    s=REVIEW_SETS['existing'];snapshot_db(s['reviews']/'mask_reviews.sqlite3',RELEASE/'before.sqlite3')
    write(RELEASE/'manifest.json',dict(base_manifest_sha256=digest(base/'manifest.json'),layout_manifest_sha256=digest(LAYOUT/'manifest.json'),source_script_sha256=digest(base/'review.js'),
        assets={n:digest(RELEASE/n) for n in ('page.html','review.js','report-font.otf')},task_manifest_sha256=digest(s['root']/'manifest.json'),
        policy_sha256=digest(base/'policy.json'),reinspection_sha256=digest(base/'reinspection.json'),change='filter_coordination_and_visible_history_feedback_only'))
    write(RELEASE/'before.json',dict(supervisor=read(s['managed']/'supervisor.json'),transport=read(s['managed']/'transport.json'),new_service=read(REVIEW_SETS['new']['managed']/'supervisor.json'),
        protected={str(p.relative_to(PROJECT)):digest(p) for p in (s['root']/'manifest.json',s['root']/'proposals.jsonl',s['managed']/'runtime.json',base/'policy.json',base/'reinspection.json')}))
    print('Filter coordination overlay prepared; production annotations unchanged')


if __name__=='__main__':prepare()
