// ZCLAW 主应用类 - 统一协调所有系统
import { loadConfig, getConfig } from './config';
import { initDatabase, closeDatabase } from './db';
import { AIManager } from './core/ai/manager';
import { AgentOrchestrator } from './core/multi-agent/orchestrator';
import { RemoteExecutionEngine } from './core/remote-execution/engine';
import { TaskOrchestrator } from './core/task-orchestration/orchestrator';
import { PersistentMemorySystem } from './core/memory/memory';
import { ProactiveServiceSystem } from './core/proactive/proactive';
import { IMGateway } from './im/gateway';
import { FeishuAdapter } from './im/adapters/feishu';
import { createLogger, setLogLevel } from './utils/logger';

const log = createLogger('ZCLAW');

export class ZClawApp {
  private ai!: AIManager;
  private agentOrchestrator!: AgentOrchestrator;
  private remoteExecution!: RemoteExecutionEngine;
  private taskOrchestrator!: TaskOrchestrator;
  private memory!: PersistentMemorySystem;
  private proactive!: ProactiveServiceSystem;
  private imGateway!: IMGateway;

  async start(): Promise<void> {
    log.info('========================================');
    log.info('  ZCLAW - AI Agent Platform');
    log.info('  Version: 0.1.0');
    log.info('========================================');

    // 1. 加载配置
    const config = loadConfig();
    setLogLevel(config.log.level);
    log.info('Configuration loaded');

    // 2. 初始化数据库
    initDatabase(config.db.path);
    log.info('Database initialized');

    // 3. 初始化 AI 管理器
    this.ai = new AIManager();
    log.info('AI Manager initialized');

    // 4. 初始化核心系统
    this.remoteExecution = new RemoteExecutionEngine();
    this.taskOrchestrator = new TaskOrchestrator();
    this.memory = new PersistentMemorySystem();
    this.proactive = new ProactiveServiceSystem();
    log.info('Core systems initialized');

    // 5. 初始化多 Agent 协作系统
    this.agentOrchestrator = new AgentOrchestrator(this.ai);
    log.info('Agent Orchestrator initialized');

    // 6. 初始化 IM 网关
    this.imGateway = new IMGateway();
    this.setupIMAdapters(config);
    this.setupMessageRouting();
    log.info('IM Gateway initialized');

    // 7. 连接 IM
    await this.imGateway.connectAll();

    log.info('ZCLAW started successfully! 🦞');
    log.info(`Server: ${config.server.host}:${config.server.port}`);
    log.info(`AI Provider: ${config.ai.provider} (${config.ai.defaultModel})`);
    log.info(`Connected IMs: ${this.imGateway.getConnectedAdapters().join(', ') || 'none'}`);
  }

  private setupIMAdapters(config: ReturnType<typeof getConfig>): void {
    // 飞书
    if (config.im.feishu.enabled || config.im.feishu.appId) {
      const feishu = new FeishuAdapter(config.im.feishu.appId, config.im.feishu.appSecret);
      this.imGateway.registerAdapter(feishu);
    }

    // TODO: 其他 IM 适配器 (Telegram, QQ, WeChat)
  }

  private setupMessageRouting(): void {
    this.imGateway.onMessage(async (message) => {
      log.info(`Processing message from ${message.channelType}/${message.userId}: ${message.content.slice(0, 80)}`);

      try {
        // 记忆：记录用户消息
        await this.memory.remember(message.userId, {
          id: message.id,
          userId: message.userId,
          type: 'im_message',
          content: { text: message.content, channel: message.channelType },
          timestamp: new Date(),
        });

        // 判断消息类型并路由
        const response = await this.handleUserMessage(message.userId, message.content);

        // 回复
        await this.imGateway.send({
          channelType: message.channelType,
          channelId: message.channelId,
          userId: message.userId,
          content: response,
          contentType: 'text',
        });

      } catch (error: any) {
        log.error(`Message processing error: ${error.message}`);
        await this.imGateway.send({
          channelType: message.channelType,
          channelId: message.channelId,
          content: `处理消息时出错: ${error.message}`,
          contentType: 'text',
        });
      }
    });
  }

  async handleUserMessage(userId: string, content: string): Promise<string> {
    // 获取用户记忆上下文
    const recentMemories = await this.memory.recall(userId, content, 5);
    const context: Record<string, any> = {};
    if (recentMemories.length > 0) {
      context.recentHistory = recentMemories.map(m => m.content);
    }

    // 判断是否需要多步骤编排
    const isComplex = this.isComplexTask(content);

    if (isComplex) {
      // 复杂任务 -> 多 Agent 协作
      log.info(`Complex task detected, starting multi-agent execution`);
      const result = await this.agentOrchestrator.executeGoal(content, context);
      return result.success
        ? result.data?.report || '任务已完成'
        : `任务执行失败: ${result.error}`;
    } else {
      // 简单对话 -> 直接 AI 回复
      const profile = await this.memory.getProfile(userId);
      const systemPrompt = `你是 ZCLAW，一个智能 AI 助手 🦞。你友善、专业、高效。
${profile ? `用户偏好: ${JSON.stringify(profile.preferences)}` : ''}
请用中文简洁回复。`;

      return await this.ai.ask(content, systemPrompt);
    }
  }

  private isComplexTask(content: string): boolean {
    const complexIndicators = [
      '帮我做', '市场调研', '写报告', '分析',
      '自动化', '批量', '多步骤', '流程',
      '调研', '搜索并整理', '对比', '综合',
      '项目管理', '代码生成', '部署',
    ];
    return complexIndicators.some(indicator => content.includes(indicator));
  }

  // 公开接口：供 Tauri 前端调用
  getAI(): AIManager { return this.ai; }
  getAgentOrchestrator(): AgentOrchestrator { return this.agentOrchestrator; }
  getRemoteExecution(): RemoteExecutionEngine { return this.remoteExecution; }
  getTaskOrchestrator(): TaskOrchestrator { return this.taskOrchestrator; }
  getMemory(): PersistentMemorySystem { return this.memory; }
  getProactive(): ProactiveServiceSystem { return this.proactive; }
  getIMGateway(): IMGateway { return this.imGateway; }

  async shutdown(): Promise<void> {
    log.info('Shutting down ZCLAW...');
    await this.agentOrchestrator.shutdown();
    await this.imGateway.disconnectAll();
    closeDatabase();
    log.info('ZCLAW shutdown complete');
  }
}
