/**
 * 与其他模块集成示例
 *
 * 演示凭证管理器如何与现有的交易系统协作
 */

import { getGlobalCredentialManager, Platform, PacificaOrderType } from '../src/index';

// 模拟的其他模块接口
interface TradingEngine {
  executeOrder(signedOrder: string): Promise<void>;
}

interface AccountManager {
  getAccountBalance(accountId: string): Promise<number>;
}

class IntegratedTradingSystem {
  private credentialManager = getGlobalCredentialManager();

  async initialize() {
    const manager = await this.credentialManager;

    // 从环境变量或配置文件自动加载账户
    if (process.env.CREDENTIAL_CONFIG_PATH) {
      await manager.loadConfig(process.env.CREDENTIAL_CONFIG_PATH);
    }

    // 或者程序化添加账户
    if (process.env.PACIFICA_ACCOUNT && process.env.PACIFICA_PRIVATE_KEY) {
      await manager.addAccount({
        id: process.env.PACIFICA_ACCOUNT,
        platform: Platform.PACIFICA,
        credentials: {
          type: 'pacifica',
          privateKey: process.env.PACIFICA_PRIVATE_KEY
        }
      });
    }
  }

  async signPacificaOrder(accountId: string, orderData: any): Promise<string> {
    const manager = await this.credentialManager;

    // 序列化订单数据
    const orderMessage = this.serializeOrderData(orderData);
    const messageBytes = new TextEncoder().encode(orderMessage);

    // 使用凭证管理器签名
    const signResult = await manager.sign(accountId, messageBytes);

    if (!signResult.success) {
      throw new Error(`签名失败: ${signResult.error}`);
    }

    console.log(`✅ 订单签名成功，耗时: ${signResult.executionTime}ms`);
    return signResult.signature!;
  }

  async getSystemStats() {
    const manager = await this.credentialManager;
    const stats = await manager.getStats();

    return {
      totalAccounts: stats.totalAccounts,
      platformBreakdown: stats.accountsByPlatform,
      signingPerformance: {
        totalSignatures: stats.totalSignatures,
        successRate: `${(stats.successRate * 100).toFixed(1)}%`,
        averageTime: `${stats.averageSignatureTime.toFixed(2)}ms`
      },
      uptime: `${(stats.uptime / 1000).toFixed(1)}s`
    };
  }

  private serializeOrderData(orderData: any): string {
    // 实际项目中的订单序列化逻辑
    return JSON.stringify(orderData);
  }

  async cleanup() {
    // 全局管理器会处理资源清理
    // await GlobalCredentialManager.reset();
  }
}

// 使用示例
async function demonstrateIntegration() {
  console.log('🔗 凭证管理器集成示例');

  const tradingSystem = new IntegratedTradingSystem();

  try {
    // 1. 初始化系统
    await tradingSystem.initialize();
    console.log('✅ 交易系统初始化完成');

    // 2. 系统统计
    const stats = await tradingSystem.getSystemStats();
    console.log('📊 系统统计:', stats);

    // 3. 签名订单（模拟）
    if (process.env.PACIFICA_ACCOUNT) {
      const orderData = {
        symbol: 'BTC-USD',
        side: 'buy',
        size: '0.001',
        price: '65000',
        orderType: PacificaOrderType.LIMIT
      };

      const signature = await tradingSystem.signPacificaOrder(
        process.env.PACIFICA_ACCOUNT,
        orderData
      );

      console.log(`🔐 订单签名: ${signature.substring(0, 20)}...`);
    }

  } catch (error) {
    console.error('❌ 集成示例错误:', error);
  } finally {
    await tradingSystem.cleanup();
  }
}

// 模拟其他模块的使用方式
export class ExternalModule {
  // 其他模块可以这样使用凭证管理器
  async performSigning(accountId: string, data: string) {
    // 直接获取全局实例
    const credentialManager = await getGlobalCredentialManager();

    const message = new TextEncoder().encode(data);
    const result = await credentialManager.sign(accountId, message);

    return result;
  }

  async listAvailableAccounts() {
    const credentialManager = await getGlobalCredentialManager();
    return credentialManager.listAccounts();
  }
}

if (require.main === module) {
  demonstrateIntegration().catch(console.error);
}

export { IntegratedTradingSystem };