"""Versioned vertex-2 repair and conservative quarantine; no human DB writes."""
from collections import Counter
from contextlib import closing
import copy
import hashlib
import json
from pathlib import Path
import sqlite3
import sys

import cv2
import numpy as np
from PIL import Image,ImageDraw

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

TARGET='ecb32bf169bd814b13791e4d'
TEMPLATE='b62526c40d7f972094b41bdb'
PARENT=PROJECT/'outputs/pallet_mask_template_bulk_v2'
OUT=PROJECT/'outputs/pallet_mask_template_bulk_v3'
VALIDATION=PROJECT/'outputs/pallet_mask_boundary_validation_v1'


def main():
    if OUT.exists() or VALIDATION.exists():raise ValueError('Use new correction/validation directories')
    OUT.mkdir();VALIDATION.mkdir()
    active=PROJECT/'configs/active_mask_template_proposals.json'
    assert json.loads(active.read_text())['proposals_sha256']==digest(PARENT/'proposals.jsonl')
    parent_files={str(p.relative_to(PROJECT)):digest(p) for p in PARENT.rglob('*') if p.is_file() and not p.name.endswith(('-wal','-shm'))}
    service_paths=['outputs/pallet_mask_gallery_managed_v1/public_access.json',
        'outputs/pallet_pose_review_managed_v1/supervisor.json','outputs/pallet_structure_review_managed_v1/supervisor.json']
    services={name:json.loads((PROJECT/name).read_text()) for name in service_paths}
    (VALIDATION/'active_proposals_before.json').write_bytes(active.read_bytes())
    live=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
    snapshot=VALIDATION/'reviews_before.sqlite3'
    with closing(sqlite3.connect(live.resolve().as_uri()+'?mode=ro',uri=True)) as src,closing(sqlite3.connect(snapshot)) as dest:src.backup(dest)
    snapshot.chmod(0o600)
    with closing(sqlite3.connect(snapshot.as_uri()+'?mode=ro',uri=True)) as db:
        history_count=db.execute('SELECT COUNT(*) FROM events').fetchone()[0]
        saved_count=db.execute('SELECT COUNT(*) FROM annotations').fetchone()[0]
        current={k:json.loads(v) for k,v in db.execute('SELECT target_key,payload FROM annotations')}
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    _,sources=load_dataset(formal);protected=protected_snapshot(formal)
    write_json(VALIDATION/'before_deployment.json',dict(parent_files=parent_files,services=services,
        snapshot_sha256=digest(snapshot),saved_count=saved_count,history_count=history_count,
        active_proposals_sha256=digest(active),protected_formal=protected))
    proposals=[json.loads(s) for s in (PARENT/'proposals.jsonl').read_text().splitlines()]
    inventory=json.loads((PARENT/'template_inventory.json').read_text())
    templates={t['row']['target_key']:t for t in inventory['templates']}
    rows={p['target_key']:p['source'] for p in proposals}
    rows.update({k:t['row'] for k,t in templates.items()})
    evidence=ImageEvidence(formal,rows,sources);new=[];quarantine=[];audits=[];correction=None
    for p in proposals:
        key=p['target_key'];t=templates[p['template']['target_key']];im=evidence.image(p['source']['frame_id'])
        ref=affine_reference(p,t);before=beam_boundary_audit(im,p['polygon'],ref)
        item=dict(target_key=key,template_key=p['template']['target_key'],class_id=p['class_id'],
            original_proposal_sha256=hashlib.sha256(canonical(p)).hexdigest(),before=before,
            same_template_as_reported=p['template']['target_key']==TEMPLATE)
        if key==TARGET:
            assert t['row']['target_key']==TEMPLATE and before['state']=='review_required'
            assert current.get(key,{}).get('revision',0)==p['target_expected_revision']
            assert hashlib.sha256(canonical(current.get(key))).hexdigest()==p['target_snapshot_payload_sha256']
            fixed,fit=image_corner_fit(im,p['polygon'],ref,p['source']['size'])
            after=beam_boundary_audit(im,fixed,ref);assert after['state']=='passed'
            assert fixed[:1]+fixed[2:]==p['polygon'][:1]+p['polygon'][2:]
            assert fixed[1][0]<p['polygon'][1][0] and fixed[1][1]<p['polygon'][1][1]
            revised=copy.deepcopy(p);revised['polygon']=fixed
            revised['boundary_correction']=dict(version=VERSION,user_report='Vertex 2 right/down cuts the right beam',
                parent_proposals_sha256=digest(PARENT/'proposals.jsonl'),parent_proposal_sha256=item['original_proposal_sha256'],
                original_polygon=p['polygon'],fit=fit,before=before,after=after,
                scope='machine_proposal_only_no_live_human_annotation_rewrite',human_mask_confirmed=False)
            revised['metrics']['boundary_guard']=after
            new.append(revised);correction=revised;item.update(action='vertex_2_repaired',after=after)
            panel=Image.new('RGB',(1480,305),'#121923');draw=ImageDraw.Draw(panel)
            draw.text((15,8),'OLD: beam clipped (red) -> NEW: observed edge intersection (green); only vertex 2 moved',fill='white')
            panel.paste(overlay(im,p['source'],p['polygon'],'#ff7060'),(0,30))
            panel.paste(overlay(im,p['source'],fixed,'#55ff99'),(740,30));panel.save(OUT/'vertex2_before_after.png')
        elif before['state']=='review_required':
            quarantine.append(dict(proposal=p,boundary_audit=before,status='withdrawn_machine_suggestion_pending_manual_review',
                human_annotation_unchanged=True));item['action']='quarantined_not_automatically_corrected'
        else:new.append(p);item['action']='unchanged'
        audits.append(item)
    assert correction is not None
    assert len(new)==51 and len(quarantine)==1 and len(audits)==52
    for p in new:polygon_value(p['polygon'],*p['source']['size'])
    for n,c in inventory['classes'].items():c['preview']=sum(p['class_id']==int(n) for p in new)
    for name,records in [('proposals.jsonl',new),('review_required.jsonl',quarantine),('boundary_audits.jsonl',audits)]:
        (OUT/name).write_bytes(b''.join(canonical(v)+b'\n' for v in records))
    write_json(OUT/'template_inventory.json',inventory)
    package_preview(OUT,new,templates,rows,evidence,inventory['classes'])
    # A visible correction notice avoids presenting an old report title as new.
    report=(OUT/'report_zh.html').read_text().replace('首批待复核样例','批量候选 · 边界修订版').replace('首批对照','边界修订版').replace('首批候选','当前候选')
    report=report.replace('本轮是小样预览，未抽中的目标不等同于无法补标。','本版只审查原52份候选，不新增模板或跨划分传播。')
    notice='<section id="boundary-correction"><h2>第2顶点问题已修正</h2><p>目标：2023_9_26/26-09-2023_02-02-35#yellow/405mm/1700mm。保留8个顶点，只调整第2顶点至原图横梁上缘与右缘交点。仍为待复核机器草稿，不自动确认。</p><img src="vertex2_before_after.png" alt="红色旧版切割横梁，绿色新版第2顶点修正"><p>同模板另有1份局部边界风险候选暂撤下待人工复核，其余50份轮廓不变；当前提供51份候选。旧人工位姿、选面、修订历史和旧图册均未覆盖。</p></section>'
    report=report.replace('<p>左侧蓝色',notice+'<p>左侧蓝色')
    # Stable anchors make the reported frame directly reachable from a public URL.
    for p in new:
        # Locate by image URI rather than global replace of a shared class marker.
        image=f'src="cases/{p["target_key"]}.png"';pos=report.index(image);start=report.rfind('<article ',0,pos)
        report=report[:start]+report[start:].replace('<article ',f'<article id="target-{p["target_key"]}" ',1)
    (OUT/'report_zh.html').write_text(report)
    from fontTools import subset
    from fontTools.ttLib import TTFont
    font_source=Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf')
    font=TTFont(font_source);sub=subset.Subsetter();sub.populate(text=report);sub.subset(font);font.save(OUT/'report-font.otf')
    required={ord(c) for c in report if '\u3400'<=c<='\u9fff'};assert required<=set(TTFont(OUT/'report-font.otf').getBestCmap())
    write_json(OUT/'font_coverage.json',dict(all_report_Chinese_present=True,chinese_glyphs=len(required),font_sha256=digest(OUT/'report-font.otf')))
    manifest=dict(state='boundary_revision_pending_independent_verification',version='same_class_fixed_vertex_bulk_boundary_v2',
        publication_version=2,parent='outputs/pallet_mask_template_bulk_v2',parent_proposals_sha256=digest(PARENT/'proposals.jsonl'),
        proposals=len(new),original_proposals=len(proposals),corrected_proposals=1,quarantined_proposals=len(quarantine),unchanged_proposals=50,
        corrected_target=TARGET,quarantined_targets=[q['proposal']['target_key'] for q in quarantine],
        classes=inventory['classes'],formal_manifest_sha256=digest(formal/'manifest.json'),
        classification_sha256=json.loads((PARENT/'manifest.json').read_text())['classification_sha256'],
        proposals_sha256=digest(OUT/'proposals.jsonl'),source_image_hashes=evidence.used,
        boundary_guard_code_sha256=digest(PROJECT/'pallet/mask_boundary_review.py'),generation_script_sha256=digest(__file__),
        vertex_counts=dict(Counter(p['vertex_count'] for p in new)),publication_mode='read_only_sidecar_explicit_human_adoption',
        production_database_writes=0,human_confirmation_inferred=False,cross_split_template_transfers=0)
    write_json(OUT/'manifest.json',manifest)
    for p,sha in parent_files.items():assert digest(PROJECT/p)==sha
    assert protected_snapshot(formal)==protected
    print(json.dumps(dict(state='generated',proposals=len(new),new_vertex=correction['polygon'][1],
        old_vertex=correction['boundary_correction']['fit']['old_vertex'],quarantined=manifest['quarantined_targets'])),flush=True)


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