/**
 * P2P 核心管理器
 */
import { p2pStore } from './p2p-store-memory.js';
import { p2pIdentity } from './p2p-identity.js';
import { p2pConnection } from './p2p-connection.js';
import { p2pMessages } from './p2p-messages.js';
export class P2PManager {
    identity = p2pIdentity;
    connection = p2pConnection;
    messages = p2pMessages;
    // 初始化
    async init() {
        const identity = await this.identity.init();
        this.messages.startListening();
        return identity;
    }
    // 连接到节点
    async connect(input, onProgress) {
        return this.connection.connect(input, onProgress);
    }
    // 断开连接
    async disconnect(nodeId) {
        return this.connection.disconnect(nodeId);
    }
    // 发送消息
    async sendMessage(content, targetNodeId) {
        return this.messages.send(content, targetNodeId);
    }
    // 获取连接历史
    async getHistory() {
        return p2pStore.getHistory();
    }
    // 更新历史条目
    async updateHistory(id, updates) {
        return p2pStore.updateHistory(id, updates);
    }
    // 删除历史条目
    async deleteHistory(id) {
        return p2pStore.deleteHistory(id);
    }
    // 获取收到的消息
    async getMessages() {
        return this.messages.getReceivedMessages();
    }
    // 监听消息
    onMessage(handler) {
        this.messages.onMessage(handler);
    }
    // 获取未读数
    getUnreadCount() {
        return this.messages.getUnreadCount();
    }
    // 获取已连接节点
    getConnectedPeers() {
        return this.connection.getConnectedPeers();
    }
    // 获取节点数量
    getPeerCount() {
        return this.connection.getPeerCount();
    }
    // 获取离线队列
    async getOfflineQueue() {
        return this.messages.getOfflineQueue();
    }
    // 获取离线消息数量
    async getOfflineQueueCount() {
        return p2pStore.getQueueCount();
    }
    // 销毁
    destroy() {
        this.connection.destroy();
        this.messages.destroy();
    }
    // 获取持久连接列表
    async getPersistentConnections() {
        return this.connection.getPersistentConnections();
    }
    // 更新连接状态
    async updateConnectionStatus(id, status, channelId) {
        await fetch('/api/p2p/connection-status', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id, status, channelId })
        });
    }
    // 切换连接状态
    async toggleConnection(connection, enable) {
        return this.connection.toggleConnection(connection, enable);
    }
    // CID 解析
    async resolveFromCID(cid) {
        return this.connection.resolveFromCID(cid);
    }
    // 连接并创建对话通道
    async connectAndCreateChannel(input, onProgress) {
        return this.connection.connectAndCreateChannel(input, onProgress);
    }
}
// 全局单例
export const p2pManager = new P2PManager();
// 挂载到全局
if (typeof window !== 'undefined') {
    window.p2pManager = p2pManager;
}
console.log('[P2P Manager] 已初始化');
