"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractFinMessages = extractFinMessages;
exports.startSwiftFinTcpServer = startSwiftFinTcpServer;
const net_1 = __importDefault(require("net"));
const inboundParser_1 = require("../parsers/inboundParser");
/** Extract FIN messages from a TCP buffer (brace blocks or $...$ framed). */
function extractFinMessages(buffer) {
    const messages = [];
    let rest = buffer;
    while (rest.length > 0) {
        const dollarStart = rest.indexOf('$');
        const braceStart = rest.indexOf('{1:');
        if (braceStart >= 0 && (dollarStart < 0 || braceStart < dollarStart)) {
            const end = rest.indexOf('-}', braceStart);
            if (end < 0)
                break;
            messages.push(rest.slice(braceStart, end + 2));
            rest = rest.slice(end + 2);
            continue;
        }
        if (dollarStart >= 0) {
            const end = rest.indexOf('$', dollarStart + 1);
            if (end < 0)
                break;
            messages.push(rest.slice(dollarStart + 1, end));
            rest = rest.slice(end + 1);
            continue;
        }
        break;
    }
    return { messages, remainder: rest };
}
function startSwiftFinTcpServer(options) {
    const buffers = new Map();
    const server = net_1.default.createServer((socket) => {
        const key = `${socket.remoteAddress ?? 'unknown'}:${socket.remotePort ?? 0}`;
        buffers.set(key, '');
        socket.on('data', (chunk) => {
            const prev = buffers.get(key) ?? '';
            const combined = prev + chunk.toString('utf8');
            const { messages, remainder } = extractFinMessages(combined);
            buffers.set(key, remainder);
            for (const payload of messages) {
                if (!payload.trim())
                    continue;
                options.onMessage({
                    source: `tcp:${key}:${Date.now()}`,
                    format: (0, inboundParser_1.detectInboundFormat)(payload),
                    payload,
                    metadata: { remote: key },
                });
            }
        });
        socket.on('close', () => buffers.delete(key));
        socket.on('error', () => buffers.delete(key));
    });
    server.listen(options.port, options.host);
    return server;
}
//# sourceMappingURL=swiftFinTcpAdapter.js.map