/**
 * [MOCK-012] 客户端管理模块DataSource
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在USE_MOCK=true时启用 */

import { lightweightClientService } from './lightweightClientService';

export interface Client {
  id: string;
  name: string;
  host: string;
  port: number;
  status: 'connected' | 'disconnected' | 'error';
  lastSeen: Date;
  groupId?: string;
  tags?: string[];
  description?: string;
  performance?: {
    cpu: number;
    memory: number;
    network: number;
  };
  history?: {
    timestamp: Date;
    status: string;
    message: string;
  }[];
}

export interface ClientGroup {
  id: string;
  name: string;
  description: string;
  clientIds: string[];
  color: string;
}

export interface ClientDataSource {
  fetchClients(): Promise<Client[]>;
  fetchGroups(): Promise<ClientGroup[]>;
  connectClient(host: string, port: number, name: string, groupId?: string, description?: string): Promise<string>;
  disconnectClient(clientId: string): Promise<void>;
  updateClient(clientId: string, client: Partial<Client>): Promise<Client | null>;
  createGroup(group: Omit<ClientGroup, 'id' | 'clientIds'>): Promise<ClientGroup>;
  updateGroup(groupId: string, group: Partial<ClientGroup>): Promise<ClientGroup | null>;
  deleteGroup(groupId: string): Promise<boolean>;
  addClientToGroup(clientId: string, groupId: string): Promise<boolean>;
  removeClientFromGroup(clientId: string, groupId: string): Promise<boolean>;
  getClientDetails(clientId: string): Promise<Client | null>;
  getClientPerformance(clientId: string): Promise<{ cpu: number; memory: number; network: number }>;
}

export class ClientDataSourceImpl implements ClientDataSource {
  private groups: ClientGroup[] = [
    { id: 'g1', name: 'Production', description: 'Production clients', clientIds: ['localhost:8080'], color: '#1890ff' },
    { id: 'g2', name: 'Staging', description: 'Staging clients', clientIds: [], color: '#52c41a' },
    { id: 'g3', name: 'Development', description: 'Development clients', clientIds: [], color: '#faad14' },
  ];

  async fetchClients(): Promise<Client[]> {
    try {
      const clientList = lightweightClientService.getClientList();
      return clientList.map(client => ({
        ...client,
        lastSeen: new Date(client.lastSeen),
        performance: {
          cpu: Math.random() * 100,
          memory: Math.random() * 100,
          network: Math.random() * 100,
        },
        history: [
          { timestamp: new Date(Date.now() - 3600000), status: 'connected', message: 'Client connected' },
          { timestamp: new Date(Date.now() - 1800000), status: 'connected', message: 'Command executed successfully' },
          { timestamp: new Date(Date.now() - 900000), status: 'connected', message: 'Heartbeat received' },
        ],
      }));
    } catch (error) {
      console.error('Failed to fetch clients:', error);
      return [];
    }
  }

  async fetchGroups(): Promise<ClientGroup[]> {
    return this.groups;
  }

  async connectClient(host: string, port: number, name: string, groupId?: string, description?: string): Promise<string> {
    try {
      const clientId = await lightweightClientService.connectToClient(host, port);
      
      // 如果指定了组，将客户端添加到组中
      if (groupId) {
        await this.addClientToGroup(clientId, groupId);
      }
      
      return clientId;
    } catch (error) {
      console.error('Failed to connect client:', error);
      throw error;
    }
  }

  async disconnectClient(clientId: string): Promise<void> {
    try {
      lightweightClientService.disconnect(clientId);
      
      // 从所有组中移除客户端
      this.groups.forEach(group => {
        group.clientIds = group.clientIds.filter(id => id !== clientId);
      });
    } catch (error) {
      console.error('Failed to disconnect client:', error);
      throw error;
    }
  }

  async updateClient(clientId: string, client: Partial<Client>): Promise<Client | null> {
    try {
      const clients = await this.fetchClients();
      const existingClient = clients.find(c => c.id === clientId);
      
      if (!existingClient) {
        return null;
      }
      
      // 处理组变更
      if (client.groupId !== undefined) {
        // 从旧组中移除
        this.groups.forEach(group => {
          group.clientIds = group.clientIds.filter(id => id !== clientId);
        });
        
        // 添加到新组
        if (client.groupId) {
          await this.addClientToGroup(clientId, client.groupId);
        }
      }
      
      return {
        ...existingClient,
        ...client,
      };
    } catch (error) {
      console.error('Failed to update client:', error);
      return null;
    }
  }

  async createGroup(group: Omit<ClientGroup, 'id' | 'clientIds'>): Promise<ClientGroup> {
    const newGroup: ClientGroup = {
      ...group,
      id: `g${this.groups.length + 1}`,
      clientIds: [],
    };
    
    this.groups.push(newGroup);
    return newGroup;
  }

  async updateGroup(groupId: string, group: Partial<ClientGroup>): Promise<ClientGroup | null> {
    const existingGroup = this.groups.find(g => g.id === groupId);
    
    if (!existingGroup) {
      return null;
    }
    
    Object.assign(existingGroup, group);
    return existingGroup;
  }

  async deleteGroup(groupId: string): Promise<boolean> {
    const index = this.groups.findIndex(g => g.id === groupId);
    
    if (index === -1) {
      return false;
    }
    
    this.groups.splice(index, 1);
    return true;
  }

  async addClientToGroup(clientId: string, groupId: string): Promise<boolean> {
    const group = this.groups.find(g => g.id === groupId);
    
    if (!group) {
      return false;
    }
    
    if (!group.clientIds.includes(clientId)) {
      group.clientIds.push(clientId);
    }
    
    return true;
  }

  async removeClientFromGroup(clientId: string, groupId: string): Promise<boolean> {
    const group = this.groups.find(g => g.id === groupId);
    
    if (!group) {
      return false;
    }
    
    group.clientIds = group.clientIds.filter(id => id !== clientId);
    return true;
  }

  async getClientDetails(clientId: string): Promise<Client | null> {
    const clients = await this.fetchClients();
    return clients.find(c => c.id === clientId) || null;
  }

  async getClientPerformance(clientId: string): Promise<{ cpu: number; memory: number; network: number }> {
    return {
      cpu: Math.random() * 100,
      memory: Math.random() * 100,
      network: Math.random() * 100,
    };
  }
}

export const clientDataSource = new ClientDataSourceImpl();