"""Record independent and online publication-10 evidence without confirming GT."""
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.pose_review_geometry import canonical


def main():
    root=PROJECT/'outputs/pallet_mask_remaining_expand_v1'
    tasks=PROJECT/'outputs/pallet_mask_remaining_direct_requests_v2'
    out=PROJECT/'outputs/pallet_mask_remaining_expand_deployment_v1'
    final=out/'final_acceptance.json'
    if final.exists():raise ValueError('Preserve completed rollout evidence')
    manifest=json.loads((root/'manifest.json').read_text());seal=json.loads((root/'verification.json').read_text())
    if (seal['state']!='passed' or seal['publication_version']!=10 or seal['proposals_verified']!=1061 or
            seal['proposals_sha256']!=digest(root/'proposals.jsonl') or seal['manifest_sha256']!=digest(root/'manifest.json')):
        raise ValueError('Need matching independent 1,061-frame expansion seal')
    evidence={}
    for name in ('public_acceptance.json','public_ui_acceptance.json','deployment_verification.json',
                 'pose_sidecar_acceptance.json','manual_source_ui_acceptance.json',
                 'direct_tasks_validation/public_acceptance.json','online_normalized_layout.json'):
        value=json.loads((out/name).read_text())
        if value['state']!='passed':raise ValueError('Incomplete acceptance: '+name)
        evidence[name]=digest(out/name)
    direct=json.loads((tasks/'independent_verification.json').read_text())
    if direct['state']!='passed' or direct['request_count']!=50 or direct['manifest_sha256']!=digest(tasks/'manifest.json'):
        raise ValueError('Need independently verified direct-manual worklist')
    delivery=json.loads((root/'delivery_verification.json').read_text())
    if delivery['state']!='passed' or delivery['sha256']!=digest(root/delivery['archive']):
        raise ValueError('Verified ZIP changed')
    counts={}
    for name in ('integration_pytest.xml','workflow_pytest.xml'):
        xml=ET.parse(out/name).getroot()
        if any(int(s.get(f,'0')) for s in xml.iter('testsuite') for f in ('errors','failures')):
            raise ValueError('Regression failure: '+name)
        counts[name]=sum(int(s.get('tests','0')) for s in xml.iter('testsuite'))
    public=json.loads((out/'public_acceptance.json').read_text())
    result=dict(state='passed',publication_version=10,directory=str(root.relative_to(PROJECT)),
        total_distinct_frames=manifest['proposals'],new_machine_candidates=manifest['new_proposals'],
        saved_human_at_snapshot=manifest['saved_human'],remaining_classes_saved_human=192,
        completed_manual_requests_verified=51,new_four_point_sources=15,generation_templates=41,
        old_500_preserved=True,old_141_manual_proposals_preserved=True,old_no_change_dispositions_preserved=45,
        direct_manual_requests=50,direct_task_classes=[4,5,7,14,22],direct_tasks_counted_as_completed=False,
        class_distinct_frames={c:v['distinct_frames'] for c,v in manifest['classes'].items()},
        class_shortfalls={c:v['missing'] for c,v in manifest['classes'].items()},
        all_22_class_100_coverage_complete=False,newly_at_100_coverage=[6,13],
        class19_locked_pool_capacity=88,class19_data_shortfall_at_least=12,
        public_assets_verified=public['public_assets_verified'],desktop_mobile_editor_verified=True,
        all_22_class_filters_verified=True,production_annotation_writes=0,
        formal_protected_files_unchanged=20768,pose_fixed_target_denominator=12344,
        thresholds_relaxed=False,forced_fill=False,recursive_unreviewed_candidate_propagation=False,
        automatic_training_eligible=False,robot_command_eligible=False,human_confirmation_inferred=False,
        frozen_offline_mobile_outer_overflow_pixels=4,online_outer_overflow_fixed_without_changing_frozen_html=True,
        real_iPhone_Safari_tested=False,regression_test_results=counts,
        gallery_url=public['public_url'],manual_request_url='https://lovely-ask-garmin-labeled.trycloudflare.com/template-requests/?batch=remaining-direct-v1',
        archive_sha256=delivery['sha256'],verification_sha256=digest(root/'verification.json'),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_369_candidate_reviews_and_50_actual_manual_saves'))+b'\n')
    print(json.dumps({k:result[k] for k in ('state','publication_version','total_distinct_frames','new_machine_candidates',
        'saved_human_at_snapshot','direct_manual_requests','public_assets_verified')}),flush=True)


if __name__=='__main__':main()
