// ZCLAW API 层 - 供 Tauri 前端调用的接口
import type { ZClawApp } from '../app';
import { createLogger } from '../utils/logger';

const log = createLogger('API');

export interface APIResponse<T = any> {
  success: boolean;
  data?: T;
  error?: string;
}

// API 处理器集合 - 供 Tauri Commands 调用
export class ZClawAPI {
  constructor(private app: ZClawApp) {}

  // === 聊天 ===
  async sendMessage(userId: string, content: string): Promise<APIResponse<{ reply: string }>> {
    try {
      const reply = await this.app.handleUserMessage(userId, content);
      return { success: true, data: { reply } };
    } catch (error: any) {
      log.error(`sendMessage error: ${error.message}`);
      return { success: false, error: error.message };
    }
  }

  // === 任务 ===
  async submitTask(userId: string, payload: any): Promise<APIResponse<{ taskId: string }>> {
    try {
      const engine = this.app.getRemoteExecution();
      const taskId = await engine.submitTask({
        id: '',
        userId,
        deviceId: 'local',
        channel: 'desktop',
        type: 'immediate',
        priority: 'normal',
        payload,
        status: 'pending',
        createdAt: new Date(),
      });
      return { success: true, data: { taskId } };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  async getTaskStatus(taskId: string): Promise<APIResponse<{ status: string }>> {
    try {
      const engine = this.app.getRemoteExecution();
      const status = await engine.getStatus(taskId);
      return { success: true, data: { status } };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  async getTaskStats(): Promise<APIResponse> {
    try {
      const stats = this.app.getRemoteExecution().getStats();
      return { success: true, data: stats };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  // === 多 Agent ===
  async executeGoal(userId: string, goal: string): Promise<APIResponse> {
    try {
      const result = await this.app.getAgentOrchestrator().executeGoal(goal);
      return { success: true, data: result };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  // === 记忆 ===
  async getUserProfile(userId: string): Promise<APIResponse> {
    try {
      const profile = await this.app.getMemory().getProfile(userId);
      return { success: true, data: profile || null };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  async getMemoryEvents(userId: string, query: string = '', limit: number = 20): Promise<APIResponse> {
    try {
      const events = await this.app.getMemory().recall(userId, query, limit);
      return { success: true, data: events };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  // === 定时任务 ===
  async listScheduledTasks(userId: string): Promise<APIResponse> {
    try {
      const tasks = await this.app.getProactive().listTasks(userId);
      return { success: true, data: tasks };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  async scheduleTask(userId: string, schedule: any, taskConfig: any): Promise<APIResponse> {
    try {
      await this.app.getProactive().scheduleTask({
        id: '',
        userId,
        channel: 'desktop',
        schedule,
        task: taskConfig,
        status: 'active',
      });
      return { success: true };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  // === 系统状态 ===
  async getSystemStatus(): Promise<APIResponse> {
    try {
      const taskStats = this.app.getRemoteExecution().getStats();
      const agents = this.app.getAgentOrchestrator().getAgents().map(a => a.getInfo());
      const activePlans = this.app.getAgentOrchestrator().getActivePlans();
      const connectedIMs = this.app.getIMGateway().getConnectedAdapters();

      return {
        success: true,
        data: {
          taskStats,
          activeAgents: agents.length,
          activePlans: activePlans.length,
          connectedIMs,
        },
      };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }
}
