import fs from 'fs';
import path from 'path';
import dotenv from 'dotenv';

/**
 * Loads environment variables only from the target project .env.
 * The MCP repo must not auto-read its own .env/package/cwd files.
 */
function loadAllEnvs(projectPath?: string) {
  if (!projectPath) {
    return;
  }

  const envPath = path.resolve(projectPath, '.env');
  if (fs.existsSync(envPath)) {
    const result = dotenv.config({ path: envPath, override: true, quiet: true });
    if (result.error) {
      console.error(`Failed to load .env from ${envPath}:`, result.error);
    }
  }
}

export function getConfig(projectPath?: string) {
  if (projectPath) {
    loadAllEnvs(projectPath);
  }

  return {
    cflint: {
      jarPath: process.env.CFLINT_JAR || 'C:\\tesisquare\\cflint\\CFLint-1.5.0-all.jar',
      javaPath: process.env.JAVA_BIN
        ? process.env.JAVA_BIN
        : (process.env.JAVA_HOME
          ? path.join(process.env.JAVA_HOME as string, 'bin', 'java.exe')
          : 'D:\\programmi\\ColdFusion2023\\jre\\bin\\java.exe'),
      defaultConfigPath: process.env.CFLINT_CONFIG || null
    }
  };
}

// Maintain backward compatibility with the static config object if needed,
// but it will only have startup values.
export const config = getConfig();
