"""Activate only independently sealed publication 11, then seal its read-only rollout."""
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_continue_v1'
REQUESTS=PROJECT/'outputs/pallet_mask_remaining_followup_requests_v2'
OUT=PROJECT/'outputs/pallet_mask_remaining_continue_deployment_v1'


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+'.remainingcontinue.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']==11 and
        verification['manifest_sha256']==digest(ROOT/'manifest.json') and
        verification['proposals_sha256']==digest(ROOT/'proposals.jsonl'),'Matching independent gallery seal required')
    work=read(REQUESTS/'manifest.json');independent=read(REQUESTS/'independent_verification.json');built=read(REQUESTS/'verification.json')
    for proof in (independent,built):
        require(proof['state']=='passed' and proof['requests_sha256']==digest(REQUESTS/'requests.jsonl') and
            proof['manifest_sha256']==digest(REQUESTS/'manifest.json'),'Matching independent/self task 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')
    archive=dict(archive,archive=str(archive_path.relative_to(PROJECT)))
    return manifest,work,independent,archive


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']==10,'Expected preserved publication 10 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=11,
        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=11,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='已保存复核后继续：410份合格人工保存来源，保持原门槛；仅本轮185份机器草稿，必须显式采用')
    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='本轮新图直接人工覆盖：Class 3四张及Class 4、5、7、14、22各十张，不重画已完成轮廓或强行增点')
    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=11,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']==11 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_c64837a264b02755b52495c6_ui_acceptance.json',
            'manual_source_3756ced3791a9669463f6fb0_ui_acceptance.json','direct_tasks_final_validation/public_acceptance.json',
            'online_normalized_layout.json','original_rectangle_navigation_ui_acceptance.json','archive_independent_acceptance.json',
            'task_title_reload.json','post_reload_source_integrity.json','task_title_and_protected_deeplink_ui_acceptance.json'):
        value=read(OUT/name);require(value['state']=='passed','Incomplete public acceptance: '+name);evidence[name]=digest(OUT/name)
    tests={}
    for name in ('integration_pytest.xml','continuation_final_pytest.xml','pipeline_publication_final_pytest.xml',
            'post_reload_pytest.xml','release_guard_final_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/'direct_tasks_final_validation/public_acceptance.json')
    require(public['targets']==1296 and public['new']==185 and tasks['requests']==54,'Public counts differ')
    require(tasks['online_publication_status_normalized'] and tasks['frozen_asset_bytes_unchanged'],'Independent task publication status not verified')
    base=read(PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json')['public_url']
    result=dict(state='passed',publication_version=11,directory=str(ROOT.relative_to(PROJECT)),total_distinct_images=1296,
        new_machine_candidates=185,generation_templates=410,actual_previous_batch_saved_reviews=369,
        previous_batch_changed_from_proposal=260,previous_batch_saved_no_change=109,completed_manual_tasks=50,
        new_modified_four_point_sources=48,reviewed_original_rectangle_sources=2,reviewed_original_rectangles_not_propagation_seeds=True,
        saved_human_contour_sources=1022,saved_review_sources_including_original_boxes=1024,
        statistics_basis='verified_immutable_generation_snapshot_not_a_live_review_counter',
        old_user_no_change_statements_preserved=45,earlier_candidates_without_new_save=42,
        direct_manual_requests=54,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=904,all_22_class_100_coverage_complete=False,class19_locked_pool_capacity=82,class19_data_shortfall_at_least=18,
        thresholds_relaxed=False,forced_fill=False,formal_protected_files_unchanged=20768,production_annotation_writes=0,
        public_gallery_assets_verified=public['public_assets_verified'],public_task_routes_verified=tasks['public_assets_verified'],
        registration_attempts_independently_recomputed=6383,accepted_targets_before_frame_diversity=200,
        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+'/?revision=11#new-batch',manual_request_url=base+'/template-requests/?batch=remaining-followup-v2',
        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_continue.py','pallet/mask_gallery.py',
            'pallet/mask_gallery_review.py','pallet/mask_template_requests.py','pallet/assets/mask_gallery/editor.js',
            'scripts/check_mask_template_requests_public.py','scripts/verify_mask_remaining_followup_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='waiting_for_actual_185_reviews_and_54_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()
