import { readFile, access } from 'fs/promises';
import { join } from 'path';
import type { MCPConfig, MCPServerConfig } from './types.js';

const DEFAULT_CONFIG: MCPConfig = {
  servers: {},
};

/**
 * Interpolate environment variables in a string
 * Supports ${VAR} and ${VAR:-default} syntax
 */
function interpolateEnv(value: string): string {
  return value.replace(/\$\{([^}]+)\}/g, (match, expr) => {
    // Handle default value syntax: ${VAR:-default}
    const [varName, defaultValue] = expr.split(':-');
    return process.env[varName] ?? defaultValue ?? '';
  });
}

/**
 * Interpolate environment variables in server config
 */
function interpolateServerConfig(config: MCPServerConfig): MCPServerConfig {
  const result = { ...config };

  // Interpolate command
  result.command = interpolateEnv(config.command);

  // Interpolate args
  if (config.args) {
    result.args = config.args.map(interpolateEnv);
  }

  // Interpolate env values
  if (config.env) {
    result.env = {};
    for (const [key, value] of Object.entries(config.env)) {
      result.env[key] = interpolateEnv(value);
    }
  }

  // Interpolate cwd
  if (config.cwd) {
    result.cwd = interpolateEnv(config.cwd);
  }

  return result;
}

/**
 * Load MCP configuration from .emdash/mcp.json
 */
export async function loadMCPConfig(repoRoot: string): Promise<MCPConfig> {
  const configPath = join(repoRoot, '.emdash', 'mcp.json');

  try {
    await access(configPath);
  } catch {
    return DEFAULT_CONFIG;
  }

  try {
    const content = await readFile(configPath, 'utf-8');
    const config = JSON.parse(content) as MCPConfig;

    // Interpolate environment variables in each server config
    const servers: Record<string, MCPServerConfig> = {};
    for (const [name, serverConfig] of Object.entries(config.servers)) {
      servers[name] = interpolateServerConfig(serverConfig);
    }

    return { servers };
  } catch (err) {
    console.warn(`Failed to load MCP config from ${configPath}:`, err);
    return DEFAULT_CONFIG;
  }
}

/**
 * Get enabled servers from config
 */
export function getEnabledServers(config: MCPConfig): Record<string, MCPServerConfig> {
  const enabled: Record<string, MCPServerConfig> = {};

  for (const [name, serverConfig] of Object.entries(config.servers)) {
    if (serverConfig.enabled !== false) {
      enabled[name] = serverConfig;
    }
  }

  return enabled;
}
