const fs = require('fs').promises;
const path = require('path');

/**
 * ConfigGenerator - Generates config.yaml and metadata from settings
 * Matches the behavior of the terminal launcher exactly
 */
class ConfigGenerator {
  constructor(cosmoRoot, logger = console) {
    this.cosmoRoot = cosmoRoot;
    this.logger = logger;
  }

  /**
   * Generate complete config.yaml from settings
   */
  async generateConfig(settings) {
    const { 
      exploration_mode = 'guided',
      domain = '',
      context = '',
      execution_mode = 'mixed',
      depth = 'normal',
      max_cycles = '100',
      silent_planning = false,
      enable_web_search = false,
      enable_sleep = false,
      enable_coding_agents = true,
      enable_github_mcp = false,
      review_period = 20,
      max_concurrent = 4,
      file_access_paths = 'runtime/outputs/, runtime/exports/',
      cluster_enabled = false,
      cluster_backend = 'none',
      cluster_size = 1,
      specialization_enabled = false,
      specialization_profiles = [],
      dream_mode = false,
      dream_cycles = 100,
      dreams_per_cycle = 10,
      enable_stabilization = false,
      enable_experimental = false,
      enable_introspection = false,
      enable_agent_routing = false,
      enable_memory_governance = false,
      enable_recursive_mode = false,
      enable_frontier = false,
      enable_capabilities = true,
      frontier_mode = 'observe',
      // Local LLM settings
      enable_local_llm = false,
      local_llm_base_url = 'http://localhost:11434/v1',
      local_llm_default_model = 'qwen2.5:14b',
      local_llm_fast_model = 'qwen2.5:14b',
      searxng_url = ''
    } = settings || {};

    // Escape for YAML
    const contextEscaped = (context || '').replace(/\|/g, ' ').replace(/'/g, "\\'");
    const domainEscaped = (domain || '').replace(/\|/g, ' ').replace(/'/g, "\\'");

    // Convert unlimited to null
    const maxCyclesValue = max_cycles === 'unlimited' ? 'null' : max_cycles;

    // Calculate agent weights
    const codeCreationWeight = enable_coding_agents ? '25' : '0';
    const codeExecutionWeight = enable_coding_agents ? '10' : '0';
    // NOTE: Research agents can do file analysis via MCP even without web search
    // They have defensive checks to gracefully handle web search being disabled
    const researchWeight = '20';

    // QA enabled for autonomous, disabled for guided
    const qaEnabled = exploration_mode !== 'guided';

    // Build config YAML
    let configYaml = `# COSMO Configuration
# Generated by COSMO Launcher Dashboard
# ${new Date().toISOString()}

architecture:
  roleSystem:
    type: dynamic
    explorationMode: ${exploration_mode}
    
    guidedFocus:
      domain: "${domainEscaped}"
      executionMode: ${execution_mode}
      taskPriority: 1.0
      autonomousPriority: 0.3
      silentPlanning: ${silent_planning}
      context: |
        ${contextEscaped}
      depth: "${depth}"
      intrinsicBias: 0.8
      curiosityAllowed: ${!enable_stabilization}
    
    initialRoles:
      - id: curiosity
        prompt: "Generate ONE novel question (2-4 sentences)."
        promptGuided: "Generate ONE question about {domain}. {context}"
        temperature: 1.0
        max_completion_tokens: 500
        successThreshold: 0.6
        enableMCPTools: true
      - id: analyst
        prompt: "Examine ONE topic (3-5 sentences)."
        promptGuided: "Examine ONE aspect of {domain}. {context}"
        temperature: 1.0
        max_completion_tokens: 500
        successThreshold: 0.7
        enableMCPTools: true
      - id: critic
        prompt: "Critically evaluate ONE assumption (3-5 sentences)."
        promptGuided: "Evaluate ONE assumption about {domain}. {context}"
        temperature: 1.0
        max_completion_tokens: 500
        successThreshold: 0.7
        enableMCPTools: true
    evolutionEnabled: false
    maxRoles: 15
  
  codeCreation:
    planMode: true
    maxOutputTokensPerCall: 4000
    perFileRetryLimit: 2
    planRetryLimit: 1
    planMaxOutputTokens: 2000
    reasoningEffort: low

  memory:
    type: graph
    topology: small-world
    embedding:
      model: text-embedding-3-small
      dimensions: 512
    decay:
      function: exponential
      baseFactor: 0.995
      minimumWeight: 0.1
      decayInterval: 3600
      exemptTags:
        - agent_insight
        - agent_finding
        - mission_plan
        - cross_agent_pattern
    spreading:
      enabled: true
      maxDepth: 3
      activationThreshold: 0.1
      decayFactor: 0.7
    hebbian:
      enabled: true
      reinforcementStrength: 0.1
      weakenFactor: 0.05
    smallWorld:
      clusteringCoefficient: 0.6
      averagePathLength: 3.0
      bridgeProbability: 0.05
      rewireInterval: 600
      maxRewireEdgesPerRun: 5000
      rewireYieldEvery: 500
    contextDiversity:
      enabled: true
      noContextProbability: 0.15
      maxContextNodes: 3
      peripheralSamplingRate: 0.20
      minSimilarityThreshold: 0.3
  
  reasoning:
    mode: quantum
    parallelBranches: ${enable_local_llm ? 2 : (enable_stabilization ? 2 : 5)}  # Reduced for local LLM (single GPU)
    collapseStrategy: weighted
    entanglementEnabled: ${!enable_stabilization}
    tunnelingProbability: ${enable_stabilization ? 0.0 : 0.02}
    features:
      branchPolicy:
        enabled: true
      latentProjector:
        enabled: true
      consistencyReview:
        enabled: true
        divergenceThreshold: 0.85
        maxBranchesAnalyzed: 3
        minCyclesBetweenReviews: 3
    latentProjector:
      maxMemoryNodes: 5
      maxGoalCount: 3
      hintMaxLength: 140
      vectorSize: 128
      autoTrain: true
      autoTrainThreshold: 100
      autoTrainInterval: 50
  
  creativity:
    chaosEnabled: ${!enable_stabilization}
    chaoticRNN:
      size: 100
      spectralRadius: 0.95
      updateSteps: 10
      perturbationInterval: 300
    mutations:
      enabled: ${!enable_stabilization}
      mutationRate: ${enable_stabilization ? 0 : 0.1}
      hybridizationRate: ${enable_stabilization ? 0 : 0.05}
  
  goals:
    intrinsicEnabled: ${!enable_stabilization}
    discoveryMethod: reflection
    maxGoals: ${enable_stabilization ? 25 : 150}
    prioritization: uncertainty
    rotation:
      enabled: true
      maxPursuitsPerGoal: 10
      satisfactionThreshold: 0.6
      staleArchiveAfterDays: 3
      dominanceThreshold: 0.20
      checkInterval: 5
    curator:
      enabled: true
      curationInterval: 20
      minGoalsForCampaign: 3
      campaignDuration: 30
      synthesisThreshold: 3
  
  thermodynamic:
    surpriseEnabled: ${!enable_stabilization}
    freeEnergyTarget: 0.5
  
  environment:
    sensorsEnabled: true
    sensors:
      - name: system_time
        type: internal
        pollInterval: 60
        enabled: true
  
  temporal:
    sleepEnabled: ${enable_sleep}
    oscillations:
      enabled: ${!enable_stabilization}
      fastPhaseDuration: 300
      slowPhaseDuration: 120
  
  cognitiveState:
    curiosityEnabled: ${!enable_stabilization}
    moodEnabled: ${!enable_stabilization}
    energyEnabled: true
    adaptationRate: 1.0
    initialCuriosity: 0.5
    initialMood: 0.5
    initialEnergy: 1.0
  
  reflection:
    enabled: true

models:
  # Core models - GPT-5.5 (best general-purpose model)
  primary: gpt-5.5
  fast: gpt-5.4-mini
  nano: gpt-5.4-mini
  embeddings: text-embedding-3-small
  
  # Component-specific models
  strategicModel: gpt-5.5            # Synthesis, planning, integration, QA agents
  coordinatorStrategic: gpt-5.5      # Meta-coordinator strategic decisions
  coordinatorStandard: gpt-5.4-mini    # Meta-coordinator reviews
  plannerModel: gpt-5.4-mini           # Guided mode planner
  curatorModel: gpt-5.4-mini           # Goal curator operations
  curatorStrategic: gpt-5.5          # Goal curator deep analysis
  
  defaultReasoningEffort: low
  defaultMaxTokens: ${enable_local_llm ? 4000 : 6000}
  enableWebSearch: ${enable_web_search}  # Works with local LLM via free DuckDuckGo search
  enableExtendedReasoning: ${!enable_local_llm}

providers:
  openai:
    enabled: ${!enable_local_llm}
${enable_local_llm ? `
  # Local LLM provider (Ollama, vLLM, llama.cpp, etc.)
  local:
    enabled: true
    baseURL: "${local_llm_base_url}"
    defaultModel: "${local_llm_default_model}"
    modelMapping:
      gpt-5.5: "${local_llm_default_model}"
      gpt-5: "${local_llm_default_model}"
      gpt-5.4-mini: "${local_llm_fast_model}"
      gpt-5.4-nano: "${local_llm_fast_model}"
    supportsTools: true
    supportsStreaming: true
${searxng_url ? `    searxngUrl: "${searxng_url}"` : '    # searxngUrl: "http://localhost:8888"  # Optional: SearXNG for reliable web search'}

# Route all components to local provider
modelAssignments:
  default:
    provider: local
    model: "${local_llm_default_model}"
  quantumReasoner.branches:
    provider: local
    model: "${local_llm_fast_model}"
  coordinator:
    provider: local
    model: "${local_llm_fast_model}"
` : ''}
coordinator:
  enabled: ${dream_mode ? 'false' : 'true'}
  reviewCyclePeriod: ${enable_local_llm ? Math.max(review_period, 25) : (enable_stabilization ? 15 : review_period)}  # Increased for local LLM
  model: gpt-5.4-mini
  reasoningEffort: low
  maxTokens: 3000
  maxConcurrent: ${enable_local_llm ? 2 : (enable_stabilization ? 2 : max_concurrent)}  # Reduced for local LLM
  enableCodingAgents: ${enable_coding_agents}
  
  useTemplateReports: true
  useMemorySummaries: true
  extractiveSummarization: true
  
  qualityAssurance:
    enabled: ${qaEnabled}
    mode: 'balanced'
    minConfidence: 0.7
    autoRejectThreshold: 0.3
    checkNovelty: false
    checkConsistency: true
    checkFactuality: false
  
  agentTypeWeights:
    planning: 25
    integration: 25
    code_creation: ${codeCreationWeight}
    research: ${researchWeight}
    analysis: 20
    synthesis: 20
    document_creation: 15
    code_execution: ${codeExecutionWeight}
    exploration: ${enable_stabilization ? 0 : 10}
    document_analysis: 10
    specialized_binary: 10
    completion: 5
    quality_assurance: 5
    consistency: 5
  
  codeExecution:
    enabled: ${enable_coding_agents}
    containerTimeout: 600000
    maxContainersPerReview: 1
    autoCleanup: true

execution:
  # Execution timing and cycle configuration
  baseInterval: ${enable_local_llm ? 90 : 60}  # Increased for local LLM (slower inference)
  # Code execution backend configuration (container vs local)
  backend: local  # 'local' (default) or 'container' (legacy, has download corruption issues)
  
  local:
    pythonPath: python3  # Auto-detect if not set
    useVirtualEnv: false
    virtualEnvPath: null
    timeout: 30000  # 30 seconds
    maxMemory: 512MB
    allowedPackages: [numpy, pandas, matplotlib, scipy]
    autoInstallPackages: true
    workingDir: runtime/outputs/execution
    
  container:
    timeout: 600000  # 10 minutes
    maxFiles: 50
  maxCycles: ${dream_mode ? dream_cycles : maxCyclesValue}
  adaptiveTimingEnabled: true${dream_mode ? `
  dreamMode: true
  dreamModeSettings:
    continuousConsolidation: true
    dreamsPerCycle: ${dreams_per_cycle}
    preventWake: true
    preventEnergyRestoration: true
    disableConsolidationRateLimit: true` : ''}

timeouts:
  cycleTimeoutMs: ${enable_local_llm ? 300000 : 180000}  # 5min for local LLM, 3min for cloud
  operationTimeoutMs: ${enable_local_llm ? 180000 : 120000}  # Increased for local LLM

resources:
  memoryLimitMB: 1024
  memoryWarningThreshold: 0.8
  cpuWarningThreshold: 0.9

cluster:
  enabled: ${cluster_enabled}
  backend: ${cluster_backend}
  instanceCount: ${cluster_size}
  mode: active-active
  stateStore:
    compression: true
    compressionRatio: 0.25
  coordinator:
    enabled: ${cluster_enabled}
    quorumRatio: 0.67
    minQuorum: 2
    timeoutMs: 60000
    skipOnTimeout: true
    pollIntervalMs: 500
    barrierTtlMs: 600000
    gating:
      enabled: false
  redis:
    url: "redis://localhost:6379"
    tls: false
    acl: false
    keyPrefix: "cosmo:cluster:"
  filesystem:
    root: "runtime/cluster"
    leaseMs: 5000
    graceMs: 2000

introspection:
  enabled: ${enable_introspection}
  routingEnabled: ${enable_introspection}
  maxFilesPerCycle: 10
  maxPreviewLength: 400
  maxRoutedItems: 5

agentRouting:
  enabled: ${enable_agent_routing}
  autoSpawn: ${enable_agent_routing}
  maxMissionsPerCycle: 2
  spawnCooldownCycles: 5
  criticOnContradiction: true
  synthesisOnAnalysis: true
  reuseOnCode: true
  researchOnQuestions: true

memoryGovernance:
  enabled: ${enable_memory_governance}
  applyPruning: false
  decayHalfLifeCycles: 200
  pruneThreshold: 0.1
  maxNodesConsidered: 200

recursiveMode:
  enabled: ${enable_recursive_mode}
  haltOnGoalExhaustion: ${enable_recursive_mode}
  minCyclesBeforeGoalExhaustion: 20
  maxMetaIterations: 8
  minCyclesPerReview: 30
  stagnationTolerance: 3

substrate:
  enabled: ${enable_recursive_mode}
  pythonBin: python3

frontier:
  enabled: ${enable_frontier}
  mode: observe
  outputDir: ./runtime/outputs/governance
  policies:
    bashExecute: observe
    codeExecute: observe
    fileWrite: observe
    configLoad: observe
`;

    // Add specialization if enabled
    if (specialization_enabled && specialization_profiles && specialization_profiles.length > 0) {
      const domainYaml = (exploration_mode === 'guided' && domain) ? 
        `['${domain.replace(/'/g, "''")}']` : '[]';
      
      configYaml += `  specialization:
    enabled: true
    defaults:
      boost: 2
      penalty: 0.5
      unmatchedPenalty: 0.9
      minMultiplier: 0.3
      maxMultiplier: 3
      nonPreferredPenalty: 0.1
    profiles:
`;
      
      for (let i = 0; i < cluster_size; i++) {
        const instanceLabel = `cosmo-${i + 1}`;
        const profile = specialization_profiles[i] || {};
        configYaml += `      ${instanceLabel}:
        name: ${profile.name || 'generalist'}
        agentTypes: ${JSON.stringify(profile.agentTypes || [])}
        keywords: ${JSON.stringify(profile.keywords || [])}
        tags: ${JSON.stringify(profile.tags || [])}
        avoidKeywords: ${JSON.stringify(profile.avoidKeywords || [])}
        avoidTags: ${JSON.stringify(profile.avoidTags || [])}
        domains: ${domainYaml}
`;
      }
    } else {
      configYaml += `  specialization:
    enabled: false
`;
    }

    configYaml += `
acceptance:
  enabled: true
  defaultThreshold: 0.7
  qaEnabled: true
  toolValidation: true
  literalValidation: true
  minConfidence: 0.7
  autoRejectThreshold: 0.3

# Executive Ring - COSMO's executive function layer (middle ring)
# Implements dorsolateral PFC function (continuous reality checking)
executiveRing:
  enabled: true
  useLLM: true
  coherenceThreshold: 0.5
  alignmentCheckInterval: 5
  stuckLoopThreshold: 5
  toolBuildingThreshold: 6
  
  # Basal ganglia: Action selection with commitment
  maxActiveGoals: 3              # Hard limit on concurrent goal pursuits
  maxConcurrentAgents: 2         # Hard limit on parallel agents
  commitmentCycles: 10           # Cycles to commit before re-evaluating

# Capabilities - Direct tool access (Embodied Cognition)
# NEW: Motor cortex layer for autonomous action
capabilities:
  enabled: ${enable_capabilities}
  executiveGating: true          # Route through Executive Ring for judgment
  useFrontierGate: true          # Log actions via FrontierGate
  defaultMode: ${frontier_mode}  # observe | soft | hard

logging:
  level: info
  thoughtJournal: true
  cycleMetrics: true

dashboard:
  enabled: true
  port: 3344

mcp:
  server:
    enabled: true
    port: 3347
  
  client:
    enabled: true
    servers:
      - label: "filesystem"
        type: "http"
        url: "http://localhost:3347/mcp"
        auth: null
        allowedTools: ["read_file", "read_binary_file", "list_directory"]
        requireApproval: "never"
        enabled: true
`;

    // Add file access paths
    if (file_access_paths !== 'FULL_ACCESS') {
      configYaml += `        allowedPaths:\n`;
      const paths = file_access_paths.split(',').map(p => p.trim()).filter(p => p);
      for (const p of paths) {
        configYaml += `          - "${p}"\n`;
      }
    } else {
      // Full repository access - provide repository root path
      configYaml += `        # Full repository access (node_modules/ and .git/ excluded)\n`;
      configYaml += `        allowedPaths:\n`;
      configYaml += `          - "."\n`;
    }

    // Add GitHub MCP if enabled
    if (enable_github_mcp && process.env.GITHUB_PERSONAL_ACCESS_TOKEN) {
      configYaml += `      
      - label: "github"
        type: "external_process"
        command: "npx"
        args: ["-y", "@modelcontextprotocol/server-github"]
        env:
          GITHUB_PERSONAL_ACCESS_TOKEN: "${process.env.GITHUB_PERSONAL_ACCESS_TOKEN}"
        requireApproval: "never"
        enabled: true
`;
    }

    // Add experimental section if enabled
    if (enable_experimental) {
      configYaml += `

experimental:
  enabled: true
  approval:
    required: true
    timeout_sec: 60
  limits:
    time_sec: 600
    actions: 50
  network:
    allow: ["localhost"]
`;
    }

    return configYaml;
  }

  /**
   * Generate metadata JSON from settings
   */
  generateMetadata(settings, cleanStart = false) {
    const {
      exploration_mode = 'guided',
      domain = '',
      context = '',
      execution_mode = 'mixed',
      depth = 'normal',
      max_cycles = '100',
      silent_planning = false,
      enable_web_search = true,
      enable_sleep = true,
      enable_coding_agents = true,
      enable_stabilization = false,
      enable_github_mcp = false,
      enable_experimental = false,
      enable_introspection = true,
      enable_agent_routing = true,
      enable_memory_governance = true,
      enable_recursive_mode = true,
      enable_frontier = true,
      enable_capabilities = true,
      frontier_mode = 'observe',
      review_period = 20,
      max_concurrent = 4,
      file_access_paths = 'runtime/outputs/, runtime/exports/',
      cluster_enabled = false,
      cluster_backend = 'none',
      cluster_size = 1,
      specialization_enabled = false,
      specialization_profiles = [],
      enable_local_llm = false,
      local_llm_base_url = 'http://localhost:11434/v1',
      local_llm_default_model = 'qwen2.5:14b',
      local_llm_fast_model = 'qwen2.5:14b',
      searxng_url = ''
    } = settings || {};

    const maxCyclesValue = max_cycles === 'unlimited' ? 'null' : max_cycles;

    // Build specialization metadata
    let specializationMeta = {
      profiles: '',
      agentTypes: '',
      keywords: '',
      tags: '',
      avoidKeywords: '',
      avoidTags: ''
    };

    if (specialization_enabled && specialization_profiles && specialization_profiles.length > 0) {
      const profiles = [];
      const agentTypes = [];
      const keywords = [];
      const tags = [];
      const avoidKeywords = [];
      const avoidTags = [];

      for (let i = 0; i < cluster_size; i++) {
        const instanceLabel = `cosmo-${i + 1}`;
        const profile = specialization_profiles[i] || {};

        profiles.push(`${instanceLabel}=${profile.name || 'generalist'}`);
        agentTypes.push(`${instanceLabel}=${JSON.stringify(profile.agentTypes || [])}`);
        keywords.push(`${instanceLabel}=${JSON.stringify(profile.keywords || [])}`);
        tags.push(`${instanceLabel}=${JSON.stringify(profile.tags || [])}`);
        avoidKeywords.push(`${instanceLabel}=${JSON.stringify(profile.avoidKeywords || [])}`);
        avoidTags.push(`${instanceLabel}=${JSON.stringify(profile.avoidTags || [])}`);
      }

      specializationMeta.profiles = profiles.join('|');
      specializationMeta.agentTypes = agentTypes.join('|');
      specializationMeta.keywords = keywords.join('|');
      specializationMeta.tags = tags.join('|');
      specializationMeta.avoidKeywords = avoidKeywords.join('|');
      specializationMeta.avoidTags = avoidTags.join('|');
    }

    const metadata = {
      created: new Date().toISOString(),
      cleanStart,
      explorationMode: exploration_mode,
      domain,
      context,
      executionMode: execution_mode,
      depth,
      maxCycles: maxCyclesValue,
      silentPlanning: silent_planning,
      enableWebSearch: enable_web_search,
      enableSleep: enable_sleep,
      enableCodingAgents: enable_coding_agents,
      enableStabilization: enable_stabilization,
      githubMcpEnabled: enable_github_mcp,
      enableExperimental: enable_experimental,
      enableIntrospection: enable_introspection,
      enableAgentRouting: enable_agent_routing,
      enableMemoryGovernance: enable_memory_governance,
      enableRecursiveMode: enable_recursive_mode,
      enableFrontier: enable_frontier,
      enableCapabilities: enable_capabilities,
      frontierMode: frontier_mode,
      reviewPeriod: review_period,
      maxConcurrent: max_concurrent,
      fileAccessEnabled: true,
      fileAccessPaths: file_access_paths,
      clusterEnabled: cluster_enabled,
      clusterBackend: cluster_backend,
      clusterSize: cluster_size,
      clusterDashboardPort: 3360,
      clusterFilesystemRoot: cluster_backend === 'filesystem' ? 'runtime/cluster' : null,
      clusterSpecializationEnabled: specialization_enabled,
      clusterSpecializationProfiles: specializationMeta.profiles,
      clusterSpecializationAgentTypes: specializationMeta.agentTypes,
      clusterSpecializationKeywords: specializationMeta.keywords,
      clusterSpecializationTags: specializationMeta.tags,
      clusterSpecializationAvoidKeywords: specializationMeta.avoidKeywords,
      clusterSpecializationAvoidTags: specializationMeta.avoidTags,
      // Local LLM settings
      enableLocalLlm: enable_local_llm,
      localLlmBaseUrl: enable_local_llm ? local_llm_base_url : null,
      localLlmDefaultModel: enable_local_llm ? local_llm_default_model : null,
      localLlmFastModel: enable_local_llm ? local_llm_fast_model : null,
      searxngUrl: searxng_url || null,
      launcherVersion: '2.0-web'
    };

    return metadata;
  }

  /**
   * Write config.yaml file
   */
  async writeConfig(settings) {
    const configYaml = await this.generateConfig(settings);
    const configPath = path.join(this.cosmoRoot, 'src', 'config.yaml');

    try {
      await fs.writeFile(configPath, configYaml, 'utf8');
      this.logger.info(`Config written: ${configPath}`);
      return { success: true, path: configPath };
    } catch (error) {
      this.logger.error('Failed to write config:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * Write metadata JSON file
   */
  async writeMetadata(runPath, settings, cleanStart = false) {
    const metadata = this.generateMetadata(settings, cleanStart);
    const metadataPath = path.join(runPath, 'run-metadata.json');

    try {
      await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
      this.logger.info(`Metadata written: ${metadataPath}`);
      return { success: true, path: metadataPath, metadata };
    } catch (error) {
      this.logger.error('Failed to write metadata:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * Get default settings for new run
   */
  getDefaults() {
    return {
      exploration_mode: 'guided',
      domain: '',
      context: '',
      execution_mode: 'mixed',
      depth: 'normal',
      max_cycles: '100',
      silent_planning: false,
      enable_web_search: true,          // Default: enabled
      enable_sleep: true,               // Default: enabled
      enable_coding_agents: true,
      enable_introspection: true,       // Default: enabled
      enable_agent_routing: true,       // Default: enabled
      enable_memory_governance: true,   // Default: enabled
      enable_recursive_mode: true,      // Default: enabled
      enable_frontier: true,            // Default: enabled (observe mode)
      enable_capabilities: true,        // Default: enabled
      frontier_mode: 'observe',
      enable_stabilization: false,      // Keep disabled
      enable_github_mcp: false,         // Keep disabled
      enable_experimental: false,       // Keep disabled
      review_period: 20,
      max_concurrent: 4,
      file_access_paths: 'runtime/outputs/, runtime/exports/',
      cluster_enabled: false,
      cluster_backend: 'none',
      cluster_size: 1,
      specialization_enabled: false,
      specialization_profiles: [],
      // Local LLM settings (for air-gapped / no API cost operation)
      enable_local_llm: false,
      local_llm_base_url: 'http://localhost:11434/v1',
      local_llm_default_model: 'qwen2.5:14b',
      local_llm_fast_model: 'qwen2.5:14b',
      searxng_url: ''
    };
  }
}

module.exports = { ConfigGenerator };
