"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildAddressIndex = buildAddressIndex;
exports.getAddressTransactions = getAddressTransactions;
exports.summarizeAddressActivity = summarizeAddressActivity;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
function normalizeAddr(a) {
    return a.toLowerCase();
}
function leafToRows(batchId, leaf) {
    const txHash = String(leaf.txHash || '');
    const from = String(leaf.from || '');
    const to = String(leaf.to || '');
    const base = {
        txHash,
        batchId,
        valueWei: String(leaf.onChainValueWei ?? leaf.value ?? leaf.nativeValueWei ?? '0'),
        valueUsd: leaf.valueUsd != null ? String(leaf.valueUsd) : undefined,
        nativeValueUsd: leaf.nativeValueUsd != null ? String(leaf.nativeValueUsd) : undefined,
        totalTransfersUsd: leaf.totalTransfersUsd != null ? String(leaf.totalTransfersUsd) : undefined,
        blockNumber: Number(leaf.blockNumber ?? 0),
        blockTimestamp: Number(leaf.blockTimestamp ?? 0),
        logCount: leaf.logCount != null ? Number(leaf.logCount) : undefined,
        receiptHash: leaf.receiptHash != null ? String(leaf.receiptHash) : undefined,
        success: Boolean(leaf.success),
        transfers: Array.isArray(leaf.transfers)
            ? leaf.transfers
            : undefined,
    };
    const rows = [];
    if (/^0x[a-fA-F0-9]{40}$/.test(from)) {
        rows.push({ ...base, role: 'from', counterparty: to });
    }
    if (/^0x[a-fA-F0-9]{40}$/.test(to)) {
        rows.push({ ...base, role: 'to', counterparty: from });
    }
    return rows;
}
function buildAddressIndex(batchPayloadDir) {
    const byAddress = {};
    let batchCount = 0;
    let txCount = 0;
    if (!fs.existsSync(batchPayloadDir)) {
        return { builtAt: new Date().toISOString(), batchCount: 0, txCount: 0, byAddress };
    }
    const files = fs
        .readdirSync(batchPayloadDir)
        .filter((f) => /^batch-\d+\.json$/.test(f))
        .sort((a, b) => {
        const na = parseInt(a.replace(/\D/g, ''), 10);
        const nb = parseInt(b.replace(/\D/g, ''), 10);
        return na - nb;
    });
    for (const file of files) {
        const batchId = file.replace('batch-', '').replace('.json', '');
        const raw = JSON.parse(fs.readFileSync(path.join(batchPayloadDir, file), 'utf8'));
        if (!raw.leaves?.length)
            continue;
        batchCount++;
        for (const leaf of raw.leaves) {
            txCount++;
            for (const row of leafToRows(batchId, leaf)) {
                const key = normalizeAddr(row.role === 'from' ? String(leaf.from) : String(leaf.to));
                if (!byAddress[key])
                    byAddress[key] = [];
                byAddress[key].push(row);
            }
        }
    }
    for (const key of Object.keys(byAddress)) {
        byAddress[key].sort((a, b) => b.blockNumber - a.blockNumber || b.batchId.localeCompare(a.batchId));
    }
    return {
        builtAt: new Date().toISOString(),
        batchCount,
        txCount,
        byAddress,
    };
}
function getAddressTransactions(index, address, limit = 50, offset = 0) {
    const key = normalizeAddr(address);
    const all = index.byAddress[key] ?? [];
    return {
        total: all.length,
        items: all.slice(offset, offset + limit),
    };
}
function summarizeAddressActivity(rows) {
    let totalWei = 0n;
    let totalUsd = 0;
    const seen = new Set();
    for (const row of rows) {
        if (seen.has(row.txHash))
            continue;
        seen.add(row.txHash);
        try {
            totalWei += BigInt(row.valueWei);
        }
        catch {
            /* skip */
        }
        const usd = Number(row.totalTransfersUsd ?? row.valueUsd ?? '0');
        if (Number.isFinite(usd))
            totalUsd += usd;
    }
    return {
        txCount: seen.size,
        totalValueWei: totalWei.toString(),
        totalUsd: totalUsd.toFixed(6),
    };
}
