#!/usr/bin/env python3
"""Reproduce the frozen DN address-role audit; standard-library Python only.

Run: python reproduce.py
No network, wallet, keys, inferred entity labels or human estimates are used.
Input data is decoded public API JSON saved on 2026-11-29. See README.md.
"""
import csv
import hashlib
import json
import re
import sqlite3
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent
DATA = ROOT / 'data'
CHAIN_ID = 1
FIRST, LAST = 20_000_000, 20_000_020
POOL = '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640'
TOPIC = '0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67'

def require(condition, message):
    if not condition:
        raise ValueError(message)

def load(path):
    return json.loads(path.read_text())

def hex_value(value, size, label):
    require(isinstance(value, str) and re.fullmatch('0x[0-9a-fA-F]{%d}' % size, value), label + ': invalid hex length')
    return value.lower()

def normalise(raw, transactions, headers):
    require(raw.get('status') == '1' and isinstance(raw.get('result'), list), 'Log query did not succeed')
    require(len(raw['result']) < 1000, 'Log cap reached: split the range; do not assume completeness')
    head = {}
    for h in headers:
        require(h['chain'] == 'ETH.main', 'Wrong header chain')
        require(h['height'] not in head, 'Duplicate header height')
        hex_value('0x' + h['hash'], 64, 'Block hash')
        head[h['height']] = h
    require(FIRST in head and LAST in head, 'Missing boundary header')
    seen = {}
    duplicate_rows = 0
    for row in raw['result']:
        block = int(row['blockNumber'], 16)
        require(FIRST <= block <= LAST, 'Event outside declared inclusive block range')
        require(row['address'].lower() == POOL, 'Wrong emitting contract')
        topics = [x.lower() for x in row['topics'] if x is not None]
        require(len(topics) == 3 and topics[0] == TOPIC, 'Wrong event topic or indexed field count')
        for topic in topics:
            hex_value(topic, 64, 'Topic')
        require(topics[1][2:26] == '0' * 24 and topics[2][2:26] == '0' * 24, 'Non-address indexed topic')
        tx_hash = hex_value(row['transactionHash'], 64, 'Transaction hash')
        require(block in head, 'Missing event-bearing block header')
        block_hash = '0x' + head[block]['hash'].lower()
        timestamp = int(row['timeStamp'], 16)
        header_time = int(datetime.fromisoformat(head[block]['time'].replace('Z', '+00:00')).timestamp())
        require(header_time == timestamp, 'Header/log timestamp mismatch')
        tx = transactions.get(tx_hash)
        require(tx and tx.get('status') == '1', 'Missing or unsuccessful transaction lookup')
        t = tx['result']
        require(t['hash'].lower() == tx_hash and int(t['blockNumber']) == block, 'Transaction join mismatch')
        require(int(t['timeStamp']) == timestamp and t['success'] is True, 'Transaction status/time mismatch')
        require(t.get('next_page_params') is None, 'Transaction logs are paginated: fetch remaining pages')
        index = int(row['logIndex'], 16)
        matches = [x for x in t['logs'] if int(x['index']) == index]
        require(len(matches) == 1, 'Event log index is not unique in transaction response')
        match = matches[0]
        require(match['address'].lower() == POOL and match['data'].lower() == row['data'].lower(), 'Transaction/log payload mismatch')
        require([x.lower() for x in match['topics'] if x is not None] == topics, 'Transaction/log topics mismatch')
        item = {
            'chain_id': CHAIN_ID,
            'block_number': block,
            'block_hash': block_hash,
            'transaction_hash': tx_hash,
            'transaction_index': int(row['transactionIndex'], 16),
            'log_index': index,
            'timestamp': timestamp,
            'time_utc': datetime.fromtimestamp(timestamp, timezone.utc).isoformat().replace('+00:00', 'Z'),
            'emitting_contract': POOL,
            'event_topic': TOPIC,
            'origin': hex_value(t['from'], 40, 'Transaction origin'),
            'transaction_to': hex_value(t['to'], 40, 'Transaction destination'),
            'sender': '0x' + topics[1][-40:],
            'recipient': '0x' + topics[2][-40:]
        }
        key = (CHAIN_ID, block_hash, tx_hash, index)
        payload = (item, row['data'].lower())
        if key in seen:
            require(seen[key] == payload, 'Conflicting observations share one event key')
            duplicate_rows += 1
        else:
            seen[key] = payload
    return sorted([x[0] for x in seen.values()], key=lambda r: (r['block_number'], r['transaction_index'], r['log_index'])), duplicate_rows

def count_python(rows):
    origin = {r['origin'] for r in rows}
    sender = {r['sender'] for r in rows}
    recipient = {r['recipient'] for r in rows}
    return {
        'events': len(rows),
        'transactions': len({r['transaction_hash'] for r in rows}),
        'transaction_origins': len(origin),
        'transaction_destinations': len({r['transaction_to'] for r in rows}),
        'event_senders': len(sender),
        'event_recipients': len(recipient),
        'sender_recipient_overlap': len(sender & recipient),
        'sender_recipient_union': len(sender | recipient),
        'origin_sender_recipient_union': len(origin | sender | recipient),
        'rows_same_sender_recipient': sum(r['sender'] == r['recipient'] for r in rows),
        'rows_origin_differs_from_sender': sum(r['origin'] != r['sender'] for r in rows)
    }

def count_sql(rows):
    connection = sqlite3.connect(':memory:')
    connection.execute('CREATE TABLE swaps (tx TEXT, origin TEXT, destination TEXT, sender TEXT, recipient TEXT)')
    connection.executemany('INSERT INTO swaps VALUES (?,?,?,?,?)', [(r['transaction_hash'], r['origin'], r['transaction_to'], r['sender'], r['recipient']) for r in rows])
    queries = {
        'events': 'SELECT COUNT(*) FROM swaps',
        'transactions': 'SELECT COUNT(DISTINCT tx) FROM swaps',
        'transaction_origins': 'SELECT COUNT(DISTINCT origin) FROM swaps',
        'transaction_destinations': 'SELECT COUNT(DISTINCT destination) FROM swaps',
        'event_senders': 'SELECT COUNT(DISTINCT sender) FROM swaps',
        'event_recipients': 'SELECT COUNT(DISTINCT recipient) FROM swaps',
        'sender_recipient_overlap': 'SELECT COUNT(*) FROM (SELECT sender AS address FROM swaps INTERSECT SELECT recipient FROM swaps)',
        'sender_recipient_union': 'SELECT COUNT(*) FROM (SELECT sender AS address FROM swaps UNION SELECT recipient FROM swaps)',
        'origin_sender_recipient_union': 'SELECT COUNT(*) FROM (SELECT origin AS address FROM swaps UNION SELECT sender FROM swaps UNION SELECT recipient FROM swaps)',
        'rows_same_sender_recipient': 'SELECT COUNT(*) FROM swaps WHERE sender = recipient',
        'rows_origin_differs_from_sender': 'SELECT COUNT(*) FROM swaps WHERE origin <> sender'
    }
    result = {name: connection.execute(query).fetchone()[0] for name, query in queries.items()}
    connection.close()
    (ROOT / 'query.sql').write_text('-- Run against the five-column swaps table created in reproduce.py.\n' + '\n'.join('-- ' + name + '\n' + query + ';\n' for name, query in queries.items()))
    return result

def main():
    raw = load(DATA / 'pool-swap-logs.json')
    transactions = {p.stem.lower(): load(p) for p in (DATA / 'transactions').glob('*.json')}
    headers = load(DATA / 'block-headers.json')
    rows, duplicates = normalise(raw, transactions, headers)
    counts = count_python(rows)
    require(counts == count_sql(rows), 'Independent SQL and Python counts disagree')
    expected = {'events': 15, 'transactions': 15, 'transaction_origins': 14, 'transaction_destinations': 6, 'event_senders': 6, 'event_recipients': 9, 'sender_recipient_overlap': 4, 'sender_recipient_union': 11, 'origin_sender_recipient_union': 25, 'rows_same_sender_recipient': 7, 'rows_origin_differs_from_sender': 15}
    require(counts == expected and duplicates == 0, 'Frozen sample changed; review before updating published figures')
    (DATA / 'normalized-swaps.json').write_text(json.dumps(rows, indent=2) + '\n')
    with (DATA / 'normalized-swaps.csv').open('w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    summary = {
        'dataset': 'DN bounded Ethereum pool Swap address-role audit',
        'evidence_reviewed_at': '2026-11-29',
        'observation_type': 'Actual historical public events and transactions; not a scenario',
        'chain_id': CHAIN_ID, 'contract': POOL, 'event_topic': TOPIC,
        'first_block_inclusive': FIRST, 'last_block_inclusive': LAST,
        'scope_start_utc': '2024-06-01T22:36:47Z', 'scope_end_utc': '2024-06-01T22:40:47Z',
        'raw_rows': len(raw['result']), 'duplicate_rows': duplicates, 'counts': counts,
        'human_count': None, 'trader_entity_count': None,
        'independent_arithmetic': 'Python sets and SQLite DISTINCT / UNION / INTERSECT agree',
        'coverage': 'All 15 rows returned by one address/topic query over 21 blocks; below documented 1000-row cap. Every event cross-checked against its transaction response and separately retrieved block header. Provider indexing is not independently proven complete.',
        'excluded': ['Other contracts', 'Other events', 'Other chains and blocks', 'Failed transactions without retained Swap logs', 'Offchain customers', 'Internal calls not represented by the selected Swap event', 'Identity attribution', 'Any extrapolation to population or adoption'],
        'deduplication': 'chain_id + block_hash + transaction_hash + log_index; lowercase 20-byte addresses within chain 1; exact duplicate keys collapse, conflicting payloads fail',
        'header_limit': 'Only boundary and event-bearing block headers retained; no claim of a continuous parent-hash validation or transaction enumeration for every block'
    }
    (DATA / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
    raw_paths = [DATA / 'pool-swap-logs.json', DATA / 'block-headers.json'] + sorted((DATA / 'transactions').glob('*.json'))
    manifest = {'hash_algorithm': 'SHA-256', 'meaning': 'Checksums of the decoded JSON capture files, not original HTTP response bytes', 'files': [{'path': str(p.relative_to(ROOT)), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest(), 'bytes': p.stat().st_size} for p in raw_paths]}
    (DATA / 'capture-checksums.json').write_text(json.dumps(manifest, indent=2) + '\n')
    print(json.dumps({'counts': counts, 'duplicates': duplicates, 'python_sql_match': True}, indent=2))

if __name__ == '__main__':
    main()
