/**
 * MCP Configuration Service
 * 解析全局（环境变量）和租户级 MCP Server 配置
 *
 * 配置来源：
 * 1. 环境变量 MCP_SERVERS — 全局 Server 列表（JSON）
 * 2. TenantConfig.ai.mcpServers — 租户级 Server 列表
 */

import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TenantContextService } from '@iconsulting/shared';
import { McpServerConfig, McpTenantConfig } from './mcp.types';

interface McpGlobalConfig {
  servers: McpServerConfig[];
  enabled: boolean;
}

@Injectable()
export class McpConfigService implements OnModuleInit {
  private readonly logger = new Logger(McpConfigService.name);
  private globalConfig: McpGlobalConfig = { servers: [], enabled: false };

  constructor(
    private readonly configService: ConfigService,
    private readonly tenantContext: TenantContextService,
  ) {}

  onModuleInit() {
    this.globalConfig = this.parseGlobalConfig();
    if (this.globalConfig.enabled) {
      this.logger.log(
        `MCP global config: ${this.globalConfig.servers.length} server(s) configured — ` +
        this.globalConfig.servers.map(s => `${s.id}(${s.transport})`).join(', '),
      );
    } else {
      this.logger.log('MCP global config: disabled (MCP_SERVERS not set)');
    }
  }

  /** 获取当前请求上下文的所有 MCP Server 配置（全局 + 租户） */
  getServersForCurrentTenant(): McpServerConfig[] {
    const servers: McpServerConfig[] = [];

    // 1. 全局 servers
    if (this.globalConfig.enabled) {
      servers.push(...this.globalConfig.servers);
    }

    // 2. 租户级 servers
    const tenantMcpConfig = this.getTenantMcpConfig();
    if (tenantMcpConfig?.enabled) {
      servers.push(...tenantMcpConfig.servers);
    }

    return servers.filter(s => s.enabled !== false);
  }

  /** 获取全局 MCP Server 配置 */
  getGlobalServers(): McpServerConfig[] {
    return this.globalConfig.enabled
      ? this.globalConfig.servers.filter(s => s.enabled !== false)
      : [];
  }

  /** 检查 MCP 是否在任何层级启用 */
  isEnabled(): boolean {
    return this.globalConfig.enabled || !!this.getTenantMcpConfig()?.enabled;
  }

  /** 检查全局 MCP 是否启用 */
  isGlobalEnabled(): boolean {
    return this.globalConfig.enabled;
  }

  // ---- Private ----

  private parseGlobalConfig(): McpGlobalConfig {
    const mcpServersJson = this.configService.get<string>('MCP_SERVERS');
    if (!mcpServersJson) {
      return { servers: [], enabled: false };
    }

    try {
      const parsed = JSON.parse(mcpServersJson);
      // 支持 [{ ... }] 或 { "servers": [{ ... }] } 两种格式
      const servers: McpServerConfig[] = Array.isArray(parsed)
        ? parsed
        : (parsed.servers || []);

      // 基本校验
      const validServers = servers.filter(s => {
        if (!s.id || !s.name || !s.transport) {
          this.logger.warn(`Skipping invalid MCP server config: missing id/name/transport`);
          return false;
        }
        if (s.transport === 'stdio' && !s.command) {
          this.logger.warn(`Skipping MCP server "${s.id}": stdio transport requires "command"`);
          return false;
        }
        if (s.transport === 'sse' && !s.url) {
          this.logger.warn(`Skipping MCP server "${s.id}": sse transport requires "url"`);
          return false;
        }
        return true;
      });

      return { servers: validServers, enabled: validServers.length > 0 };
    } catch (error) {
      this.logger.error(`Failed to parse MCP_SERVERS env var: ${error}`);
      return { servers: [], enabled: false };
    }
  }

  private getTenantMcpConfig(): McpTenantConfig | null {
    try {
      const tenant = this.tenantContext.getCurrentTenant();
      if (!tenant?.config?.ai) return null;
      const mcpConfig = (tenant.config.ai as any)?.mcpServers as McpTenantConfig | undefined;
      return mcpConfig || null;
    } catch {
      return null;
    }
  }
}
