"""Read-only, event-specific canonical / independently preannotated source registry.

A target can have both task-origin and later canonical-publication saves. Resolve
each event by (publication, base proposal hash, target), never by target alone.
"""
from __future__ import annotations

from collections import Counter
import json
from pathlib import Path

from . import mask_saved_preannotations as original
from .cluster_targets import digest
from .mask_preannotation import validate_preannotation
from .mask_quota_saved_extension import indexed
from .mask_template_continue import sha
from .mask_template_refined import read_jsonl

SCHEMA, ORIGIN, FALSE_FLAGS = original.SCHEMA, original.ORIGIN, original.FALSE_FLAGS
IDENTITY_FIELDS = original.IDENTITY_FIELDS
raw_sha = original.raw_sha
validate_gallery_event = original.validate_gallery_event
package_manual_preview = original.package_manual_preview
completed_gallery_proposals = original.completed_gallery_proposals


def registry_key(value):
    return value.get('proposal_publication'), value.get('base_proposal_id'), value.get('target_key')


def prelabel_registry(directory, rows, formal_sha, publication, current, pose_event_keys,
                      publication_version, namespace):
    """Bind a complete independently sealed task pack to its real main publication."""
    directory = Path(directory)
    manifest = json.loads((directory/'manifest.json').read_text())
    seal = json.loads((directory/'verification.json').read_text())
    manifest_sha = digest(directory/'manifest.json')
    drafts = indexed(read_jsonl(directory/'proposals.jsonl'))
    requests = 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['parent_manifest_sha256'] != publication['manifest_sha256'] or
            manifest['parent_verification_sha256'] != publication['verification_sha256'] or
            manifest['proposals_sha256'] != digest(directory/'proposals.jsonl') or
            manifest['requests_sha256'] != digest(directory/'requests.jsonl') or
            manifest['input_manifest_sha256'] != digest(directory/'input_manifest.json') or
            seal.get('state') != 'passed' or seal.get('request_count') != len(drafts) or
            seal.get('manifest_sha256') != manifest_sha or
            seal.get('proposals_sha256') != manifest['proposals_sha256'] or
            seal.get('parent_verification_sha256') != publication['verification_sha256'] or
            digest(directory/'verification.json') != digest(directory/'independent_verification.json')):
        raise ValueError('Preannotation registry task/seal/formal/publication binding mismatch')
    publication_manifest = json.loads((publication['path']/'manifest.json').read_text())
    if publication_manifest['publication_version'] != publication_version:
        raise ValueError('Preannotation publication version mismatch')
    for assets in (manifest['public_assets'], seal['public_assets']):
        if any(digest(directory/name) != h for name, h in assets.items()):
            raise ValueError('Independently verified preannotation resource changed')
    result = {}
    for key, draft in sorted(drafts.items()):
        row, request = rows[key], requests[key]
        image_sha = 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)
        reference = dict(kind='independent_preannotation', namespace=namespace, path=directory,
            proposal=draft, proposal_sha256=sha(draft), source=identity, source_binding=sha(identity),
            binding=publication['binding'], proposal_publication=publication_version,
            publication_proposals_sha256=publication['proposals_sha256'], task_manifest_sha256=manifest_sha,
            task_verification_sha256=digest(directory/'verification.json'), request=request,
            preannotation_provenance=dict(proposal_sha256=sha(draft), assistant_draft=draft['preannotation'],
                worklist_manifest_sha256=manifest_sha, assistant_draft_not_human_edit=True))
        result[(publication_version, sha(draft), key)] = reference
    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 combine_registries(*registries):
    result = {}
    for registry in registries:
        if result.keys() & registry.keys():
            raise ValueError('Duplicate independent proposal identity')
        result.update(registry)
    return result


def task_references(registry, namespace):
    """Only the currently completed task pack may introduce new canonical entries."""
    references = [r for r in registry.values() if r['namespace'] == namespace]
    result = {r['proposal']['target_key']: r for r in references}
    if len(result) != len(references):
        raise ValueError('Duplicate target within task pack')
    return result


def resolve_event(value, rows, formal_sha, publications, registry, cache):
    identity = registry_key(value)
    publication = publications.get(identity[0])
    if publication is None:
        raise ValueError('Unknown gallery historical publication')
    if identity in registry:
        reference = registry[identity]
        if publication['binding'] != reference['binding']:
            raise ValueError('Independent preannotation main publication changed')
        return reference
    key = identity[2]
    proposal = publication['proposals'].get(key)
    if proposal is None or sha(proposal) != identity[1]:
        raise ValueError('Unknown canonical or independent proposal identity')
    row = rows[key]
    if (proposal['source'] != row or proposal['class_id'] != row['final_class_id'] or
            proposal['formal_manifest_sha256'] != formal_sha):
        raise ValueError('Canonical gallery source identity mismatch')
    if identity not in cache:
        source = {f: row[f] for f in IDENTITY_FIELDS}
        source.update(formal_manifest_sha256=formal_sha,
            image_sha256=digest(publication['path']/'images'/f'{key}.png'))
        cache[identity] = dict(kind='canonical_publication', proposal=proposal,
            proposal_sha256=sha(proposal), source=source, source_binding=sha(source),
            binding=publication['binding'], proposal_publication=identity[0])
    return cache[identity]


def gallery_source_records(db, rows, previous, parent, formal_sha, snapshot_sha, paths, registry):
    """Check every raw historical event and exact current/latest pair, without writes."""
    history_engine = original.parent_generation
    reviews = history_engine.remaining.snapshot_rows(db, 'reviews', rows)
    history_engine.remaining.snapshot_rows(db, 'events', rows)
    publications = history_engine.original.publication_inventory(paths, formal_sha)
    cache, histories, events, audit, references = {}, {}, [], [], {}
    for event_id, key, revision, raw in db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'):
        value = json.loads(raw)
        reference = resolve_event(value, rows, formal_sha, publications, registry, cache)
        validate_gallery_event(value, rows[key], reference, revision)
        histories.setdefault(key, []).append((event_id, revision, raw))
        events.append(value)
        references[event_id] = reference
        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_namespace=reference.get('namespace'),
            preannotation_provenance_validated=reference['kind'] == 'independent_preannotation'))
    if any(len({r for _, r, _ in h}) != len(h) for h in histories.values()):
        raise ValueError('Duplicate gallery historical event revision')
    sources, canonical_reviews = [], {}
    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, reference = json.loads(raw), references[event_id]
        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=reference['kind'], preannotation_namespace=reference.get('namespace')))
        if reference['kind'] == 'canonical_publication':
            canonical_reviews[key] = value
    # The frozen helper sees genuine canonical events only. Independent task
    # histories are validated above, never substituted into canonical publication
    # hashes. A later canonical save of an old task target is still routed here.
    canonical_events = [v for v, a in zip(events, audit) if a['proposal_registry'] == 'canonical_publication']
    templates = history_engine.original.gallery_templates(previous, canonical_reviews, canonical_events,
        {}, rows, parent, formal_sha, snapshot_sha, publication_paths=paths)
    return reviews, events, sources, templates, audit
