"""Pure closed-packet projection proposal. Importing this module performs no I/O.

One event per literal form/relation avoids an unbounded authority assertion.
It preserves source row/form order for exact independent reconstruction. Support
is scoped to this closed selection, never pooled with earlier DNB selections.
"""
import copy
import hashlib
import json

SOURCE = 'bibliographic:gnd2026-retained03'
SOURCE_ID = 'dnb-gnd-person-2026'
GROUP = 'dnb_gnd'
SCOPE = 'gnd-typed-components-retained-20260217-03'
TIER = 'bibliographic_authority'
RECEIPT_SHA = '27b4c2c3f169a88031c677e51d956792834dbcd05e424f8b356461771f9e60f8'
REPLAY_SHA = 'be1061e05721caa740f3b9107f318aeb1914d7cdc145a3c69175e3fa679d7fbd'
SNAPSHOT_SHA = '1908e6c2c3c14db8ac3b07b236b7c2615038d1b0e4c19455e59bed6e6a642335'
BASE = 'https://d-nb.info/standards/elementset/gnd#'
RELATIONS = {'preferred_name_component': BASE + 'preferredNameEntityForThePerson',
             'variant_name_component': BASE + 'variantNameEntityForThePerson'}
FIELDS = {'given': BASE + 'forename', 'family': BASE + 'surname'}
ROW_FIELDS = set(('distinct_support_records evidence_kinds form forms key language locator other_role_support '
 'preferred_component_support_records provenance representative_form_selection_does_not_relabel_source_relation '
 'role source support_kind_counts_overlap_not_additive tier typed_source_attestations variant_component_support_records').split())
PROVENANCE = {
 'metadata_license': 'CC0-1.0', 'metadata_rights_url': 'https://data.dnb.de/opendata/',
 'minimum_distinct_authority_records': 2, 'name_language_inferred': False, 'population_frequency': False,
 'private_raw_replay_sha256': REPLAY_SHA, 'publisher_snapshot': '2026-02-17T14:15Z',
 'publisher_source_sha256': SNAPSHOT_SHA,
 'publisher_source_url': 'https://data.dnb.de/opendata/authorities-gnd-person_lds_20260217.rdf.gz',
 'same_source_group_not_independent_authority_corroboration': True,
 'source_group': GROUP, 'source_identity_verified': False, 'source_scope_id': SCOPE,
 'support_unit': 'distinct_authority_records_in_this_new_selected_bulk_scope',
}

def need(ok, message):
    if not ok:
        raise ValueError(message)

def encoded(value):
    return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + '\n').encode('utf-8')

def natural(value, minimum=0):
    return type(value) is int and minimum <= value <= 3450902

def validate_source_row(row, policy):
    need(isinstance(row, dict) and set(row) == ROW_FIELDS, 'Unexpected public authority row fields')
    role, key, form = row['role'], row['key'], row['form']
    need(role in FIELDS and row['source'] == SOURCE and row['tier'] == TIER and row['language'] is None,
         'Authority source/role/unknown language differs')
    need(row['provenance'] == PROVENANCE and
         all(type(row['provenance'][name]) is type(expected) for name, expected in PROVENANCE.items()),
         'Closed authority provenance differs')
    need(isinstance(key, str) and isinstance(form, str) and policy.name_key(form) == key,
         'Authority literal normalization differs')
    forms = row['forms']
    need(isinstance(forms, list) and forms and all(isinstance(x, str) for x in forms) and
         len(set(forms)) == len(forms) and form in forms, 'Invalid authority literal forms')
    for literal in forms:
        need(len(literal.encode('utf-8')) <= 4096 and policy.name_key(literal) == key and
             policy.hygiene_reason(policy.normalize_form(literal)) is None, 'Frozen authority form gate differs')
    total, other = row['distinct_support_records'], row['other_role_support']
    need(natural(total, 2) and natural(other), 'Authority distinct support differs')
    need(not (other >= 20 and other > total * 10), 'Authority minority-role gate differs')
    need(row['representative_form_selection_does_not_relabel_source_relation'] is True and
         row['support_kind_counts_overlap_not_additive'] is True, 'Authority kind overlap/representative flag differs')
    kinds = row['evidence_kinds']
    need(isinstance(kinds, list) and kinds and len(set(kinds)) == len(kinds) and
         all(x in RELATIONS for x in kinds), 'Invalid authority relation kinds')
    support = {'preferred_name_component': row['preferred_component_support_records'],
               'variant_name_component': row['variant_component_support_records']}
    need(all(natural(n) and n <= total and ((n > 0) == (k in kinds)) for k, n in support.items()) and
         sum(support.values()) >= total, 'Overlapping authority kind support differs')
    assertions = row['typed_source_attestations']
    need(isinstance(assertions, list) and assertions, 'Missing typed literal authority attestations')
    seen = set()
    for item in assertions:
        need(isinstance(item, dict) and set(item) == {'distinct_support_records', 'evidence_kind', 'field', 'form', 'source_relation'},
             'Unexpected typed authority attestation')
        kind = item['evidence_kind']
        need(kind in kinds and item['source_relation'] == RELATIONS[kind] and item['field'] == FIELDS[role] and
             item['form'] in forms and natural(item['distinct_support_records'], 1) and
             item['distinct_support_records'] <= support[kind], 'Authority literal relation/field/support differs')
        pair = kind, item['form']
        need(pair not in seen, 'Duplicate literal authority kind/form')
        seen.add(pair)
    need({x['form'] for x in assertions} == set(forms) and {x['evidence_kind'] for x in assertions} == set(kinds),
         'Authority literal/kind coverage differs')
    need(row['locator'] == 'source-scope:' + SCOPE + '/' + role + '/' + hashlib.sha256(key.encode('utf-8')).hexdigest(),
         'Unexpected individual or changed authority locator')
    return row

def project(row, policy):
    """Yield only minimized name evidence, never an individual authority ID/link."""
    validate_source_row(row, policy)
    digest = hashlib.sha256(encoded(row)).hexdigest()
    form_ordinals = {literal: number for number, literal in enumerate(row['forms'])}
    for ordinal, assertion in enumerate(row['typed_source_attestations']):
        yield {
            'source_id': SOURCE_ID, 'tier': TIER, 'source_group': GROUP,
            'evidence_kind': assertion['evidence_kind'], 'role': row['role'], 'form': assertion['form'],
            'language': None, 'cohort': SCOPE, 'packet_receipt_sha256': RECEIPT_SHA,
            'source_row_sha256': digest, 'source_locator': row['locator'],
            'representative_form': row['form'], 'source_evidence_kinds': list(row['evidence_kinds']),
            'distinct_authority_role_key_support': row['distinct_support_records'],
            'other_role_support': row['other_role_support'],
            'preferred_component_support_records': row['preferred_component_support_records'],
            'variant_component_support_records': row['variant_component_support_records'],
            'distinct_authority_form_kind_support': assertion['distinct_support_records'],
            'primary_field': assertion['field'], 'source_relation': assertion['source_relation'],
            'source_form_ordinal': form_ordinals[assertion['form']], 'source_forms_count': len(row['forms']),
            'source_attestation_ordinal': ordinal, 'source_attestations_count': len(row['typed_source_attestations']),
        }

def recover(events, key, policy):
    """Exact data-only checker hook: recover the original minimized source row."""
    events = sorted(events, key=lambda item: item['source_attestation_ordinal'])
    need(events, 'Missing authority source events')
    first = events[0]
    need(len(events) == first['source_attestations_count'] and
         [x['source_attestation_ordinal'] for x in events] == list(range(len(events))), 'Authority evidence is incomplete')
    forms = {}
    assertions = []
    for item in events:
        ordinal = item['source_form_ordinal']
        need(ordinal not in forms or forms[ordinal] == item['form'], 'Mixed authority literal form order')
        forms[ordinal] = item['form']
        assertions.append({'distinct_support_records': item['distinct_authority_form_kind_support'],
                           'evidence_kind': item['evidence_kind'], 'field': item['primary_field'],
                           'form': item['form'], 'source_relation': item['source_relation']})
    need(sorted(forms) == list(range(first['source_forms_count'])), 'Authority literal forms are incomplete')
    row = {'distinct_support_records': first['distinct_authority_role_key_support'],
           'evidence_kinds': first['source_evidence_kinds'], 'form': first['representative_form'],
           'forms': [forms[n] for n in sorted(forms)], 'key': key, 'language': None,
           'locator': first['source_locator'], 'other_role_support': first['other_role_support'],
           'preferred_component_support_records': first['preferred_component_support_records'],
           'provenance': copy.deepcopy(PROVENANCE),
           'representative_form_selection_does_not_relabel_source_relation': True,
           'role': first['role'], 'source': SOURCE, 'support_kind_counts_overlap_not_additive': True,
           'tier': TIER, 'typed_source_attestations': assertions,
           'variant_component_support_records': first['variant_component_support_records']}
    need(list(project(row, policy)) == events, 'Authority event projection, fields or source row digest differ')
    return row

def source_catalog_entry():
    return {
        'id': SOURCE_ID, 'title': 'German National Library / GND typed name components', 'source_group': GROUP,
        'source_url': PROVENANCE['publisher_source_url'], 'policy_url': 'https://data.dnb.de/opendata/',
        'license_label': 'DNB/GND metadata — CC0 1.0',
        'license_url': 'https://creativecommons.org/publicdomain/zero/1.0/',
        'description': 'Literal forename/surname components under separately labelled preferred and variant source relations. '
                       'Support is distinct authority records within this selected scope; kind supports overlap and are not additive. '
                       'Representative spelling does not make a variant preferred. Same DNB source group is counted once, '
                       'without independent-corroboration or identity claims. Name language, origin, meaning and gender are unknown. '
                       'Individual authority links and biographical fields are omitted. NDR normalized keys and preserved literal relations/forms.',
        'downloads': [],
    }
