"""Read-only evidence for real gallery saves of independently supplied AI drafts.

The gallery publication binding and draft proposal hash deliberately have separate
registries. A task is not a canonical member of the publication it was edited in.
"""
from __future__ import annotations

from collections import Counter
import hashlib
import json
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw

from . import mask_remaining_round3 as parent_generation
from .mask_preannotation import validate_preannotation
from .mask_template_continue import sha
from .mask_template_refined import read_jsonl
from .mask_template_transfer import overlay, write_json
from .pose_review_geometry import polygon_value, raster_mask

SCHEMA = 'saved_gallery_mask_entry_v1'
ORIGIN = 'mask_gallery_human_revision'
FALSE_FLAGS = parent_generation.FALSE_FLAGS
IDENTITY_FIELDS = ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')


def raw_sha(raw):
    return hashlib.sha256(raw.encode('utf-8')).hexdigest()


def prelabel_registry(directory, rows, formal_sha, publication, current, pose_event_keys):
    """Validate the frozen draft and original pose dependency, never a fake pose save."""
    directory = Path(directory)
    manifest_sha = parent_generation.digest(directory/'manifest.json')
    manifest = parent_generation.read_json(directory/'manifest.json')
    drafts = parent_generation.indexed(read_jsonl(directory/'proposals.jsonl'))
    requests = parent_generation.indexed(read_jsonl(directory/'requests.jsonl'))
    if (set(drafts) != set(requests) or len(drafts) != manifest['request_count'] or
            manifest['formal_manifest_sha256'] != formal_sha or
            manifest['parent_proposals_sha256'] != publication['proposals_sha256'] or
            manifest['proposals_sha256'] != parent_generation.digest(directory/'proposals.jsonl') or
            manifest['requests_sha256'] != parent_generation.digest(directory/'requests.jsonl') or
            manifest['input_manifest_sha256'] != parent_generation.digest(directory/'input_manifest.json')):
        raise ValueError('Preannotation registry task/formal/publication binding mismatch')
    result = {}
    for key, draft in sorted(drafts.items()):
        row, request = rows[key], requests[key]
        image_sha = parent_generation.digest(directory/'images'/f'{key}.png')
        reference = validate_preannotation(draft, formal_sha, image_sha)
        old = current.get(key)
        if (draft['source'] != row or draft['class_id'] != row['final_class_id'] or
                request['source'] != row or request['class_id'] != draft['class_id'] or
                request['assistant_polygon'] != draft['polygon'] or request['preannotation'] != draft['preannotation'] or
                request.get('counts_as_completed_annotation') is not False or
                reference['snapshot_revision'] != (old['revision'] if old else 0) or
                reference['current_payload_sha256'] != (sha(old) if old else None) or
                request['existing_pose_revision'] != reference['snapshot_revision'] or
                request['existing_pose_payload_sha256'] != reference['current_payload_sha256'] or
                request['existing_pose_record'] is not bool(old) or
                (old is None and key in pose_event_keys) or
                draft['preannotation']['input_manifest_sha256'] != manifest['input_manifest_sha256'] or
                draft['preannotation'].get('author_role') != 'AI_assistant' or
                draft['preannotation'].get('counts_toward_coverage_before_real_human_save') is not False):
            raise ValueError('Preannotation draft/request/source/pose snapshot dependency changed')
        identity = {f: row[f] for f in IDENTITY_FIELDS}
        identity.update(formal_manifest_sha256=formal_sha, image_sha256=image_sha)
        result[key] = dict(kind='independent_preannotation', path=directory, proposal=draft,
            proposal_sha256=sha(draft), source=identity, source_binding=sha(identity),
            binding=publication['binding'], proposal_publication=13,
            publication_proposals_sha256=publication['proposals_sha256'],
            task_manifest_sha256=manifest_sha, request=request,
            preannotation_provenance=dict(proposal_sha256=sha(draft), assistant_draft=draft['preannotation'],
                worklist_manifest_sha256=manifest_sha, assistant_draft_not_human_edit=True))
    if Counter(p['class_id'] for p in drafts.values()) != Counter({int(c): n for c, n in manifest['class_counts'].items()}):
        raise ValueError('Preannotation manifest class inventory mismatch')
    return result


def validate_gallery_event(value, row, reference, revision):
    proposal = reference['proposal']
    if (value.get('target_key') != row['target_key'] or value.get('revision') != revision or
            value.get('source') != reference['source'] or value.get('source_binding') != reference['source_binding'] or
            value.get('binding') != reference['binding'] or value.get('base_proposal_id') != reference['proposal_sha256'] or
            value.get('proposal_publication') != reference['proposal_publication'] or
            value.get('event_kind') != 'human_mask_gallery_revision' or value.get('human_edited') is not True or
            any(value.get(f, False) is not False for f in parent_generation.remaining.CONFIRMATION_FLAGS + ('full_six_dof',)) or
            any((value.get('pose') or {}).get(f, False) is not False
                for f in parent_generation.remaining.CONFIRMATION_FLAGS + ('full_six_dof',)) or
            any(value.get(f, False) is not False for f in ('machine_draft', 'machine_transfer_performed', 'automatic_human_confirmation')) or
            value.get('vertex_count') != len(value.get('polygon', [])) or
            value.get('state') in ('deleted', 'deferred', 'confirmed')):
        raise ValueError('Gallery historical source/image/publication/human/flags mismatch')
    polygon_value(value['polygon'], *row['size'])
    if reference['kind'] == 'independent_preannotation':
        if (value.get('preannotation_provenance') != reference['preannotation_provenance'] or
                value.get('proposal_polygon') != proposal['polygon'] or
                value.get('original_vertex_count') != proposal['vertex_count'] or
                value.get('template_provenance') is not None or value.get('human_source_provenance') is not None or
                value.get('pose') is not None or value.get('pose_store_written') is not False or
                value.get('original_proposal_modified') is not False or
                value.get('status') != 'human_edited_draft_pending_confirmation' or
                value.get('mask_semantics') != proposal['mask_semantics'] or
                not isinstance(value.get('reviewer'), str) or not value['reviewer'].strip()):
            raise ValueError('Saved preannotation historical task/draft/provenance/pose flags mismatch')


def gallery_source_records(db, rows, previous, parent, formal_sha, snapshot_sha, paths, registry):
    """Audit every current/raw historical row, separating canonical and task hashes."""
    remaining = parent_generation.remaining
    reviews = remaining.snapshot_rows(db, 'reviews', rows)
    remaining.snapshot_rows(db, 'events', rows)
    publications = parent_generation.original.publication_inventory(paths, formal_sha)
    references, histories, events, audit = {}, {}, [], []
    for event_id, key, revision, raw in db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'):
        value = json.loads(raw)
        publication = publications.get(value.get('proposal_publication'))
        if key in registry:
            reference = registry[key]
            if publication is None or publication['binding'] != reference['binding']:
                raise ValueError('Preannotation main gallery publication changed')
        else:
            if publication is None or key not in publication['proposals']:
                raise ValueError('Unknown canonical gallery historical publication/source')
            proposal = publication['proposals'][key]
            if (proposal['source'] != rows[key] or proposal['class_id'] != rows[key]['final_class_id'] or
                    proposal['formal_manifest_sha256'] != formal_sha):
                raise ValueError('Canonical gallery source identity mismatch')
            cache_key = (value['proposal_publication'], key)
            if cache_key not in references:
                identity = {f: rows[key][f] for f in IDENTITY_FIELDS}
                identity.update(formal_manifest_sha256=formal_sha,
                    image_sha256=parent_generation.digest(publication['path']/'images'/f'{key}.png'))
                references[cache_key] = dict(kind='canonical_publication', proposal=proposal,
                    proposal_sha256=sha(proposal), source=identity, source_binding=sha(identity),
                    binding=publication['binding'], proposal_publication=value['proposal_publication'])
            reference = references[cache_key]
        validate_gallery_event(value, rows[key], reference, revision)
        histories.setdefault(key, []).append((event_id, revision, raw))
        events.append(value)
        audit.append(dict(target_key=key, event_id=event_id, revision=revision, payload_raw_sha256=raw_sha(raw),
            proposal_publication=value['proposal_publication'], source_binding=value['source_binding'],
            base_proposal_id=value['base_proposal_id'], historical_binding_validated=True,
            proposal_registry=reference['kind'], preannotation_provenance_validated=key in registry))
    sources = []
    for key, revision, raw in db.execute('SELECT target_key,revision,payload FROM reviews ORDER BY target_key'):
        history = histories.get(key, [])
        if (not history or len({r for _, r, _ in history}) != len(history) or
                history[-1][1:] != (revision, raw) or max(r for _, r, _ in history) != revision):
            raise ValueError('Gallery current is not exact raw unique latest event')
        event_id, _, event_raw = history[-1]
        value = json.loads(raw)
        sources.append(dict(target_key=key, revision=revision, current_payload_raw=raw,
            current_payload_raw_sha256=raw_sha(raw), current_payload=value, current_payload_sha256=sha(value),
            human_event_id=event_id, human_event_payload_raw=event_raw, human_event_sha256=raw_sha(event_raw),
            snapshot_sha256=snapshot_sha, history_event_ids=[i for i, _, _ in history],
            proposal_registry='independent_preannotation' if key in registry else 'canonical_publication'))
    # The frozen old helper accepts canonical publications only. No patched global,
    # substituted proposal hash, or manufactured canonical task is ever passed in.
    templates = parent_generation.original.gallery_templates(previous,
        {k: v for k, v in reviews.items() if k not in registry},
        [v for v in events if v['target_key'] not in registry], {}, rows, parent,
        formal_sha, snapshot_sha, publication_paths=paths)
    return reviews, events, sources, templates, audit


def completed_gallery_proposals(registry, reviews, sources, rows, previous, current,
                               pose_sha, gallery_sha, formal_sha, classification_sha, namespace,
                               prohibited_frames=()):
    frames = {p['source']['frame_id'] for p in previous} | set(prohibited_frames)
    keys = set(parent_generation.indexed(previous))
    result = []
    for key, reference in sorted(registry.items()):
        if key not in reviews or key not in sources:
            raise ValueError('Preannotation task has no real saved gallery current/event')
        row, value, record = rows[key], reviews[key], sources[key]
        if (key in keys or row['frame_id'] in frames or len(value['polygon']) != 4 or
                parent_generation.remaining.original_rectangle(value['polygon'], row)):
            raise ValueError('Saved gallery contour repeats a protected frame or is an original rectangle/non-quad')
        validate_gallery_event(value, row, reference, record['revision'])
        if record['current_payload_raw'] != record['human_event_payload_raw']:
            raise ValueError('Saved gallery current/event raw pair mismatch')
        gallery_review = dict(target_key=key, revision=value['revision'], payload_sha256=sha(value),
            source_binding=value['source_binding'], polygon_sha256=sha(value['polygon']), snapshot_sha256=gallery_sha,
            proposal_publication=value['proposal_publication'], publication_proposals_sha256=reference['publication_proposals_sha256'],
            base_proposal_id=value['base_proposal_id'], current_payload_raw_sha256=record['current_payload_raw_sha256'],
            human_event_id=record['human_event_id'], human_event_raw_sha256=record['human_event_sha256'],
            task_manifest_sha256=reference['task_manifest_sha256'],
            preannotation_provenance=reference['preannotation_provenance'])
        human_source = dict(target_key=key, origin=ORIGIN, gallery_review=gallery_review,
            polygon_sha256=sha(value['polygon']), image_sha256=value['source']['image_sha256'])
        old = current.get(key)
        result.append(dict(schema=SCHEMA, origin=ORIGIN, target_key=key, source=row, class_id=row['final_class_id'],
            polygon=value['polygon'], vertex_count=len(value['polygon']), human_edited=True,
            status='saved_gallery_human_contour_draft_pending_confirmation', production_saved=False,
            saved_gallery_manual_source=True, manual_four_point_source=True, propagation_seed_eligible=False,
            human_source=human_source, rendering_id=namespace+':manual_source:'+key,
            mask_semantics='real_saved_gallery_human_contour_not_pose_not_GT',
            preannotation_provenance=reference['preannotation_provenance'],
            manual_request_sha256=sha(reference['request']), assistant_draft_proposal_sha256=reference['proposal_sha256'],
            polygon_changed_from_assistant_draft=value['polygon'] != reference['proposal']['polygon'],
            target_expected_revision=old['revision'] if old else 0,
            target_snapshot_payload_sha256=sha(old) if old else None,
            snapshot_sha256=pose_sha, gallery_snapshot_sha256=gallery_sha,
            formal_manifest_sha256=formal_sha, class_assignments_sha256=classification_sha,
            machine_draft=False, machine_transfer_performed=False, pose_store_written=False,
            gallery_store_written=False, new_human_edit_created=False, classification_is_candidate_not_truth=True,
            metrics={}, flags=['real_gallery_save_four_points_no_seed_not_pose_not_GT'],
            **dict.fromkeys(FALSE_FLAGS, False)))
        keys.add(key)
        frames.add(row['frame_id'])
    return result


def package_manual_preview(out, manual, evidence):
    """Draw saved gallery polygons directly; never route them through pose/template writers."""
    for proposal in manual:
        if (proposal['schema'] != SCHEMA or 'template' in proposal or
                proposal['human_source']['target_key'] != proposal['target_key']):
            raise ValueError('Explicit saved gallery rendering schema required')
        key, row = proposal['target_key'], proposal['source']
        image = evidence.image(row['frame_id'])
        panel = Image.new('RGB', (1480, 305), '#121923')
        draw = ImageDraw.Draw(panel)
        draw.text((15, 8), f'Class {proposal["class_id"]} | REAL SAVED GALLERY HUMAN CONTOUR | NOT pose / template / GT', fill='white')
        panel.paste(overlay(image, row, proposal['polygon'], '#55ceff'), (0, 30))
        proof = proposal['human_source']['gallery_review']
        for y, text in ((55, f'Real gallery revision {proof["revision"]}; raw human event {proof["human_event_id"]}.'),
                (85, 'Current saved polygon, NOT the initial assistant draft.'),
                (115, 'Four original saved vertices; no fabricated extra points.'),
                (145, 'No propagation seed, pose write or automatic confirmation.'),
                (175, 'GT / automatic training / robot control: disabled.')):
            draw.text((765, y), text, fill='white')
        draw.text((15, 284), f'{key} | {row["split"]} | raw {proof["current_payload_raw_sha256"][:24]}', fill='white')
        panel.save(out/'cases'/f'{key}.png')
        Image.fromarray(image).save(out/'images'/f'{key}.png')
        if parent_generation.digest(out/'images'/f'{key}.png') != proposal['human_source']['image_sha256']:
            raise ValueError('Rendered gallery native image bytes differ from actual saved image binding')
        Image.fromarray(raster_mask(proposal['polygon'], *row['size']).astype(np.uint8)*255).save(out/'masks'/f'{key}.png')
        flags = dict(human_edited=True, human_confirmed=False, machine_draft=False,
            saved_gallery_manual_source=True, manual_four_point_source=True, propagation_seed_eligible=False,
            **dict.fromkeys(FALSE_FLAGS, False))
        write_json(out/'labelme'/f'{key}.json', dict(version='5.0.0', imagePath=f'../images/{key}.png',
            imageData=None, imageWidth=row['size'][0], imageHeight=row['size'][1],
            annotation_scope='single_target_mask_review_not_full_frame', other_objects_unchanged=True,
            flags=flags, saved_gallery_source=proposal['human_source'],
            shapes=[dict(label='pallet', points=proposal['polygon'], shape_type='polygon', group_id=row['box_index'], flags=flags)],
            mask_gallery_provenance=proposal))
