import { irohTransport } from './iroh-transport.js';
export class IrohIntegration {
    config;
    irohNodeId = null;
    registration = null;
    messageHandlers = new Map();
    discoveredPeers = new Map();
    refreshTimer = null;
    connectedPeers = new Set();
    constructor(config) {
        this.config = {
            refreshIntervalMs: 5 * 60 * 1000,
            discoveryIntervalMs: 30 * 1000,
            ...config,
        };
    }
    async start() {
        try {
            console.log('[IrohIntegration] Starting iroh transport...');
            const node = await irohTransport.start();
            this.irohNodeId = node.nodeId;
            console.log(`[IrohIntegration] Node ID: ${this.irohNodeId}`);
            irohTransport.onMessage('*', (msg) => {
                this.dispatchMessage(msg);
            });
            await this.registerWithDIAP();
            this.startRefreshLoop();
            console.log('[IrohIntegration] Started successfully');
            return this.irohNodeId;
        }
        catch (e) {
            console.error('[IrohIntegration] Failed to start:', e);
            return null;
        }
    }
    async registerWithDIAP() {
        if (!this.irohNodeId) {
            console.warn('[IrohIntegration] No iroh node ID');
            return;
        }
        try {
            const services = [
                { serviceType: 'iroh', endpoint: this.irohNodeId },
                { serviceType: 'iroh-quic', endpoint: `iroh://${this.irohNodeId}` },
            ];
            const agentInfo = {
                name: this.config.agentName,
                services: services,
                description: this.config.agentDescription || 'Bolloon agent with iroh P2P',
                tags: this.config.agentTags || ['bolloon', 'iroh', 'p2p'],
            };
            this.registration = await this.config.agentAuthManager.registerAgent(agentInfo, this.config.keyPair, this.irohNodeId);
            console.log(`[IrohIntegration] DIAP registered: DID=${this.registration.did.substring(0, 20)}...`);
        }
        catch (e) {
            console.error('[IrohIntegration] DIAP registration failed:', e);
        }
    }
    startRefreshLoop() {
        this.refreshTimer = setInterval(async () => {
            console.log('[IrohIntegration] Refreshing DIAP registration...');
            await this.registerWithDIAP();
        }, this.config.refreshIntervalMs);
    }
    dispatchMessage(msg) {
        const handler = this.messageHandlers.get(msg.type);
        if (handler) {
            handler(msg, msg.from);
        }
    }
    onMessage(type, handler) {
        this.messageHandlers.set(type, handler);
    }
    async sendTo(targetNodeId, type, payload) {
        return irohTransport.sendMessage(targetNodeId, type, payload);
    }
    async requestFrom(targetNodeId, type, payload) {
        return irohTransport.requestResponse(targetNodeId, type, payload);
    }
    getNodeId() {
        return this.irohNodeId;
    }
    getRegistration() {
        return this.registration;
    }
    getConnectedPeers() {
        return Array.from(this.connectedPeers);
    }
    async shutdown() {
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
            this.refreshTimer = null;
        }
        await irohTransport.shutdown();
        console.log('[IrohIntegration] Shut down');
    }
}
let integrationInstance = null;
export async function initIrohIntegration(config) {
    if (integrationInstance) {
        console.log('[IrohIntegration] Already initialized');
        return integrationInstance;
    }
    integrationInstance = new IrohIntegration(config);
    await integrationInstance.start();
    return integrationInstance;
}
export function getIrohIntegration() {
    return integrationInstance;
}
