"""Explicitly rejected-quality samples: isolated editing, never quota or GT.

This adapter reuses the original editor UI/history/conflict implementation without
changing its production files. No ambiguous machine polygon is manufactured.
"""
from contextlib import closing
import hashlib
import hmac
import io
import json
from pathlib import Path
import sqlite3

import numpy as np
from PIL import Image

from .cluster_targets import digest
from .mask_gallery import ASSETS, Handler
from .mask_gallery_review import MaskEditor, ReviewError
from .pose_review_geometry import canonical, polygon_value, raster_mask

PROJECT = Path(__file__).resolve().parents[1]
SCHEMA = 'nonconforming_mask_review_target_v1'
FALSE_FLAGS = ('counts_as_completed_annotation', 'counts_toward_under50', 'ground_truth_eligible',
    'human_mask_confirmed', 'human_pose_confirmed', 'automatic_training_eligible',
    'robot_command_eligible', 'propagation_seed_eligible', 'accepted_candidate')


def sha(value):
    return hashlib.sha256(canonical(value)).hexdigest()


def require(value, message):
    if not value:
        raise ValueError(message)


def validate_target(value):
    require(value.get('schema') == SCHEMA and value.get('class_id') == 19
        and value.get('polygon') == [] and value.get('vertex_count') == 0
        and value.get('source_quality') == 'nonconforming'
        and value.get('exception_authorized') is True
        and value.get('status') == 'nonconforming_pending_manual_inspection'
        and value.get('target_key') == value.get('source', {}).get('target_key')
        and value.get('original_rejection_reasons')
        and all(value.get(field) is False for field in FALSE_FLAGS),
        'Rejected-quality target must stay blank, explicitly nonconforming and ineligible')


def editor_script():
    """Namespace-specific copy; old editor source and services stay byte-identical."""
    text = (ASSETS/'editor.js').read_text()
    def replace(old, new):
        nonlocal text
        require(text.count(old) == 1, 'Pinned editor adapter anchor changed: '+old[:60])
        text = text.replace(old, new)
    replace("let undo=[],redo=[],restored=null", "let drawing=true; let undo=[],redo=[],restored=null")
    replace("'mask-gallery-v1:'", "'mask-nonconforming-v1:'")
    replace("expected_revision:detail.review?.revision||0,polygon:clone(polygon),", "expected_revision:detail.review?.revision||0,quality_decision:polygon.length?'redrawn_pending_quality_check':'untraceable',polygon:clone(polygon),")
    replace("d.polygon.length>=3", "d.polygon.length>=0")
    replace("detail.proposal_polygon);$('mgNote')", "detail.proposal_polygon);drawing=polygon.length===0;$('mgNote')")
    replace("const busy=loading||!!saving,editable=canEdit();", "const busy=loading||!!saving,editable=canEdit(); $('mgDrawMode').disabled=!editable;$('mgUntraceable').disabled=!editable;$('mgDrawMode').textContent=drawing?'完成描绘 / 编辑顶点':'开始 / 继续添点';")
    old = "$('mgReset').textContent=detail?.saved_gallery_manual_source?'恢复人工掩膜快照':detail?.assistant_preannotation_source?'恢复预标注草稿':detail?.original_rectangle_review_only?'恢复已复核原框':detail?.saved_pose_manual_source?'恢复人工模板快照':'恢复机器建议';"
    replace(old, "$('mgReset').textContent='清空为未描绘（可撤销）';")
    replace("'机器建议 · 尚未人工保存'", "'不合格样本 · 无可靠预轮廓，点击添点或保存无法描绘'")
    replace("await save(offset>0&&!detail?.saved_pose_manual_source&&!detail?.saved_pose_review_source&&!detail?.saved_gallery_manual_source)", "await save()")
    replace("else{const xs=polygon.map", "else if(!polygon.length){box=detail.source.bbox;} else{const xs=polygon.map")
    replace("if(!canEdit())return;\n let best", "if(!canEdit())return;\n if(drawing){if(polygon.length>=128){toast('最多128点');return;}checkpoint();polygon.push([clamp(p[0],0,detail.source.size[0]),clamp(p[1],0,detail.source.size[1])]);selected=polygon.length-1;changed();return;}\n let best")
    replace("$('mgDeleteVertex').onclick=deleteVertex;", "$('mgDeleteVertex').onclick=deleteVertex; $('mgDrawMode').onclick=()=>{if(canEdit()){drawing=!drawing;controls();toast(drawing?'点击图像添加顶点，完成后再切换编辑':'拖动顶点或点击边修改');}}; $('mgUntraceable').onclick=()=>{if(!canEdit()||!confirm('清空轮廓并标记无法描绘？可撤销，保存后只进入不合格记录库。'))return;checkpoint();polygon=[];drawing=true;selected=-1;changed();};")
    replace("polygon=clone(detail.proposal_polygon);restored=null", "polygon=clone(detail.proposal_polygon);drawing=true;restored=null")
    replace("`已保存 · r${data.review.revision}`", "`已隔离保存（不计配额）· r${data.review.revision}`")
    replace("`已保存 · r${value.review.revision}`", "`已隔离保存（不计配额）· r${value.review.revision}`")
    replace("b.textContent=v?`修改掩膜 · 已存 r${v.revision}`:'修改掩膜 / 在线复核';", "b.textContent=v?`不合格记录 · r${v.revision}`:'不合格样本 / 人工处理';")
    replace("b.textContent='修改掩膜 / 在线复核';b.onclick", "b.textContent='不合格样本 / 人工处理';b.onclick")
    replace("selectedVertex:selected,pan,view:", "selectedVertex:selected,drawing,pan,view:")
    return text


def editor_fragment():
    text = (ASSETS/'editor.html').read_text()
    text = text.replace('图册可免登录浏览。', '本批明确为不合格样本，未提供可靠预轮廓。原框仅用于定位，不是轮廓。图册可免登录浏览。')
    text = text.replace('保存为人工编辑草稿，不自动确认GT。', '仅保存到独立不合格库，不计43/50配额、不进训练或GT；可保存无法描绘。')
    text = text.replace('<button id="mgFit"', '<button id="mgDrawMode" type="button">完成描绘 / 编辑顶点</button><button id="mgUntraceable" type="button">无法描绘 / 清空</button><button id="mgFit"', 1)
    return text.replace('保存修订', '隔离保存（不计配额）').replace('保存 / 下条', '下条（未修改不记完成）')


class NonconformingEditor(MaskEditor):
    def __init__(self, gallery, directory, access_key):
        directory = Path(directory).resolve()
        require(directory.parent == PROJECT/'outputs' and directory.name.startswith('pallet_mask_nonconforming_reviews_'),
            'Nonconforming edits require their own isolated review store')
        super().__init__(gallery, directory, access_key)
        self.cookie_token = hmac.new(self.access_key.encode(), b'nonconforming-mask-editor-v1', hashlib.sha256).hexdigest()
        self.binding = sha(dict(formal=self.formal_manifest_sha256, worklist=gallery.manifest_sha256, namespace='nonconforming-v1'))

    def source_reference(self, key):
        proposal = self.proposal(key); validate_target(proposal)
        return dict(origin='nonconforming_user_authorized_exception', target_key=key,
            original_rejection_reasons=proposal['original_rejection_reasons'])

    def proposal_dependency_current(self, key):
        proposal = self.proposal(key); validate_target(proposal)
        for name, table, column in (('pallet_pose_human_review_v1/annotations.sqlite3', 'annotations', 'pose_payload_raw_sha256'),
                ('pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3', 'reviews', 'gallery_payload_raw_sha256')):
            path = (PROJECT/'outputs'/name).resolve()
            with closing(sqlite3.connect(path.as_uri()+'?mode=ro', uri=True)) as db:
                row = db.execute(f'SELECT payload FROM {table} WHERE target_key=?', (key,)).fetchone()
            expected = proposal[column]
            if (hashlib.sha256(row[0].encode()).hexdigest() if row else None) != expected:
                return False
        return True

    def detail(self, key):
        value = super().detail(key)
        value.update(source_quality='nonconforming', original_rejection_reasons=self.proposal(key)['original_rejection_reasons'],
            no_reliable_preannotation=True, counts_as_completed_annotation=False, counts_toward_under50=False)
        return value

    def save(self, key, data):
        proposal = self.proposal(key); validate_target(proposal)
        if data.get('binding') != self.binding or data.get('source_binding') != self.source_binding(key) or data.get('proposal_id') != sha(proposal):
            raise ReviewError(409, '不合格任务或目标绑定已变化，本机草稿保留')
        expected = data.get('expected_revision'); reviewer, note = data.get('reviewer'), data.get('note', '')
        if type(expected) is not int or expected < 0 or not isinstance(reviewer, str) or not 1 <= len(reviewer.strip()) <= 80 or not isinstance(note, str) or len(note) > 2000:
            raise ReviewError(400, '请填写有效标注人、备注和修订版本')
        if not self.proposal_dependency_current(key):
            raise ReviewError(409, '原人工目标已变化，请保留本机草稿；不覆盖既有记录')
        decision = data.get('quality_decision')
        if decision == 'untraceable':
            if data.get('polygon') != []:
                raise ReviewError(400, '无法描绘记录不能伪装有轮廓')
            polygon = []
        elif decision == 'redrawn_pending_quality_check':
            try:
                polygon = polygon_value(data.get('polygon'), *proposal['source']['size'])
            except (TypeError, ValueError) as error:
                raise ReviewError(400, str(error)) from error
        else:
            raise ReviewError(400, '必须明确无法描绘或人工重描待质检，不接受合格/确认/训练状态')
        restored = data.get('restored_from_revision')
        if restored is not None and (type(restored) is not int or restored not in {r['revision'] for r in self.store.history(key)}):
            raise ReviewError(400, '恢复来源修订不存在')
        value = dict(target_key=key, source=self.identity(key), source_binding=self.source_binding(key), binding=self.binding,
            base_proposal_id=sha(proposal), proposal_publication='nonconforming-v1', worklist_manifest_sha256=self.gallery.manifest_sha256,
            proposal_polygon=[], polygon=polygon, vertex_count=len(polygon), original_vertex_count=0,
            reviewer=reviewer.strip(), note=note.strip(), restored_from_revision=restored,
            status='nonconforming_human_review_not_counted', quality_decision=decision, source_quality='nonconforming',
            event_kind='human_nonconforming_mask_review', human_edited=True, original_rejection_reasons=proposal['original_rejection_reasons'],
            pose_store_written=False, original_proposal_modified=False, **dict.fromkeys(FALSE_FLAGS, False))
        return self.store.save(key, expected, value)

    def export(self, key, kind):
        proposal = self.proposal(key); review = self.store.get(key)
        if not review:
            raise ReviewError(404, '尚无已保存的不合格处理记录')
        if review['source_binding'] != self.source_binding(key):
            raise ReviewError(409, '原图绑定变化，不导出错误目标')
        if kind == 'labelme.json':
            value = dict(version='5.0.0', imagePath=f'{key}.png', imageData=None,
                imageWidth=proposal['source']['size'][0], imageHeight=proposal['source']['size'][1],
                flags=dict(nonconforming=True, ground_truth_eligible=False, counts_toward_under50=False),
                annotation_scope='single_nonconforming_target_not_GT', nonconforming_review=review,
                shapes=[dict(label='pallet_nonconforming', shape_type='polygon', points=review['polygon'], flags=dict(nonconforming=True))] if review['polygon'] else [])
            return canonical(value), 'application/json; charset=utf-8', f'{key}-nonconforming-r{review["revision"]}.json'
        if kind == 'mask.png':
            if not review['polygon']:
                raise ReviewError(400, '无法描绘记录没有掩膜；请下载包含不合格原因的JSON')
            stream = io.BytesIO(); Image.fromarray(raster_mask(review['polygon'], *proposal['source']['size']).astype(np.uint8)*255).save(stream, format='PNG')
            return stream.getvalue(), 'image/png', f'{key}-nonconforming-r{review["revision"]}.png'
        raise ReviewError(404, '不支持的导出类型')


class NonconformingGallery:
    def __init__(self, root, reviews, access_key):
        self.root = Path(root).resolve(); manifest = json.loads((self.root/'manifest.json').read_text())
        seal = json.loads((self.root/'verification.json').read_text()); self.manifest_sha256 = digest(self.root/'manifest.json')
        require(seal['state'] == 'passed_export_and_isolation_not_quality' and seal['manifest_sha256'] == self.manifest_sha256
            and digest(self.root/'proposals.jsonl') == manifest['proposals_sha256'] == seal['proposals_sha256'], 'Nonconforming manifest/proposal seal differs')
        require(seal['public_assets'] == manifest['public_assets'], 'Nonconforming public asset seal differs')
        self.proposals = {p['target_key']: p for p in map(json.loads, (self.root/'proposals.jsonl').read_text().splitlines())}
        require(len(self.proposals) == manifest['request_count'] == 7, 'Exactly seven explicit exception targets required')
        self.proposals_sha256 = digest(self.root/'proposals.jsonl'); self.count = len(self.proposals)
        self.publication_version = 'nonconforming-v1'; self.manual_request_count = 7; self.preannotation_proposals = {}
        allowed = {'report_zh.html', 'report-font.otf', 'FONT_LICENSE.txt', 'quality-editor.js'}
        allowed.update(f'{folder}/{key}.png' for key in self.proposals for folder in ('images', 'cases'))
        require(set(manifest['public_assets']) == allowed, 'Unexpected nonconforming public resource')
        self.assets = {}
        for name, expected in manifest['public_assets'].items():
            path = (self.root/name).resolve()
            require(path.is_relative_to(self.root) and not path.is_symlink() and digest(path) == expected, 'Nonconforming resource changed')
            mime = {'.html': 'text/html; charset=utf-8', '.png': 'image/png', '.otf': 'font/otf', '.txt': 'text/plain; charset=utf-8', '.js': 'text/javascript; charset=utf-8'}[path.suffix]
            self.assets['/'+name] = path, mime, expected
        for proposal in self.proposals.values():
            validate_target(proposal)
            require(proposal['image_sha256'] == manifest['public_assets'][f'images/{proposal["target_key"]}.png'], 'Wrong nonconforming target image')
        self.assets['/review-ui/editor.js'] = self.assets['/quality-editor.js']
        for name, mime in (('editor.css', 'text/css; charset=utf-8'), ('editor-font.otf', 'font/otf'), ('FONT_LICENSE.txt', 'text/plain; charset=utf-8')):
            path = ASSETS/name; self.assets['/review-ui/'+name] = path, mime, digest(path)
        self.editor = NonconformingEditor(self, reviews, access_key)
        page = (self.root/'report_zh.html').read_text()
        self.edited_page = page.replace('</html>', editor_fragment()+'</html>').encode()
        self.request_page = None
        self.csp = "default-src 'none'; img-src 'self'; font-src 'self'; connect-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"


class NonconformingHandler(Handler):
    def route(self):
        from urllib.parse import urlsplit
        if urlsplit(self.path).path == '/healthz' and self.command in ('GET', 'HEAD'):
            return self.json(dict(status='ok', service='pallet_mask_nonconforming_review', targets=7,
                source_quality='nonconforming', editing_enabled=True, counts_toward_under50=False,
                isolated_review_store=True, publication_version='nonconforming-v1'))
        return super().route()
