"""Consume closed witness exports once; close only the exact frozen V4 catalog."""
from datetime import datetime,timezone
import hashlib,json,sqlite3
from pathlib import Path
from catalog_v4 import Catalog
from freeze_inputs import ROOT,WORK,SOURCE,read,rows,sha,write,require,pin
from source_common import encoded

def witness_units():
    frozen=read(WORK/'INPUT_MANIFEST.json');specs=frozen['inputs'];units=[];proofs=[]
    directory=SOURCE/'datacite/checkpoint10-uniform-04-07-v1'
    require(sha(directory/'EXPORT_RECEIPT.json')=='9e9cb89481f8a58ba42fecc8b92a20d0a5518f536444e34384fc92f732c96cf0','Committed04–07 closure differs')
    exported=read(directory/'EXPORT_RECEIPT.json');proofs.append(pin(directory/'EXPORT_RECEIPT.json'))
    for name,meta in exported['artifacts'].items():
        actual=pin(directory/name,meta['sha256']);require(actual['bytes']==meta['bytes'],'Committed export artifact bytes differ');proofs.append(actual)
    for number in range(4,8):
        receipt=read(directory/f'COHORT{number}_ELIGIBLE_EVENTS_RECEIPT.json')
        chosen=[s for s in specs if s['id'].startswith(f'datacite-continuation-cohort-{number:04d}:')]
        require(receipt['ok'] and receipt['events']==sum(sum(s['expected_roles'].values()) for s in chosen),'Closed cohort export scope count differs')
        path=directory/f'COHORT{number}_ELIGIBLE_EVENTS.jsonl.gz'
        require(sha(path)==receipt['artifact']['sha256'],'Committed cohort export changed')
        units.append({'id':f'datacite-cohort-{number:04d}-verified-export','path':path.relative_to(ROOT).as_posix(),'sha256':receipt['artifact']['sha256'],'scopes':chosen})
    for spec in specs:
        if spec['kind']=='datacite_native':
            if int(spec['id'].split(':')[0][-4:])<8:continue
            p=WORK/'native-exports'/(spec['id'].replace(':','--')+'.jsonl.gz');rp=p.with_name(p.name+'.receipt.json');r=read(rp)
            require(r['ok'] and r['source_scope_id']==spec['id'] and r['input_manifest_sha256']==sha(WORK/'INPUT_MANIFEST.json') and
                r['admitted_rows']==sum(spec['expected_roles'].values()) and r['native_names_sha256']==spec['sha256'] and
                r['native_receipt_sha256']==spec['receipt_sha256'] and r['historical_complete_source_support_quarantine_proof_sha256']==spec['support_proof_sha256'] and
                sha(p)==r['export_sha256'],'Native08/09 witness closure differs')
            proofs.append(pin(rp));units.append({'id':spec['id'],'path':p.relative_to(ROOT).as_posix(),'sha256':r['export_sha256'],'scopes':[spec]})
        else:units.append({'id':spec['id'],'path':spec['path'],'sha256':spec['sha256'],'scopes':[spec]})
    result={'schema':'ndr-public-v4-witness-inputs/1','ok':True,'input_manifest_sha256':sha(WORK/'INPUT_MANIFEST.json'),'units':units,'proofs':proofs,
        'no_mutable_or_uncommitted_inputs':True,'no_source_parser_or_archive_replay':True}
    path=WORK/'WITNESS_INPUT_MANIFEST.json'
    if path.exists():require(read(path)==result,'Closed witness input manifest changed')
    else:write(path,result)
    return units

def main():
    require(not (WORK/'CATALOG_CLOSED_RECEIPT.json').exists(),'Catalog closure already exists')
    units=witness_units();c=Catalog(WORK/'private-catalog/catalog.sqlite3')
    try:
        c.baseline()
        for rank,unit in enumerate(units,100):
            count=c.add(ROOT/unit['path'],unit['id'],unit['sha256'],{s['id']:s for s in unit['scopes']},rank)
            print(json.dumps({'stage':'source_unit_closed','id':unit['id'],'rows':count}),flush=True)
        expected=read(WORK/'EXPECTED_SCOPE.json');wanted=rows(WORK/'EXPECTED_KEY_ROLES.jsonl.gz');matched=0
        for key, in c.db.execute('SELECT key FROM names ORDER BY key'):
            role=[r[0] for r in c.db.execute('SELECT role FROM roles WHERE key=? ORDER BY role',(key,))]
            require(next(wanted,None)=={'key':key,'roles':role},'Catalog role/key union differs from independent exact census');matched+=1
        require(next(wanted,None) is None and matched==expected['expected_public_directory_keys'],'Catalog key total differs')
        c.db.execute('CREATE INDEX IF NOT EXISTS events_by_key ON events(key,seq)');c.db.commit();c.db.execute('PRAGMA wal_checkpoint(TRUNCATE)')
        closed_units=[list(r) for r in c.db.execute('SELECT id,sha256,rows FROM units ORDER BY id')]
        require(len(closed_units)==len(units)+1,'Catalog contains an unapproved source unit')
        event_count=c.db.execute('SELECT count(*) FROM events').fetchone()[0]
    finally:c.close()
    result={'schema':'ndr-public-v4-closed-catalog/1','ok':True,'closed_at':datetime.now(timezone.utc).isoformat(),
        'input_manifest_sha256':sha(WORK/'INPUT_MANIFEST.json'),'witness_manifest_sha256':sha(WORK/'WITNESS_INPUT_MANIFEST.json'),
        'expected_scope_sha256':sha(WORK/'EXPECTED_SCOPE.json'),'keys':matched,'all_key_roles_exact_to_independent_census':True,'units':closed_units,
        'stored_source_attestations':event_count,'catalog_sha256':sha(WORK/'private-catalog/catalog.sqlite3'),'writer_sha256':sha(__file__),
        'canonical_site_unchanged':True,'ORCID05_DataCite10_all_future_excluded':True}
    write(WORK/'CATALOG_CLOSED_RECEIPT.json',result);print(json.dumps(result),flush=True)

if __name__=='__main__':main()
