"""Activate sealed publication 12 without rewriting historical labels or review stores."""
from datetime import datetime,timezone
import json
import os
from pathlib import Path
import signal
import sys
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_gallery import Gallery
from pallet.mask_quota_saved_extension import file_inventory
from pallet.mask_template_requests import load_requests
from pallet.pose_review_geometry import canonical

ROOT=PROJECT/'outputs/pallet_mask_remaining_round2_v1'
REQUESTS=PROJECT/'outputs/pallet_mask_remaining_round2_requests_v1'
OUT=PROJECT/'outputs/pallet_mask_remaining_round2_deployment_v1'
VERSION=12


def read(path):return json.loads(Path(path).read_text())


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


def write(path,value):
    path=Path(path);temporary=path.with_suffix(path.suffix+'.round2.tmp')
    require(not temporary.exists(),'Unresolved atomic publication file')
    temporary.write_bytes(canonical(value)+b'\n');temporary.replace(path)


def seals():
    manifest=read(ROOT/'manifest.json');verification=read(ROOT/'verification.json')
    require(verification['state']=='passed' and verification['publication_version']==VERSION==manifest['publication_version'] and
        verification['manifest_sha256']==digest(ROOT/'manifest.json') and verification['proposals_sha256']==digest(ROOT/'proposals.jsonl') and
        verification['proposals_verified']==manifest['proposals'],'Matching independent gallery seal required')
    require(verification['verification_script_sha256']==digest(PROJECT/'scripts/verify_mask_remaining_round2.py'),'Independent verifier code changed')
    for name,expected in manifest['frozen_code_sha256'].items():require(digest(PROJECT/name)==expected,'Frozen generation helper changed: '+name)
    work=read(REQUESTS/'manifest.json');independent=read(REQUESTS/'independent_verification.json')
    for proof in (independent,read(REQUESTS/'verification.json')):
        require(proof['state']=='passed' and proof['requests_sha256']==digest(REQUESTS/'requests.jsonl') and
            proof['manifest_sha256']==digest(REQUESTS/'manifest.json') and proof['request_count']==work['request_count'],
            'Matching independent worklist seals required')
    require(independent['parent_verification_sha256']==digest(ROOT/'verification.json'),'Worklist parent binding differs')
    archive=read(ROOT/'delivery_verification.json');archive_path=ROOT/archive['archive']
    require(archive_path.parent==ROOT and archive['state']=='passed' and archive['sha256']==digest(archive_path),'Verified public archive required')
    return manifest,work,independent,dict(archive,archive=str(archive_path.relative_to(PROJECT)))


def activate():
    require(not (OUT/'activation.json').exists(),'Preserve completed activation evidence')
    manifest,work,independent,archive=seals();frozen=read(ROOT/'configuration_input_hashes.json')
    require(file_inventory(PROJECT/'configs')==frozen,'Source configuration changed since generation; do not overwrite it')
    Gallery(ROOT)
    names=('active_mask_gallery.json','active_mask_template_proposals.json','active_mask_template_requests.json')
    old={name:read(PROJECT/'configs'/name) for name in names}
    require(old[names[0]]['publication_version']==11,'Expected preserved publication 11 before activation')
    for name in names:
        backup=OUT/(name+'.before')
        if backup.exists():require(digest(backup)==digest(PROJECT/'configs'/name),'Existing config backup differs')
        else:backup.write_bytes((PROJECT/'configs'/name).read_bytes())
    gallery=dict(old[names[0]],directory=str(ROOT.relative_to(PROJECT)),publication_version=VERSION,
        manifest_sha256=digest(ROOT/'manifest.json'),verification_sha256=digest(ROOT/'verification.json'),
        previous_directory_preserved=old[names[0]]['directory'],fine_review_template_count=manifest['generation_templates'])
    sidecar=dict(old[names[1]],version=VERSION,count=manifest['new_proposals'],
        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=f'人工保存复核后继续：{manifest["generation_templates"]}份合格来源，保持原门槛；仅本轮{manifest["new_proposals"]}份机器草稿，需显式采用')
    taskconfig=dict(old[names[2]],directory=str(REQUESTS.relative_to(PROJECT)),
        manifest_sha256=digest(REQUESTS/'manifest.json'),verification_sha256=digest(REQUESTS/'verification.json'),
        request_count=work['request_count'],completed_request_count=0,requested_classes=work['classes'],
        user_authorization='已完成185份复核与54份新图后继续：不同新图直接人工覆盖，不重派已完成轮廓或强行增点')
    services=read(OUT/'gallery_deployment_before.json')['services'];appstate=read(PROJECT/'outputs/pallet_mask_gallery_managed_v1/supervisor.json')
    require(appstate['pid']==services['pallet_mask_gallery_managed_v1']['pid'] and
        appstate['tunnel']['pid']==services['pallet_mask_gallery_managed_v1']['tunnel']['pid'],'Preserved gallery service identity changed')
    for name,value in zip(names,(gallery,sidecar,taskconfig)):write(PROJECT/'configs'/name,value)
    load_requests(PROJECT/'configs'/names[2],PROJECT)
    expected=dict(frozen,**{name:digest(PROJECT/'configs'/name) for name in names})
    require(file_inventory(PROJECT/'configs')==expected,'Unrelated configuration changed')
    state=dict(state='activated_pending_public_acceptance',publication_version=VERSION,targets=manifest['proposals'],new=manifest['new_proposals'],
        manual_requests=work['request_count'],config_before=frozen,config_after=expected,
        gallery_verification_sha256=digest(ROOT/'verification.json'),request_verification_sha256=digest(REQUESTS/'independent_verification.json'),
        archive_sha256=archive['sha256'],production_annotation_writes=0,created_at=datetime.now(timezone.utc).isoformat())
    write(OUT/'activation.json',state);write(OUT/'rollout_status.json',state)
    pid=appstate['app']['pid'];require(b'pallet.mask_gallery' in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0'),'Unexpected gallery app PID')
    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']==VERSION and health['targets']==manifest['proposals'] and health['manual_template_requests']==work['request_count'] and health['editing_enabled']:
                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('Gallery app did not reload; preserve drafts/config backups and inspect logs')


def finalize():
    require(not (OUT/'final_acceptance.json').exists(),'Preserve completed final acceptance')
    manifest,work,independent,archive=seals();activation=read(OUT/'activation.json')
    require(file_inventory(PROJECT/'configs')==activation['config_after'],'Active publication changed during acceptance')
    evidence={}
    for name in ('public_acceptance.json','public_ui_acceptance.json','deployment_verification.json','pose_sidecar_acceptance.json',
            'manual_source_ui_acceptance.json','manual_source_0f62405fc643c71371c8a0ec_ui_acceptance.json',
            'manual_source_7041455b447a160ccc16d9df_ui_acceptance.json','manual_source_db94cf18b0c6e9f8641a9be0_ui_acceptance.json',
            'online_normalized_layout.json','task_and_original_review_ui_acceptance.json','archive_independent_acceptance.json',
            'post_publication_source_integrity.json'):
        value=read(OUT/name);require(value['state']=='passed','Incomplete public acceptance: '+name);evidence[name]=digest(OUT/name)
    tests={}
    for name in ('http_pool_pytest.xml','integration_pytest.xml','pipeline_final_pytest.xml','request_pipeline_pytest.xml',
            'final_release_guard_pytest.xml'):
        suites=list(ET.parse(OUT/name).getroot().iter('testsuite'))
        require(suites and not any(int(s.get(k,'0')) for s in suites for k 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');tasks=read(OUT/'task_and_original_review_ui_acceptance.json')
    require(public['targets']==manifest['proposals'] and public['new']==manifest['new_proposals'] and tasks['task_count']==work['request_count'],
        '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']
    result=dict(state='passed',publication_version=VERSION,directory=str(ROOT.relative_to(PROJECT)),
        total_distinct_images=manifest['proposals'],new_machine_candidates=manifest['new_proposals'],generation_templates=manifest['generation_templates'],
        actual_previous_batch_saved_reviews=185,previous_batch_changed_from_proposal=132,previous_batch_saved_no_change=53,
        completed_manual_tasks=54,new_modified_manual_sources=51,new_modified_four_point_sources=47,new_modified_eight_point_sources=4,
        new_reviewed_original_rectangle_sources=3,reviewed_original_rectangle_sources=manifest['reviewed_original_rectangle'],
        reviewed_original_rectangles_not_propagation_seeds=True,saved_human_contour_sources=manifest['saved_human'],
        saved_review_sources_including_original_boxes=manifest['saved_human']+manifest['reviewed_original_rectangle'],
        statistics_basis='verified_immutable_generation_snapshot_not_live_review_counter',
        old_user_no_change_statements_preserved=45,earlier_candidates_without_new_save=42,direct_manual_requests=work['request_count'],
        direct_task_classes=work['classes'],direct_tasks_counted_as_completed=False,
        class_distinct_images={c:v['total'] for c,v in manifest['classes'].items()},class_shortfalls={c:v['missing'] for c,v in manifest['classes'].items()},
        remaining_22_class_shortfall=sum(v['missing'] for v in manifest['classes'].values()),all_22_class_100_coverage_complete=False,
        class19_locked_pool_capacity=manifest['classes']['19']['capacity_matching_distinct_frames'],
        class19_data_shortfall_at_least=manifest['classes']['19']['capacity_shortfall'],
        thresholds_relaxed=False,forced_fill=False,formal_protected_files_unchanged=20768,fixed_target_denominator=12344,production_annotation_writes=0,
        public_gallery_assets_verified=public['public_assets_verified'],public_task_routes_verified=public['public_task_routes_verified'],
        registration_attempts_independently_recomputed=manifest['registration_attempts'],human_confirmation_inferred=False,
        ground_truth_eligible=False,automatic_training_eligible=False,robot_command_eligible=False,
        all_22_class_filters_verified=True,desktop_mobile_editor_verified=True,real_iPhone_Safari_tested=False,
        gallery_url=base+f'/?revision={VERSION}#new-batch',manual_request_url=base+'/template-requests/?batch=remaining-round2-v1',
        archive=archive['archive'],archive_sha256=archive['sha256'],regression_tests=tests,test_suites_may_overlap_not_additive=True,evidence=evidence,
        verification_sha256=digest(ROOT/'verification.json'),manifest_sha256=digest(ROOT/'manifest.json'),
        request_verification_sha256=digest(REQUESTS/'independent_verification.json'),
        publication_code_sha256={n:digest(PROJECT/n) for n in ('scripts/publish_mask_remaining_round2.py','scripts/check_mask_public_pool.py',
            'scripts/review_http_pool.py','pallet/mask_gallery.py','pallet/mask_gallery_review.py','pallet/mask_template_requests.py',
            'pallet/assets/mask_gallery/editor.js','scripts/verify_mask_remaining_round2_requests.py')},
        accepted_at=datetime.now(timezone.utc).isoformat())
    write(OUT/'final_acceptance.json',result)
    write(OUT/'rollout_status.json',dict(result,state='published_acceptance_passed',
        goal_state=f'waiting_for_actual_{manifest["new_proposals"]}_reviews_and_{work["request_count"]}_direct_saves'))
    print(json.dumps(result,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()
