"""Publish independently verified strict masks and separately preannotated new-image tasks."""
from datetime import datetime,timezone
import json
import os
from pathlib import Path
import signal
import sys
import tempfile
import time
from urllib.request import urlopen
import xml.etree.ElementTree as ET

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_gallery import Gallery
from pallet.pose_review_geometry import canonical

ROOT=PROJECT/'outputs/pallet_mask_remaining_round3_v1'
TASKS=PROJECT/'outputs/pallet_mask_preannotated_requests_v1'
OUT=PROJECT/'outputs/pallet_mask_remaining_round3_deployment_v1'


def require(value,message):
    if not value:raise ValueError(message)


def read(path):return json.loads(Path(path).read_text())
def write(path,value):
    path=Path(path);temp=path.with_suffix(path.suffix+'.round3.tmp')
    require(not temp.exists(),'Unresolved publication temporary file')
    temp.write_bytes(canonical(value)+b'\n');temp.replace(path)


def seals():
    manifest=read(ROOT/'manifest.json');seal=read(ROOT/'verification.json');tasks=read(TASKS/'manifest.json');proof=read(TASKS/'verification.json')
    require(seal['state']=='passed' and seal['publication_version']==manifest['publication_version']==13 and
        seal['manifest_sha256']==digest(ROOT/'manifest.json') and seal['proposals_sha256']==digest(ROOT/'proposals.jsonl'),
        'Independent publication13 seal required')
    require(seal['verification_script_sha256']==digest(PROJECT/'scripts/verify_mask_remaining_round3.py'),'Gallery verifier changed')
    require(all(digest(PROJECT/n)==h for n,h in manifest['frozen_code_sha256'].items()),'Frozen registration/helper code changed')
    require(proof['state']=='passed' and proof['preannotations_verified'] is True and proof['request_count']==tasks['request_count']==37
        and proof['manifest_sha256']==digest(TASKS/'manifest.json') and proof['requests_sha256']==digest(TASKS/'requests.jsonl')
        and proof['proposals_sha256']==digest(TASKS/'proposals.jsonl') and proof['parent_verification_sha256']==digest(ROOT/'verification.json'),
        'Matching independently verified drawn tasks required')
    require(proof==read(TASKS/'independent_verification.json') and
        proof['verification_script_sha256']==digest(PROJECT/'scripts/verify_mask_preannotated_requests.py'),'Preannotation independent seal/code differs')
    require(read(OUT/'preannotation_editor_synthetic_acceptance.json')['state']=='passed','Isolated save/failure tests required')
    archive=read(ROOT/'delivery_verification.json')
    require(archive['state']=='passed' and digest(ROOT/archive['archive'])==archive['sha256'],'Verified archive required')
    return manifest,tasks,proof,archive


def activate():
    require(not (OUT/'activation.json').exists(),'Preserve previous activation evidence')
    manifest,tasks,proof,archive=seals();before=read(ROOT/'configuration_input_hashes.json')
    require(file_inventory(PROJECT/'configs')==before,'User/source configuration changed; do not overwrite it')
    names=('active_mask_gallery.json','active_mask_template_proposals.json','active_mask_template_requests.json')
    old={n:read(PROJECT/'configs'/n) for n in names};require(old[names[0]]['publication_version']==12,'Expected publication12 baseline')
    taskconfig=dict(old[names[2]],schema='preannotated_mask_worklist_v1',directory=str(TASKS.relative_to(PROJECT)),
        manifest_sha256=digest(TASKS/'manifest.json'),verification_sha256=digest(TASKS/'verification.json'),
        request_count=37,completed_request_count=0,requested_classes=tasks['classes'],counts_as_completed_annotation=False,
        user_authorization='新图先完成助手掩膜预标注，再交给用户复核；不发布只有原框的任务，不伪造人工保存或放宽传播门槛')
    with tempfile.TemporaryDirectory(prefix='preannotation-publication-check-',dir='/tmp/opencode') as directory:
        path=Path(directory)/'tasks.json';path.write_bytes(canonical(taskconfig));preview=Gallery(ROOT,requests_config=path)
        require(preview.count==1478 and len(preview.preannotation_proposals)==37,'Drawn tasks must remain separate from counted strict gallery')
    gallery=dict(old[names[0]],directory=str(ROOT.relative_to(PROJECT)),publication_version=13,
        manifest_sha256=digest(ROOT/'manifest.json'),verification_sha256=digest(ROOT/'verification.json'),
        previous_directory_preserved=old[names[0]]['directory'],fine_review_template_count=650)
    sidecar=dict(old[names[1]],version=13,count=29,proposals=str((ROOT/'new_proposals.jsonl').relative_to(PROJECT)),
        proposals_sha256=digest(ROOT/'new_proposals.jsonl'),manifest=str((ROOT/'manifest.json').relative_to(PROJECT)),
        manifest_sha256=digest(ROOT/'manifest.json'),verification=str((ROOT/'verification.json').relative_to(PROJECT)),
        verification_sha256=digest(ROOT/'verification.json'),gallery_review_snapshot=str((ROOT/'gallery_reviews_snapshot.sqlite3').relative_to(PROJECT)),
        gallery_review_snapshot_sha256=digest(ROOT/'gallery_reviews_snapshot.sqlite3'),
        authorization='650份合格真实保存来源按原门槛扩展，仅29份严格候选；37份看图预标注任务不加入位姿侧车或传播模板')
    for name in names:
        path=OUT/(name+'.before')
        if path.exists():require(digest(path)==digest(PROJECT/'configs'/name),'Configuration backup differs')
        else:path.write_bytes((PROJECT/'configs'/name).read_bytes())
    statepath=PROJECT/'outputs/pallet_mask_gallery_managed_v1/supervisor.json';service=read(statepath)
    pid=service['app']['pid'];require(b'pallet.mask_gallery' in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0'),'Unexpected gallery app PID')
    for name,value in zip(names,(gallery,sidecar,taskconfig)):write(PROJECT/'configs'/name,value)
    after=dict(before,**{name:digest(PROJECT/'configs'/name) for name in names});require(file_inventory(PROJECT/'configs')==after,'Unrelated configuration changed')
    status=dict(state='activated_pending_public_acceptance',publication_version=13,targets=1478,new_strict_candidates=29,
        preannotated_tasks=37,assistant_drafts_counted_as_completed=False,config_before=before,config_after=after,
        gallery_verification_sha256=digest(ROOT/'verification.json'),preannotation_verification_sha256=digest(TASKS/'verification.json'),
        production_annotation_writes=0,created_at=datetime.now(timezone.utc).isoformat())
    write(OUT/'activation.json',status);write(OUT/'rollout_status.json',status);os.kill(pid,signal.SIGTERM)
    deadline=time.monotonic()+100
    while time.monotonic()<deadline:
        try:
            health=json.load(urlopen('http://127.0.0.1:3393/healthz',timeout=3))
            if health['publication_version']==13 and health['targets']==1478 and health['manual_template_requests']==37 and health['editing_enabled']:
                now=read(statepath);require(now['pid']==service['pid'] and now['tunnel']['pid']==service['tunnel']['pid'],'Supervisor/tunnel changed')
                print(json.dumps(dict(state='active_local_health_passed_pending_public_acceptance',health=health)),flush=True);return
        except (OSError,ValueError):pass
        time.sleep(1)
    raise RuntimeError('Publication app reload not ready; preserve drafts and inspect logs')


def finalize():
    require(not (OUT/'final_acceptance.json').exists(),'Preserve completed final acceptance')
    manifest,tasks,proof,archive=seals();require(file_inventory(PROJECT/'configs')==read(OUT/'activation.json')['config_after'],'Active configuration changed')
    names=('public_acceptance.json','public_ui_acceptance.json','preannotation_public_ui_acceptance.json','pose_sidecar_acceptance.json',
        'deployment_verification.json','preannotation_editor_synthetic_acceptance.json','post_publication_source_integrity.json',
        'archive_independent_acceptance.json','preannotation_visual_acceptance.json')
    evidence={}
    for name in names:
        require(read(OUT/name)['state']=='passed','Incomplete publication check: '+name);evidence[name]=digest(OUT/name)
    tests={}
    for name in ('integration_pytest.xml','pipeline_final_pytest.xml','release_guard_pytest.xml'):
        suites=list(ET.parse(OUT/name).getroot().iter('testsuite'))
        require(suites and not any(int(s.get(f,'0')) for s in suites for f in ('failures','errors')),'Failed regression suite')
        tests[name]=sum(int(s.get('tests','0')) for s in suites);evidence[name]=digest(OUT/name)
    public=read(OUT/'public_acceptance.json');require(public['targets']==1478 and public['new']==29 and public['separately_preannotated_tasks_verified']==37,
        'Public counts differ')
    from scripts.check_mask_refined_public import refresh_service_metadata
    refresh_service_metadata();base=read(PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json')['public_url']
    value=dict(state='passed',publication_version=13,total_distinct_images=1478,new_strict_candidates=29,preannotated_new_image_tasks=37,
        preannotated_class_counts=tasks['class_counts'],every_new_task_preannotated_before_publication=True,
        preannotations_separate_from_strict_registration=True,assistant_drafts_counted_as_completed=False,
        actual_prior_candidate_saves=51,prior_changed=36,prior_saved_unchanged=15,actual_new_manual_contours=48,
        pending_original_rectangle_saves_not_counted=2,old_original_rectangle_reviews_preserved=5,saved_human_contours=1357,
        templates=650,registration_attempts_independently_replayed=9262,class_shortfalls={c:v['missing'] for c,v in manifest['classes'].items()},
        remaining_shortfall=722,class19_capacity=61,class19_new_data_shortfall_at_least=39,ground_truth_eligible=False,
        automatic_training_eligible=False,robot_command_eligible=False,thresholds_relaxed=False,production_annotation_writes=0,
        fixed_target_denominator=12344,protected_formal_files=20768,all_human_history_preserved=True,all_old_publications_preserved=True,
        gallery_url=base+'/?revision=13#new-batch',preannotated_task_url=base+'/template-requests/?batch=preannotated-v1',
        public_gallery_assets_verified=public['public_assets_verified'],public_task_routes_verified=public['public_task_routes_verified'],
        archive=str((ROOT/archive['archive']).relative_to(PROJECT)),archive_sha256=archive['sha256'],tests=tests,test_suites_overlap_not_additive=True,
        real_iPhone_Safari_tested=False,evidence=evidence,verification_sha256=digest(ROOT/'verification.json'),
        statistics_basis='independently_verified_immutable_generation_snapshot_not_live_human_completion',
        publication_code_sha256={n:digest(PROJECT/n) for n in ('scripts/publish_mask_remaining_round3.py','pallet/mask_preannotation.py',
            'pallet/mask_gallery.py','pallet/mask_gallery_review.py','pallet/mask_template_requests.py',
            'pallet/assets/mask_gallery/editor.js','pallet/assets/mask_gallery/editor-font.otf','scripts/check_mask_public_pool.py')},
        preannotation_verification_sha256=digest(TASKS/'verification.json'),accepted_at=datetime.now(timezone.utc).isoformat())
    write(OUT/'final_acceptance.json',value);write(OUT/'rollout_status.json',dict(value,state='published_acceptance_passed',
        goal_state='waiting_for_actual_29_strict_reviews_and_37_preannotation_reviews'))
    print(json.dumps(value,ensure_ascii=False),flush=True)


if __name__=='__main__':
    import argparse
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--stage',choices=('activate','finalize'),required=True)
    args=parser.parse_args();activate() if args.stage=='activate' else finalize()
