"""Independent local audit and final packaging of the boundary-only revision."""
from contextlib import closing
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import sys
from zipfile import ZipFile,ZIP_DEFLATED

import cv2
import numpy as np
from PIL import Image

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest,protected_snapshot
from pallet.mask_boundary_review import affine_reference,beam_boundary_audit,image_corner_fit
from pallet.pose_review_geometry import canonical,polygon_value,raster_mask

ROOT=PROJECT/'outputs/pallet_mask_template_bulk_v3'
VALIDATION=PROJECT/'outputs/pallet_mask_boundary_validation_v1'
TARGET='ecb32bf169bd814b13791e4d'


def main():
    receipt=ROOT/'verification.json'
    if receipt.exists():raise ValueError('Do not overwrite completed verification')
    manifest=json.loads((ROOT/'manifest.json').read_text())
    assert manifest['state']=='boundary_revision_pending_independent_verification'
    assert digest(PROJECT/'pallet/mask_boundary_review.py')==manifest['boundary_guard_code_sha256']
    assert digest(PROJECT/'scripts/revise_mask_template_boundary.py')==manifest['generation_script_sha256']
    parent=PROJECT/manifest['parent'];assert digest(parent/'proposals.jsonl')==manifest['parent_proposals_sha256']
    old={p['target_key']:p for p in map(json.loads,(parent/'proposals.jsonl').read_text().splitlines())}
    new={p['target_key']:p for p in map(json.loads,(ROOT/'proposals.jsonl').read_text().splitlines())}
    templates={t['row']['target_key']:t for t in json.loads((ROOT/'template_inventory.json').read_text())['templates']}
    assert len(old)==52 and len(new)==51 and len(set(old)-set(new))==1
    assert set(old)-set(new)==set(manifest['quarantined_targets'])
    counts=dict(unchanged=0,corrected=0);recovered=None
    for key,p in new.items():
        t=templates[p['template']['target_key']];assert p['class_id']==t['row']['final_class_id']
        assert p['source']['split']==t['row']['split'] and p['source']['policy_id']==t['row']['policy_id']
        assert len(p['polygon'])==len(t['polygon'])==p['vertex_count']>4
        assert not p['human_mask_confirmed'] and not p['automatic_training_eligible'] and not p['robot_command_eligible']
        polygon_value(p['polygon'],*p['source']['size'])
        im=np.asarray(Image.open(ROOT/'images'/f'{key}.png'))
        np.testing.assert_array_equal(im,np.asarray(Image.open(parent/'images'/f'{key}.png')))
        ref=affine_reference(p,t);audit=beam_boundary_audit(im,p['polygon'],ref);assert audit['state']=='passed',key
        np.testing.assert_array_equal(np.asarray(Image.open(ROOT/'masks'/f'{key}.png'))>0,raster_mask(p['polygon'],*p['source']['size']))
        label=json.loads((ROOT/'labelme'/f'{key}.json').read_text());assert label['shapes'][0]['points']==p['polygon']
        if key==TARGET:
            assert beam_boundary_audit(im,old[key]['polygon'],ref)['state']=='review_required'
            fixed,fit=image_corner_fit(im,old[key]['polygon'],ref,p['source']['size'])
            np.testing.assert_allclose(fixed,p['polygon'],atol=1e-8,rtol=0)
            assert p['polygon'][:1]+p['polygon'][2:]==old[key]['polygon'][:1]+old[key]['polygon'][2:]
            assert fit['new_vertex'][0]<fit['old_vertex'][0] and fit['new_vertex'][1]<fit['old_vertex'][1]
            assert audit['thickness_ratio_p10']>.9 and audit['bright_exclusion_sections_fraction']==0
            added=raster_mask(p['polygon'],*p['source']['size'])&~raster_mask(old[key]['polygon'],*p['source']['size'])
            recovered=dict(new_included_native_pixels=int(added.sum()),bright_new_included_pixels=int(np.sum(added&(im>=170))),
                new_vertex=fit['new_vertex'],old_vertex=fit['old_vertex'],after_guard=audit)
            assert recovered['bright_new_included_pixels']>100
            counts['corrected']+=1
        else:
            assert canonical(p)==canonical(old[key]),key
            assert digest(ROOT/'masks'/f'{key}.png')==digest(parent/'masks'/f'{key}.png')
            counts['unchanged']+=1
    assert counts==dict(unchanged=50,corrected=1)
    quarantined=[json.loads(s) for s in (ROOT/'review_required.jsonl').read_text().splitlines()]
    assert len(quarantined)==1
    for q in quarantined:
        p=q['proposal'];assert p==old[p['target_key']]
        im=np.asarray(Image.open(parent/'images'/f'{p["target_key"]}.png'))
        assert beam_boundary_audit(im,p['polygon'],affine_reference(p,templates[p['template']['target_key']]))['state']=='review_required'
    # Version asset URLs too, so an old cached orange outline cannot survive a
    # refresh of the corrected report at the same public address.
    report=(ROOT/'report_zh.html').read_text()
    report=re.sub(r'((?:src|href)=")([^"#?:]+)(")',r'\1\2?revision=2\3',report)
    report=report.replace("url('report-font.otf')","url('report-font.otf?revision=2')")
    (ROOT/'report_zh.html').write_text(report)
    from fontTools.ttLib import TTFont
    assert {ord(c) for c in report if '\u3400'<=c<='\u9fff'}<=set(TTFont(ROOT/'report-font.otf').getBestCmap())
    before=json.loads((VALIDATION/'before_deployment.json').read_text())
    for file,sha in before['parent_files'].items():assert digest(PROJECT/file)==sha,file
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    assert protected_snapshot(formal)==before['protected_formal']
    live=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    with closing(sqlite3.connect(live.resolve().as_uri()+'?mode=ro',uri=True)) as db:
        db.execute('ATTACH DATABASE ? AS frozen',((VALIDATION/'reviews_before.sqlite3').as_uri()+'?mode=ro',))
        assert db.execute('SELECT COUNT(*) FROM frozen.events f LEFT JOIN main.events m ON m.id=f.id WHERE m.payload IS NULL OR m.payload!=f.payload').fetchone()[0]==0
    result=dict(state='passed',publication_version=2,proposals_verified=51,proposals_sha256=digest(ROOT/'proposals.jsonl'),
        counts=counts,original_candidates_reviewed=52,same_template_candidates_reviewed=3,quarantined_candidates=1,
        target=TARGET,recovered_material=recovered,all_other_vertex_coordinates_unchanged=True,
        all_retained_candidates_pass_local_guard=True,old_report_and_artifacts_unchanged=True,
        formal_protected_files_verified=len(before['protected_formal']),historical_events_verified=before['history_count'],
        extra_public_images=['vertex2_before_after.png'],production_annotation_writes=0,human_confirmation_inferred=False,
        report_sha256=digest(ROOT/'report_zh.html'),verification_script_sha256=digest(__file__))
    receipt.write_bytes(canonical(result)+b'\n')
    with ZipFile(ROOT/'mask_template_bulk.zip','w',ZIP_DEFLATED) as z:
        for path in sorted(ROOT.rglob('*')):
            if path.is_file() and path.suffix not in ('.zip','.sqlite3') and not path.name.endswith(('-wal','-shm')):z.write(path,path.relative_to(ROOT))
    with ZipFile(ROOT/'mask_template_bulk.zip') as z:
        assert z.testzip() is None
        for name in z.namelist():assert z.read(name)==(ROOT/name).read_bytes()
    (VALIDATION/'delivery.json').write_bytes(canonical(dict(state='passed',archive_sha256=digest(ROOT/'mask_template_bulk.zip'),
        manifest_sha256=digest(ROOT/'manifest.json'),verification_sha256=digest(receipt),proposals_sha256=digest(ROOT/'proposals.jsonl')))+b'\n')
    print(json.dumps(dict(state='passed',counts=counts,new_vertex=recovered['new_vertex'],
        recovered_bright_pixels=recovered['bright_new_included_pixels'],proposals=51)),flush=True)


if __name__=='__main__':cv2.setNumThreads(1);main()
