"""One fresh, private V5 writer. Only closed PL/SSB inputs; no publication."""
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
import copy
import ctypes
import gzip
import hashlib
import json
import os
import re
import shutil
import sqlite3
import sys
import zipfile

ROOT = Path(__file__).resolve().parents[3]
WORK = Path(__file__).parent
BASE = WORK.parent
V4 = BASE / 'public-expansion-v4'
OLD_RELEASE = 'bd6cd4af10c570a666ac6e02'
sys.path[:0] = [str(V4), str(ROOT / 'scripts_build')]
from catalog_v4 import Catalog
from public_name_segment_layout import SCHEMA, Segments, View
from public_name_v3_projection import EvidencePages, head, attach_evidence
import build_public_name_directory as helpers

def check(ok, message):
    if not ok:
        raise RuntimeError(message)

def sha(path):
    digest = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(chunk)
    return digest.hexdigest()

def read(path):
    return json.loads(Path(path).read_text('utf-8'))

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

def save(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open('xb') as stream:
        stream.write(encoded(value))

def rows(path):
    with gzip.open(path, 'rt', encoding='utf-8') as stream:
        for line in stream:
            check(len(line.encode('utf-8')) <= 65536, 'Official packet row exceeds fixed bound')
            yield json.loads(line)

def pin(path):
    return {'path': Path(path).relative_to(ROOT).as_posix(), 'bytes': Path(path).stat().st_size, 'sha256': sha(path)}

def report(stage, **fields):
    print(json.dumps({'stage': stage, 'at': datetime.now(timezone.utc).isoformat(), **fields}), flush=True)

SPECS = [
    {'id': 'pl-pesel-public-2026', 'scope': 'pl-pesel-20260120-public02',
     'folder': 'official-public-readiness-20261102/pl-pesel-01', 'packet': 'packet-02',
     'closed_sha': 'c1cea331772cd260b78c35dac635035671b660912d5606e34f3b98bedb9f4ae0',
     'receipt_sha': '77d131de064ab544d5ca6ea8161ca57bf36c05a61f33b238d71fe6fdd2b554c8',
     'source': 'official:pl_pesel_2026', 'roles': {'family': 598294, 'given': 79747},
     'keys': 661275, 'rows': 678177, 'license': 'CC0-1.0'},
    {'id': 'no-ssb-protected-surnames-2025', 'scope': 'no-ssb-20251231-public01',
     'folder': 'fresh-official-supply-20261102', 'packet': 'packet-01',
     'closed_sha': '0490d3a05613ddaf3bdbaa6d26e256226e1e62edbec7204bb641948d170f3015',
     'receipt_sha': '79fa4b1da2f7a29303d4ec6ae3e244faa9969f50ca822f5d48e278f0e46eef06',
     'source': 'official:no_ssb_protected_surnames_20251231', 'roles': {'family': 315862},
     'keys': 315862, 'rows': 315862, 'license': 'CC-BY-4.0'},
]

def freeze():
    check(not (WORK / 'INPUT_MANIFEST.json').exists(), 'Fresh V5 destination required')
    manifest = read(ROOT / f'site/assets/public-name-data/{OLD_RELEASE}/manifest.json')
    check(manifest['release'] == OLD_RELEASE and manifest['totals']['spellings'] == 1211234, 'Live V4 baseline differs')
    db_path = V4 / 'private-catalog/catalog.sqlite3'
    old_closure = read(V4 / 'CATALOG_CLOSED_RECEIPT.json')
    check(sha(db_path) == old_closure['catalog_sha256'], 'Closed V4 catalog differs')
    dependencies = [pin(V4 / 'CATALOG_CLOSED_RECEIPT.json'), pin(V4 / 'EXECUTION_RECEIPT.json'),
                    pin(V4 / f'KEY_ROLE_INDEX_{OLD_RELEASE}.jsonl.gz'), pin(db_path)]
    for spec in SPECS:
        folder = BASE / spec['folder']
        packet = folder / spec['packet']
        check(sha(folder / 'CLOSED_HANDOFF.json') == spec['closed_sha'], 'Source closure changed')
        check(sha(packet / 'RECEIPT.json') == spec['receipt_sha'], 'Preferred packet receipt changed')
        receipt = read(packet / 'RECEIPT.json')
        check(receipt['complete'] is True, 'Incomplete source packet')
        dependencies.extend([pin(folder / 'CLOSED_HANDOFF.json'), pin(packet / 'RECEIPT.json')])
        if spec['license'] == 'CC0-1.0':
            check(sha(folder / 'INDEPENDENT_REPLAY_AND_PUBLICATION_READINESS.json') ==
                  '6bfc6d5640a09eff52544dc8672a1801312d9d71e6661fdf6a58526019e18f5d' and
                  sha(folder / 'OUTPUT_CHECK.json') == '95e071b9f062ae1526b6b1058ea161feb600272feb2762524d57140dc0a8240e' and
                  read(folder / 'OUTPUT_CHECK.json')['passed'] is True, 'PL replay/publication closure differs')
            dependencies.extend([pin(folder / 'INDEPENDENT_REPLAY_AND_PUBLICATION_READINESS.json'), pin(folder / 'OUTPUT_CHECK.json')])
        else:
            check(sha(folder / 'INDEPENDENT_SOURCE_REPLAY.json') ==
                  'fd070ba5427c403f805f9257f34eba64548e6d4f1dacfa2d5c00ab6870088b68' and
                  sha(folder / 'SOURCE_RIGHTS_AND_PRIVACY_AUDIT.json') ==
                  'b4f017d3204bc3b00f4d4d5a16d92f08c0db90c532beb36194a225dd022cc717', 'SSB raw replay/rights closure differs')
            dependencies.extend([pin(folder / 'INDEPENDENT_SOURCE_REPLAY.json'), pin(folder / 'SOURCE_RIGHTS_AND_PRIVACY_AUDIT.json')])
        for name, item in receipt['artifacts'].items():
            actual = pin(packet / name)
            check(actual['sha256'] == item['sha256'] and actual['bytes'] == item['bytes'], 'Packet artifact differs: ' + name)
            dependencies.append(actual)
        spec['names_sha256'] = receipt['artifacts']['NAMES.jsonl.gz']['sha256']
    protected = [pin(p) for p in sorted((ROOT / 'site').rglob('*')) if p.is_file() and '.wrangler' not in p.parts]
    save(WORK / 'BASELINE_SITE_MANIFEST.json', {'files': protected})
    result = {'schema': 'ndr-public-v5-closed-official-inputs/1', 'ok': True,
              'frozen_at': datetime.now(timezone.utc).isoformat(), 'baseline_release': OLD_RELEASE,
              'baseline_keys': 1211234, 'inputs': SPECS, 'dependencies': dependencies,
              'baseline_manifest_sha256': sha(ROOT / f'site/assets/public-name-data/{OLD_RELEASE}/manifest.json'),
              'baseline_site_manifest_sha256': sha(WORK / 'BASELINE_SITE_MANIFEST.json'),
              'source_proof_scope': 'Exact completed raw replay/qualification/privacy receipts reused; no reacquisition or new raw replay.',
              'excluded': ['DataCite10/11', 'ORCID05 and later', 'INSEE', 'GND', 'all later packets'],
              'no_collected_global_increment': True, 'no_language_origin_meaning_gender_inference': True,
              'writer_sha256': sha(__file__)}
    save(WORK / 'INPUT_MANIFEST.json', result)
    report('closed_inputs_frozen', sources=len(SPECS), baseline=1211234)
    return result

def event(row, spec, policy):
    role, key, form = row['role'], row['key'], row['form']
    check(role in spec['roles'] and row['tier'] == 'official' and row['source'] == spec['source'] and
          row['language'] is None and policy.name_key(form) == key and
          policy.hygiene_reason(policy.normalize_form(form)) is None, 'Official literal role/normalization differs')
    proof = row['provenance']
    if spec['license'] == 'CC0-1.0':
        check(set(row) == {'role', 'key', 'form', 'language', 'source', 'tier', 'locator', 'provenance'}, 'Unexpected public PESEL field')
        check(proof['license'] == spec['license'] and proof['primary_typed_field_attestation'] is True and
              proof['name_language_origin_meaning_gender_inferred'] is False and proof['identity_validated'] is False,
              'PESEL source evidence differs')
        witnesses = proof['witnesses']
        fields = {'dataset_id', 'resource_id', 'csv_file_sha256', 'csv_row', 'source_field', 'raw_name_utf8_sha256', 'raw_row_canonical_sha256', 'published_count', 'locator'}
        check(witnesses and all(set(w) == fields and type(w['csv_row']) is int and w['csv_row'] > 0 and
              type(w['published_count']) is int and w['published_count'] >= 2 and
              re.fullmatch('[0-9a-f]{64}', w['raw_name_utf8_sha256']) and
              re.fullmatch('[0-9a-f]{64}', w['raw_row_canonical_sha256']) for w in witnesses), 'PESEL exact literal/count witness differs')
        kind = 'official_typed_name_field'
    else:
        allowed = {'count_status', 'form', 'frequency_cell', 'key', 'language', 'language_status', 'license', 'locator', 'primary_frequency', 'provenance', 'publisher_count_marker', 'role', 'source', 'source_cell', 'source_reference_date', 'source_row', 'suppressed_cells', 'tier'}
        check(set(row) == allowed and role == 'family' and row['license'] == 'CC-BY-4.0' and
              proof['source_file_sha256'] == '7a3147a17e10ea2745edcfd9b5cf49bcf5fd13f1174d26b7208304741afea68c' and
              re.fullmatch('[0-9a-f]{64}', proof['raw_name_utf8_sha256']) and
              proof['language_origin_meaning_gender_inferred'] is False and proof['identity_validated'] is False,
              'SSB explicit official field differs')
        check((row['count_status'] == 'unknown' and row['primary_frequency'] is None and row['publisher_count_marker'] == ':') or
              (row['count_status'] == 'exact' and type(row['primary_frequency']) is int and row['primary_frequency'] >= 0), 'SSB suppression/count differs')
        kind = 'official_surname_list'
    return {'source_id': spec['id'], 'tier': 'official', 'evidence_kind': kind, 'role': role, 'form': form,
            'language': None, 'cohort': spec['scope'], 'packet_receipt_sha256': spec['receipt_sha'], 'official_record': row}

def catalog(frozen):
    directory = WORK / 'private-catalog'
    directory.mkdir()
    dest = directory / 'catalog.sqlite3'
    check(not dest.exists(), 'Fresh catalog required')
    check(not (V4 / 'private-catalog/catalog.sqlite3-wal').exists() or
          (V4 / 'private-catalog/catalog.sqlite3-wal').stat().st_size == 0, 'Original closed catalog has uncheckpointed WAL')
    shutil.copyfile(V4 / 'private-catalog/catalog.sqlite3', dest)
    check(sha(dest) == next(x['sha256'] for x in frozen['dependencies'] if x['path'].endswith('private-catalog/catalog.sqlite3')),
          'Exact immutable baseline copy differs')
    census = sqlite3.connect(WORK / 'scope-census.sqlite3')
    census.executescript('PRAGMA journal_mode=WAL; PRAGMA cache_size=-32768; CREATE TABLE names(key TEXT PRIMARY KEY,mask INTEGER,prior_mask INTEGER) WITHOUT ROWID;')
    old_pairs = 0
    with gzip.open(V4 / f'KEY_ROLE_INDEX_{OLD_RELEASE}.jsonl.gz', 'rt', encoding='utf-8') as stream:
        for line in stream:
            row = json.loads(line)
            mask = sum({'given': 1, 'family': 2}[r] for r in row['roles'])
            census.execute('INSERT INTO names VALUES(?,?,?)', (row['key'], mask, mask)); old_pairs += mask.bit_count()
    census.commit()
    check(census.execute('SELECT count(*) FROM names').fetchone()[0] == 1211234, 'Prior key export differs')
    c = Catalog(dest)
    policy = helpers.policy()
    for rank, spec in enumerate(SPECS, 10000):
        seen = set(); pairs = set(); counts = Counter(); count = 0
        for row in rows(BASE / spec['folder'] / spec['packet'] / 'NAMES.jsonl.gz'):
            triple = (row['role'], row['key'], row['form'])
            check(triple not in seen, 'Duplicate official literal observation'); seen.add(triple)
            pair = (row['role'], row['key']); pairs.add(pair)
            c.event(row['key'], row['form'], event(row, spec, policy), rank)
            mask = {'given': 1, 'family': 2}[row['role']]
            census.execute('INSERT INTO names VALUES(?,?,0) ON CONFLICT(key) DO UPDATE SET mask=names.mask|excluded.mask', (row['key'], mask))
            count += 1
            if count % 25000 == 0:
                c.db.commit(); census.commit(); report('official_rows', source=spec['id'], rows=count)
        counts.update(role for role, _ in pairs)
        check(count == spec['rows'] and dict(counts) == spec['roles'] and len({k for _, k in pairs}) == spec['keys'], 'Frozen official source census differs')
        c.db.execute('INSERT INTO units VALUES(?,?,?)', (spec['scope'], spec['names_sha256'], count))
        c.db.commit(); census.commit()
    total, given, family, shared, added = census.execute('SELECT count(*),sum((mask&1)>0),sum((mask&2)>0),sum(mask=3),sum(prior_mask=0) FROM names').fetchone()
    check(given + family - shared == total, 'Role union arithmetic differs')
    c.db.execute('CREATE INDEX IF NOT EXISTS events_by_key ON events(key,seq)'); c.db.commit()
    wanted = census.execute('SELECT key,mask FROM names ORDER BY key')
    matched = 0
    with (WORK / 'EXPECTED_KEY_ROLES.jsonl.gz').open('xb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0) as out:
        for key, in c.db.execute('SELECT key FROM names ORDER BY key'):
            roles = [r[0] for r in c.db.execute('SELECT role FROM roles WHERE key=? ORDER BY role', (key,))]
            mask = sum({'given': 1, 'family': 2}[r] for r in roles)
            check(next(wanted, None) == (key, mask), 'Exact independently merged role/key census differs')
            out.write(encoded({'key': key, 'roles': roles})); matched += 1
    check(next(wanted, None) is None and matched == total, 'Exact merged key total differs')
    c.db.execute('PRAGMA wal_checkpoint(TRUNCATE)'); c.close()
    census.execute('PRAGMA wal_checkpoint(TRUNCATE)'); census.close()
    result = {'ok': True, 'closed_at': datetime.now(timezone.utc).isoformat(), 'input_manifest_sha256': sha(WORK / 'INPUT_MANIFEST.json'),
              'baseline_keys': 1211234, 'keys': total, 'given_role_keys': given, 'family_role_keys': family,
              'shared_role_keys': shared, 'additional_public_keys': added, 'prior_role_pairs_preserved': old_pairs,
              'catalog_sha256': sha(dest), 'key_role_index_sha256': sha(WORK / 'EXPECTED_KEY_ROLES.jsonl.gz'),
              'all_native_official_source_role_form_counts_exact': True, 'no_collected_union_increment': True}
    save(WORK / 'CATALOG_CLOSED_RECEIPT.json', result)
    report('catalog_closed', **result)
    return result

def source_catalog(old):
    sources = copy.deepcopy(old['sources'])
    sources.extend([
        {'id': SPECS[0]['id'], 'title': 'Poland PESEL published given-name and surname fields',
         'source_url': 'https://api.dane.gov.pl/1.4/datasets/1667,lista-imion-wystepujacych-w-rejestrze-pesel-osoby-zyjace',
         'license_label': 'CC0 1.0 (publisher datasets 1667 and 1681)', 'license_url': 'https://creativecommons.org/publicdomain/zero/1.0/',
         'policy_url': 'https://api.dane.gov.pl/1.4/datasets/1681,nazwiska-osob-zyjacych-wystepujace-w-rejestrze-pesel',
         'description': 'Six national CSV resources dated January 20, 2026 explicitly publish first/second given-name fields and current surnames. Only literal qualified name fields, per-resource published counts, row/field locators and hashes are included. Publisher-omitted singletons and deceased people are not reconstructed. Counts are never pooled or treated as people or worldwide frequency. Source jurisdiction does not establish name language, origin, meaning or gender. Existing Japanese checkpoint corroboration remains separate from these primary national field witnesses. NDR normalized spelling keys, applied the frozen hygiene rules, retained source roles/forms/witnesses, and deduplicated spelling keys. No personal PESEL identifiers or contact records are included.', 'downloads': []},
        {'id': SPECS[1]['id'], 'title': 'Statistics Norway published protected-surname list',
         'source_url': 'https://www.ssb.no/befolkning/navn/statistikk/navn/artikler/etternavn',
         'license_label': 'CC BY 4.0 — Statistics Norway (SSB)', 'license_url': 'https://creativecommons.org/licenses/by/4.0/',
         'policy_url': 'https://www.ssb.no/diverse/lisens',
         'description': 'Statistics Norway, protected surnames as of December 31, 2025, worksheet Ark1, explicitly typed NAVN surname column. The publisher describes spelling/variant handling; no original-language or original-script reconstruction is attempted. Colon-suppressed counts remain unknown, never zero or inferred; disclosed source counts remain separate. Official list presence is evidence for a spelling and surname role, not identity validation or name-availability advice. Language, origin, meaning and gender are unknown. NDR extracted literal fields, applied frozen normalization/hygiene, preserved exact workbook/cell/name hashes and source suppression, and deduplicated spelling keys. Attribution: Statistics Norway (SSB), linked source and CC BY 4.0 license. These transformations are modifications by Names Done Right.', 'downloads': []}
    ])
    return sources

def build(closed):
    old = read(ROOT / f'site/assets/public-name-data/{OLD_RELEASE}/manifest.json')
    code = {str(p.relative_to(ROOT)): sha(p) for p in [Path(__file__), V4 / 'catalog_v4.py',
            ROOT / 'scripts_build/public_name_v3_catalog.py', ROOT / 'scripts_build/public_name_v3_projection.py',
            ROOT / 'scripts_build/public_name_segment_layout.py']}
    release = hashlib.sha256(encoded({'schema': SCHEMA, 'inputs': sha(WORK / 'INPUT_MANIFEST.json'), 'catalog': closed['catalog_sha256'], 'code': code})).hexdigest()[:24]
    stage = WORK / 'staging' / release
    target = stage / 'assets/public-name-data' / release
    target.mkdir(parents=True)
    projection = sqlite3.connect(WORK / 'projection.sqlite3')
    projection.executescript('PRAGMA cache_size=-32768; CREATE TABLE heads(key TEXT PRIMARY KEY,data TEXT,roles TEXT);')
    evidence = Segments(target, release, segment_bytes=512 * 1024, start_number=500000)
    pages = EvidencePages(evidence, projection)
    c = Catalog(WORK / 'private-catalog/catalog.sqlite3')
    totals = Counter(); languages = Counter(); largest = (0, '')
    for row in c.records():
        totals['spellings'] += 1; totals['role_keys'] += len(row['roles'])
        for role in row['roles']: totals[role + '_role_keys'] += 1
        totals['corroborated_spellings'] += bool(row['corroborated_roles'])
        totals['training_source_spellings'] += bool(row['primary_locators'])
        totals['source_attested_spellings'] += bool(row.get('attestations'))
        totals['training_source_only_spellings'] += bool(row['primary_locators']) and not row['corroborated_roles'] and not row.get('attestations')
        totals['source_role_differences'] += row['source_role_difference']
        for item in row.get('attestations', []):
            if item['tier'] == 'lexical_sharealike': languages[(item['language'], item['language_name'])] += 1
        largest = max(largest, (len(encoded(row)), row['key']))
        compact = head(row, pages.add(row))
        projection.execute('INSERT INTO heads VALUES(?,?,?)', (row['key'], encoded(compact).decode(), json.dumps(row['roles'])))
        if totals['spellings'] % 25000 == 0:
            projection.commit(); report('evidence_projected', keys=totals['spellings'])
    pages.flush(); evidence.close(); projection.commit()
    check(totals['spellings'] == closed['keys'] and totals['given_role_keys'] == closed['given_role_keys'] and
          totals['family_role_keys'] == closed['family_role_keys'] and totals['corroborated_spellings'] == 31818 and
          totals['training_source_spellings'] == 135249 and len({code for code, _ in languages}) == 224, 'Complete source/evidence census differs')
    totals['additional_public_spellings'] = closed['additional_public_keys']
    hot = Segments(target, release, segment_bytes=128 * 1024)
    writers = {role: View(hot, role, target_page_bytes=32 * 1024, page_rows=25) for role in ('all', 'given', 'family')}
    largest_head = (0, '')
    for key, data, roles in projection.execute('SELECT key,data,roles FROM heads ORDER BY key'):
        row = attach_evidence(json.loads(data), projection)
        largest_head = max(largest_head, (len(encoded(row)), key))
        writers['all'].add(row)
        for role in json.loads(roles): writers[role].add(row)
    views = {role: writer.finish() for role, writer in writers.items()}
    hot.close(); projection.close(); c.close()
    sources = source_catalog(old)
    def download(source, filename, label, kind, data):
        check(len(data) <= 25 * 1024 * 1024, 'Actual public asset exceeds fixed cap')
        path = target / 'downloads' / filename
        if path.exists(): check(path.read_bytes() == data, 'Conflicting shared public support filename')
        else:
            path.parent.mkdir(exist_ok=True); path.write_bytes(data)
        source['downloads'].append({'kind': kind, 'label': label, 'original_filename': filename,
                                   'url': f'/assets/public-name-data/{release}/downloads/{filename}', 'bytes': len(data), 'sha256': sha(path)})
    for spec in SPECS:
        source = next(s for s in sources if s['id'] == spec['id'])
        packet = BASE / spec['folder'] / spec['packet']
        prefix = 'pl' if spec['license'] == 'CC0-1.0' else 'ssb'
        # Exact binary slices reconstruct the original compressed source packet.
        chunks = []
        with (packet / 'NAMES.jsonl.gz').open('rb') as stream:
            for number in range(1000):
                data = stream.read(15 * 1024 * 1024)
                if not data: break
                name = f'{prefix}-names.gz.part{number:03d}'
                download(source, name, f'Original admitted source packet, consecutive binary part {number + 1}', 'source', data)
                chunks.append({'part': number, 'file': name, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()})
        chunk_manifest = {'original_filename': 'NAMES.jsonl.gz', 'original_sha256': spec['names_sha256'],
                          'instruction': 'Concatenate binary parts in part order before gzip decompression. These are consecutive byte ranges of ONE gzip file.', 'chunks': chunks}
        download(source, f'{prefix}-parts.json', 'Original packet reconstruction manifest and hashes', 'source', encoded(chunk_manifest))
        metadata = WORK / f'{prefix}-proofs.zip'
        with zipfile.ZipFile(metadata, 'x', compression=zipfile.ZIP_DEFLATED) as bundle:
            for name in ('RECEIPT.json', 'SOURCE.json', 'NOTICE.txt', 'MODIFICATIONS.json', 'COUNTS.json', 'PRIMARY_REUSE_EVIDENCE.json'):
                if (packet / name).exists():
                    info = zipfile.ZipInfo(name, date_time=(2026, 11, 2, 0, 0, 0)); info.compress_type = zipfile.ZIP_DEFLATED
                    bundle.writestr(info, (packet / name).read_bytes())
        download(source, metadata.name, 'Source hashes, original notices, reuse conditions and modification evidence', 'source', metadata.read_bytes())
        download(source, f'{prefix}-NOTICE.txt', 'Publisher attribution, license and modification notice', 'notice', (packet / 'NOTICE.txt').read_bytes())
    cutoff = {'release': release, 'prior_public_release': OLD_RELEASE, 'inputs': SPECS,
              'input_manifest_sha256': sha(WORK / 'INPUT_MANIFEST.json'), 'global_collected_increment': 0,
              'official_list_presence_not_independent_corroboration': True,
              'unknown_language_origin_meaning_gender': True, 'SSB_suppression_not_reconstructed': True,
              'original_gzip_packets_reconstructable_from_exact_binary_parts': True}
    for source in sources:
        download(source, 'v5-cutoff.json', 'Frozen V5 source scope and conditions', 'notice', encoded(cutoff))
        download(source, 'build_v5.py', 'V5 transformation source', 'modifications', Path(__file__).read_bytes())
    manifest = {**old, 'release': release, 'totals': dict(totals), 'sources': sources, 'views': views,
                'storage': {**old['storage'], 'hot_segments': len(hot.files), 'evidence_segments': len(evidence.files)},
                'lexical_language_attestations': [{'code': code, 'name': name, 'observations': count} for (code, name), count in sorted(languages.items(), key=lambda x: (x[0][1].casefold(), x[0][0]))],
                'limitations': old['limitations'] + ['Poland/Statistics Norway source geography and publisher sex categories do not establish name language, origin, meaning or gender. Official list presence is not identity validation, worldwide frequency or independent same-role corroboration. Suppressed or omitted source counts stay unknown.']}
    check(len(encoded(manifest)) <= 512 * 1024, 'Actual manifest transport cap exceeded')
    (target / 'manifest.json').write_bytes(encoded(manifest))
    (stage / 'assets/public-name-data/manifest.json').write_bytes(encoded(manifest))
    # Reuse the closed upper-index compiler without executing its builder.
    from build_v4 import compile_indexes
    indexes = compile_indexes(views, target, release)
    generated = stage / 'functions/_lib/active-public-name-release.js'
    generated.parent.mkdir(parents=True)
    generated.write_text('const freeze=(v)=>{if(v&&typeof v==="object"){Object.freeze(v);for(const c of Object.values(v))freeze(c);}return v;};\nconst data=freeze(' + json.dumps({'manifest': manifest, 'indexes': indexes}, ensure_ascii=True, separators=(',', ':')) + ');\nexport const activeManifest=data.manifest;\nexport const compiledIndexes=data.indexes;\n', encoding='utf-8')
    retained = [p for p in (ROOT / 'site').rglob('*') if p.is_file() and 'functions' not in p.parts and '.wrangler' not in p.parts]
    fresh = [p for p in (stage / 'assets').rglob('*') if p.is_file()]
    check(len(retained) + len(fresh) - 1 <= 20000 and max(p.stat().st_size for p in fresh) <= 25 * 1024 * 1024, 'Actual retained static-file/asset budget exceeded')
    result = {'ok': True, 'built_at': datetime.now(timezone.utc).isoformat(), 'release': release,
              'stage': str(stage), 'totals': dict(totals), 'views': {r: {'count': v['count'], 'depth': v['depth']} for r, v in views.items()},
              'hot_segments': len(hot.files), 'evidence_segments': len(evidence.files), 'evidence_pages': pages.pages,
              'largest_full_record': largest, 'largest_head': largest_head, 'largest_evidence_page_bytes': pages.largest_inflated,
              'new_static_files': len(fresh), 'total_static_files_including_retained': len(retained) + len(fresh) - 1,
              'maximum_new_asset_bytes': max(p.stat().st_size for p in fresh), 'new_static_bytes': sum(p.stat().st_size for p in fresh),
              'manifest_sha256': sha(target / 'manifest.json'), 'catalog_sha256': sha(WORK / 'private-catalog/catalog.sqlite3'),
              'key_role_index': str(WORK / 'EXPECTED_KEY_ROLES.jsonl.gz'), 'code': code,
              'canonical_site_changed': False, 'deployed': False, 'fifty_million_achieved': False}
    save(WORK / 'BUILD_RECEIPT.json', result)
    report('build_complete', **result)

def main():
    check(Path(sys.executable).resolve() == Path('C:/Users/bhara/.cache/codex-runtimes/codex-primary-runtime/dependencies/python/python.exe').resolve(), 'Bundled Python required')
    kernel = ctypes.WinDLL('kernel32', use_last_error=True)
    kernel.CreateMutexW.restype = ctypes.c_void_p
    kernel.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
    handle = kernel.CreateMutexW(None, False, 'Local\\NamesDoneRightPublicV5Writer')
    check(handle, 'Unable to create writer OS mutex')
    kernel.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
    check(kernel.WaitForSingleObject(handle, 0) == 0, 'Another V5 primary writer owns the OS lease')
    try:
        check(shutil.disk_usage(ROOT).free >= 96 * 1024**3, 'Insufficient bounded staging disk headroom')
        save(WORK / 'RUN_IDENTITY.json', {'pid': os.getpid(), 'started_at': datetime.now(timezone.utc).isoformat(), 'command': str(Path(__file__)), 'mutex': 'Local\\NamesDoneRightPublicV5Writer', 'writer_sha256': sha(__file__), 'disk_free_bytes': shutil.disk_usage(ROOT).free})
        frozen = freeze()
        closed = catalog(frozen)
        build(closed)
    finally:
        kernel.ReleaseMutex.argtypes = [ctypes.c_void_p]; kernel.ReleaseMutex(handle)
        kernel.CloseHandle.argtypes = [ctypes.c_void_p]; kernel.CloseHandle(handle)

if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        save(WORK / 'FAILED.json', {'at': datetime.now(timezone.utc).isoformat(), 'type': type(exc).__name__, 'error': str(exc), 'writer_sha256': sha(__file__)})
        raise
