"""Prepare a verified direct-manual config; activation is a separate atomic step."""
from contextlib import closing
import json
from pathlib import Path
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():
    root=PROJECT/'outputs/pallet_mask_remaining_direct_requests_v2'
    out=PROJECT/'outputs/pallet_mask_remaining_expand_deployment_v1'
    parent=PROJECT/'outputs/pallet_mask_remaining_expand_v1'
    seal=json.loads((root/'independent_verification.json').read_text())
    if (seal['state']!='passed' or seal['request_count']!=50 or seal['manifest_sha256']!=digest(root/'manifest.json') or
            seal['requests_sha256']!=digest(root/'requests.jsonl') or seal['parent_verification_sha256']!=digest(parent/'verification.json')):
        raise ValueError('Matching independent 50-task and publication-10 seals required')
    requests=list(map(json.loads,(root/'requests.jsonl').read_text().splitlines()))
    from hashlib import sha256
    with closing(sqlite3.connect((PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3').as_uri()+'?mode=ro',uri=True)) as db:
        for r in requests:
            row=db.execute('SELECT payload FROM annotations WHERE target_key=?',(r['target_key'],)).fetchone()
            actual=sha256(canonical(json.loads(row[0]))).hexdigest() if row else None
            if actual!=r['existing_pose_payload_sha256']:
                raise ValueError('A manual target changed after verification; preserve it rather than overwrite')
    verified=root/'verification.json'
    if verified.exists():raise ValueError('Preserve completed public-loader verification')
    value=dict(state='passed',request_count=50,requests_sha256=seal['requests_sha256'],public_assets=seal['public_assets'],
        independent_verification_sha256=digest(root/'independent_verification.json'),counts_as_completed_annotation=False)
    verified.write_bytes(canonical(value)+b'\n')
    config=dict(schema='manual_mask_template_worklist_v1',directory=str(root.relative_to(PROJECT)),
        manifest_sha256=digest(root/'manifest.json'),verification_sha256=digest(verified),request_count=50,
        completed_request_count=0,target_per_class=100,requested_classes=[4,5,7,14,22],counts_as_completed_annotation=False,
        user_authorization='已完成51项后继续：对真实四点类别补充不同图像的直接人工覆盖，不强行增点或重画已完成轮廓')
    proposed=out/'proposed_direct_manual_config.json'
    if proposed.exists():raise ValueError('Preserve prior proposed activation')
    proposed.write_bytes(canonical(config)+b'\n')
    if load_requests(proposed,PROJECT)['count']!=50:raise ValueError('Public loader rejected exact worklist')
    print('Verified 50-task config prepared; no active configuration or annotation writes',flush=True)


if __name__=='__main__':main()
