import { http } from './http';
import { SERVICE_CONFIGS, ServiceConfig } from '../../../server/src/config/serviceConfig';

export interface ServiceInfo {
  name: string;
  enabled: boolean;
  initialized: boolean;
  error?: string;
  config?: ServiceConfig;
}

export interface ServiceStats {
  total: number;
  enabled: number;
  disabled: number;
  initialized: number;
  failed: number;
  byCategory: Record<string, { total: number; enabled: number; initialized: number }>;
  byMemoryImpact: {
    low: { total: number; enabled: number };
    medium: { total: number; enabled: number };
    high: { total: number; enabled: number };
  };
}

export interface ServicePreset {
  id: string;
  name: string;
  description: string;
  serviceCount: number;
}

export interface ServiceManagerDataSource {
  list(): Promise<{ services: ServiceInfo[]; groupedServices: Record<string, ServiceInfo[]>; stats: ServiceStats }>;
  getStats(): Promise<ServiceStats>;
  toggle(name: string, enabled: boolean): Promise<{ name: string; enabled: boolean; message: string }>;
  batchToggle(services: string[], enabled: boolean): Promise<{ results: Array<{ name: string; success: boolean; error?: string }>; message: string }>;
  applyPreset(preset: string): Promise<{ preset: string; enabledCount: number; message: string }>;
  getPresets(): Promise<ServicePreset[]>;
  getCategories(): Promise<Record<string, { label: string; color: string }>>;
}

class ServiceManagerApiDataSource implements ServiceManagerDataSource {
  async list() {
    const response = await http.get('/api/service-manager/list');
    return response.data.data;
  }

  async getStats() {
    const response = await http.get('/api/service-manager/stats');
    return response.data.data;
  }

  async toggle(name: string, enabled: boolean) {
    const response = await http.post(`/api/service-manager/toggle/${name}`, { enabled });
    return response.data.data;
  }

  async batchToggle(services: string[], enabled: boolean) {
    const response = await http.post('/api/service-manager/batch-toggle', { services, enabled });
    return response.data.data;
  }

  async applyPreset(preset: string) {
    const response = await http.post(`/api/service-manager/apply-preset/${preset}`);
    return response.data.data;
  }

  async getPresets() {
    const response = await http.get('/api/service-manager/presets');
    return response.data.data;
  }

  async getCategories() {
    const response = await http.get('/api/service-manager/categories');
    return response.data.data;
  }
}

class ServiceManagerMockDataSource implements ServiceManagerDataSource {
  private mockServices: ServiceInfo[] = SERVICE_CONFIGS.map(config => ({
    name: config.name,
    enabled: config.enabled,
    initialized: config.enabled,
    config,
  }));

  async list() {
    const groupedServices = this.mockServices.reduce((acc, service) => {
      const category = service.config?.category || 'BUSINESS';
      if (!acc[category]) acc[category] = [];
      acc[category].push(service);
      return acc;
    }, {} as Record<string, ServiceInfo[]>);

    const byCategory: Record<string, { total: number; enabled: number; initialized: number }> = {};
    const categories = Array.from(new Set(this.mockServices.map(s => s.config?.category || 'BUSINESS')));
    categories.forEach(cat => {
      const services = this.mockServices.filter(s => s.config?.category === cat);
      byCategory[cat] = {
        total: services.length,
        enabled: services.filter(s => s.enabled).length,
        initialized: services.filter(s => s.initialized).length,
      };
    });

    const byMemoryImpact = {
      low: {
        total: this.mockServices.filter(s => s.config?.memoryImpact === 'low').length,
        enabled: this.mockServices.filter(s => s.config?.memoryImpact === 'low' && s.enabled).length,
      },
      medium: {
        total: this.mockServices.filter(s => s.config?.memoryImpact === 'medium').length,
        enabled: this.mockServices.filter(s => s.config?.memoryImpact === 'medium' && s.enabled).length,
      },
      high: {
        total: this.mockServices.filter(s => s.config?.memoryImpact === 'high').length,
        enabled: this.mockServices.filter(s => s.config?.memoryImpact === 'high' && s.enabled).length,
      },
    };

    return {
      services: this.mockServices,
      groupedServices,
      stats: {
        total: this.mockServices.length,
        enabled: this.mockServices.filter(s => s.enabled).length,
        disabled: this.mockServices.filter(s => !s.enabled).length,
        initialized: this.mockServices.filter(s => s.initialized).length,
        failed: this.mockServices.filter(s => s.error).length,
        byCategory,
        byMemoryImpact,
      },
    };
  }

  async getStats(): Promise<ServiceStats> {
    const list = await this.list();
    return list.stats;
  }

  async toggle(name: string, enabled: boolean) {
    const service = this.mockServices.find(s => s.name === name);
    if (service) service.enabled = enabled;
    return { name, enabled, message: `服务 "${name}" 已${enabled ? '启用' : '禁用'}` };
  }

  async batchToggle(services: string[], enabled: boolean) {
    return {
      results: services.map(name => ({ name, success: true })),
      message: `已${enabled ? '启用' : '禁用'} ${services.length} 个服务`,
    };
  }

  async applyPreset(preset: string) {
    return { preset, enabledCount: 5, message: `已应用 "${preset}" 预设` };
  }

  async getPresets(): Promise<ServicePreset[]> {
    return [
      { id: 'minimal', name: '最小模式', description: '仅启动核心服务', serviceCount: 10 },
      { id: 'standard', name: '标准模式', description: '启动默认启用的服务', serviceCount: 20 },
      { id: 'development', name: '开发模式', description: '核心+业务服务', serviceCount: 30 },
      { id: 'full', name: '完整模式', description: '启动所有服务', serviceCount: 100 },
    ];
  }

  async getCategories() {
    return {
      CORE: { label: '核心服务', color: 'blue' },
      BUSINESS: { label: '业务服务', color: 'green' },
      TELEMETRY: { label: '遥测服务', color: 'orange' },
      SECURITY: { label: '安全服务', color: 'red' },
      NETWORK: { label: '网络服务', color: 'purple' },
      AI: { label: 'AI服务', color: 'cyan' },
    };
  }
}

const useMock = process.env.NODE_ENV === 'development' || process.env.REACT_APP_USE_MOCK === 'true';
export const serviceManagerDataSource: ServiceManagerDataSource = useMock
  ? new ServiceManagerMockDataSource()
  : new ServiceManagerApiDataSource();
