"""Activate independently verified remaining-class tasks without changing the 500 masks."""
import argparse
from contextlib import closing
import json
import os
from pathlib import Path
import signal
import sqlite3
import sys
import time
from urllib.request import urlopen

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest
from pallet.mask_quota_saved_extension import file_inventory
from pallet.mask_template_requests import load_requests
from pallet.pose_review_geometry import canonical


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--directory',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_requests_v2')
    parser.add_argument('--output',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_deployment_v1')
    args=parser.parse_args();root=args.directory.resolve();out=args.output.resolve()
    if not all(p.is_relative_to(PROJECT/'outputs') for p in (root,out)):raise ValueError('Expected outputs directories')
    out.mkdir(exist_ok=True)
    if (out/'publication.json').exists():raise ValueError('Preserve completed publication evidence')
    verified=json.loads((root/'verification.json').read_text());manifest=json.loads((root/'manifest.json').read_text())
    if verified['state']!='passed' or verified['requests_sha256']!=digest(root/'requests.jsonl'):
        raise ValueError('Expected independently verified manual worklist')
    independent=json.loads((root/'independent_verification.json').read_text())
    if (independent['state']!='passed' or independent['manifest_sha256']!=digest(root/'manifest.json') or
            verified['independent_verification_sha256']!=digest(root/'independent_verification.json') or
            verified['public_assets']!=independent['public_assets']):
        raise ValueError('Matching independent worklist seal required')
    if manifest['request_count']!=51 or verified['request_count']!=51:raise ValueError('Expected first 51 representative tasks')
    requests=list(map(json.loads,(root/'requests.jsonl').read_text().splitlines()))
    active_path=PROJECT/'configs/active_mask_gallery.json';active=json.loads(active_path.read_text());batch=PROJECT/active['directory']
    if active['publication_version']!=9 or len((batch/'proposals.jsonl').read_text().splitlines())!=500:
        raise ValueError('Keep the final 500-frame gallery active')
    if digest(batch/'manifest.json')!=active['manifest_sha256'] or digest(batch/'verification.json')!=active['verification_sha256']:
        raise ValueError('The 500-frame gallery binding differs')
    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:
            row=db.execute('SELECT payload FROM annotations WHERE target_key=?',(r['target_key'],)).fetchone()
            if (row is not None)!=r['existing_pose_record']:
                raise ValueError('Manual request target changed before activation')
            if row and digest_value(json.loads(row[0]))!=r['existing_pose_payload_sha256']:
                raise ValueError('Manual request target revision changed before activation')
    request_config=PROJECT/'configs/active_mask_template_requests.json'
    backup=out/'active_mask_template_requests.json.before'
    if backup.exists():raise ValueError('Preserve existing publication backup')
    backup.write_bytes(request_config.read_bytes())
    config=dict(schema='manual_mask_template_worklist_v1',directory=str(root.relative_to(PROJECT)),
        manifest_sha256=digest(root/'manifest.json'),verification_sha256=digest(root/'verification.json'),
        request_count=51,completed_request_count=0,target_per_class=100,counts_as_completed_annotation=False,
        requested_classes=manifest['classes'],
        user_authorization='为剩余17类构建标签；每类先补3份人工模板，严格配准后扩展，不改已有500张')
    proposed=out/'proposed_active_requests.json';proposed.write_bytes(canonical(config)+b'\n')
    checked=load_requests(proposed,PROJECT)
    if checked['count']!=51:raise ValueError('Request count differs')
    service_path=PROJECT/'outputs/pallet_mask_gallery_managed_v1/supervisor.json'
    service=json.loads(service_path.read_text());pid=service['app']['pid']
    if b'pallet.mask_gallery' not in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0'):
        raise ValueError('Expected original managed gallery application')
    before=dict(gallery_config_sha256=digest(active_path),mask_sidecar_sha256=digest(PROJECT/'configs/active_mask_template_proposals.json'),
        gallery_directory=active['directory'],gallery_file_inventory=file_inventory(batch),
        supervisor_pid=service['pid'],tunnel_pid=service['tunnel']['pid'],old_app_pid=pid)
    (out/'before_activation.json').write_bytes(canonical(before)+b'\n')
    tmp=request_config.with_suffix('.remaining.tmp');tmp.write_bytes(proposed.read_bytes());tmp.replace(request_config)
    os.kill(pid,signal.SIGTERM)
    end=time.monotonic()+100
    while time.monotonic()<end:
        try:
            with urlopen('http://127.0.0.1:3393/healthz',timeout=3) as response:health=json.load(response)
            if health.get('publication_version')==9 and health.get('targets')==500 and health.get('manual_template_requests')==51:
                now=json.loads(service_path.read_text())
                if now['pid']!=before['supervisor_pid'] or now['tunnel']['pid']!=before['tunnel_pid']:
                    raise ValueError('Original supervisor or tunnel changed')
                if (digest(active_path)!=before['gallery_config_sha256'] or file_inventory(batch)!=before['gallery_file_inventory'] or
                        digest(PROJECT/'configs/active_mask_template_proposals.json')!=before['mask_sidecar_sha256']):
                    raise ValueError('Original 500-frame gallery or sidecar changed')
                result=dict(state='published_pending_public_acceptance',requests=51,classes=manifest['classes'],
                    gallery_targets_unchanged=500,publication_version_unchanged=9,production_annotation_writes=0,
                    pose_application_not_restarted=True,original_tunnel_and_supervisor_preserved=True,
                    source=str(root.relative_to(PROJECT)),manifest_sha256=digest(root/'manifest.json'),
                    verification_sha256=digest(root/'verification.json'))
                (out/'publication.json').write_bytes(canonical(result)+b'\n');print(json.dumps(result),flush=True);return
        except (OSError,ValueError):pass
        time.sleep(1)
    raise RuntimeError('Manual worklist configuration saved but app is not ready; inspect service logs, preserve drafts')


def digest_value(value):
    import hashlib
    return hashlib.sha256(canonical(value)).hexdigest()


if __name__=='__main__':main()
