"""Seal the first remaining-class worklist rollout; do not claim its tasks done."""
import json
from pathlib import Path
import sys
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.pose_review_geometry import canonical


def main():
    out=PROJECT/'outputs/pallet_mask_remaining_deployment_v1'
    sources=PROJECT/'outputs/pallet_mask_remaining_classes_v1'
    requests=PROJECT/'outputs/pallet_mask_remaining_requests_v2'
    final=out/'final_acceptance.json'
    if final.exists():raise ValueError('Preserve completed acceptance evidence')
    source_seal=json.loads((sources/'independent_verification.json').read_text())
    request_seal=json.loads((requests/'independent_verification.json').read_text())
    if any(v['state']!='passed' for v in (source_seal,request_seal)):
        raise ValueError('Both source reuse and manual worklist need independent verification')
    if source_seal['manifest_sha256']!=digest(sources/'manifest.json') or request_seal['manifest_sha256']!=digest(requests/'manifest.json'):
        raise ValueError('Independent manifest binding changed')
    config=json.loads((PROJECT/'configs/active_mask_template_requests.json').read_text())
    if config['directory']!=str(requests.relative_to(PROJECT)) or config['verification_sha256']!=digest(requests/'verification.json'):
        raise ValueError('Active manual tasks differ')
    before=json.loads((out/'before_activation.json').read_text());gallery=PROJECT/before['gallery_directory']
    if (digest(PROJECT/'configs/active_mask_gallery.json')!=before['gallery_config_sha256'] or
            digest(PROJECT/'configs/active_mask_template_proposals.json')!=before['mask_sidecar_sha256'] or
            file_inventory(gallery)!=before['gallery_file_inventory']):
        raise ValueError('The original 500-mask gallery or sidecar changed')
    evidence={}
    for name in ('public_validation/public_acceptance.json','deployment_verification.json',
                 'all_class_deeplink_api_acceptance.json','offline_manual_requests_layout.json'):
        value=json.loads((out/name).read_text())
        if value['state']!='passed':raise ValueError('Incomplete acceptance: '+name)
        evidence[name]=digest(out/name)
    public=json.loads((out/'public_validation/public_acceptance.json').read_text())
    if public['requests']!=51 or public['accepted_candidate_count_unchanged']!=500:
        raise ValueError('Published request/gallery counts differ')
    tests=ET.parse(out/'regression_pytest.xml').getroot()
    if any(int(s.get(k,'0')) for s in tests.iter('testsuite') for k in ('errors','failures')):
        raise ValueError('Regression suite has failures')
    total=sum(int(s.get('tests','0')) for s in tests.iter('testsuite'))
    archive=PROJECT/'outputs/pallet_mask_remaining_delivery_v1/archive_verification.json'
    delivery=json.loads(archive.read_text())
    if delivery['state']!='passed' or delivery['sha256']!=digest(PROJECT/delivery['archive']):
        raise ValueError('Verified label export changed')
    inventory=json.loads((sources/'class_inventory.json').read_text())
    result=dict(state='passed',scope='remaining_17_classes_first_representative_manual_worklist',
        source_directory=str(sources.relative_to(PROJECT)),request_directory=str(requests.relative_to(PROJECT)),
        classes=request_seal['classes'],target_per_class=100,source_labels_reused=source_seal['saved_sources_verified'],
        reused_four_point_sources=sum(v['manual_four_count'] for v in inventory.values()),
        eligible_saved_human_templates=sum(v['templates'] for v in inventory.values()),
        manual_requests=51,requests_per_class=3,existing_pose_tasks=3,no_prior_pose_tasks=48,
        tasks_not_inferred_completed=True,all_remaining_quotas_complete=False,
        class19_population_frames=96,class19_after_inherited_500_frames=92,class19_protected_aware_capacity=90,
        class19_target_shortfall_at_least=10,thresholds_relaxed=False,forced_fill=False,
        previous_500_gallery_unchanged=True,previous_publication_version=9,
        request_url=public['url']+'?batch=remaining17-v1',public_assets_verified=public['public_assets_verified'],
        desktop_mobile_request_and_deeplink_checks_passed=True,all_17_class_target_apis_verified=True,
        regression_tests_passed=total,production_annotation_writes=0,
        human_confirmation_inferred=False,ground_truth_eligible=False,automatic_training_eligible=False,robot_command_eligible=False,
        real_iPhone_Safari_tested=False,source_verification_sha256=digest(sources/'independent_verification.json'),
        request_verification_sha256=digest(requests/'independent_verification.json'),
        archive=delivery['archive'],archive_sha256=delivery['sha256'],evidence=evidence)
    final.write_bytes(canonical(result)+b'\n')
    (out/'rollout_status.json').write_bytes(canonical(dict(result,state='published_acceptance_passed',goal_state='waiting_for_51_actual_manual_saves'))+b'\n')
    print(json.dumps(result,ensure_ascii=False),flush=True)


if __name__=='__main__':main()
