'use strict';

const path = require('path');

let lastEnsureAt = 0;

function isMcpAutoConfigDisabled(env = process.env) {
  return getMcpAutoConfigSkipReason(env) === 'disabled';
}

function isMcpCapableAgentCommand(cmd) {
  const base = path.basename(String(cmd || '')).toLowerCase();
  return base === 'claude' || base === 'codex';
}

function loadMcpIntegration() {
  return require(path.resolve(__dirname, '..', '..', 'wall-e', 'lib', 'mcp-integration'));
}

function getMcpAutoConfigSkipReason(env = process.env) {
  try {
    const { getMcpAutoConfigSkipReason: getReason } = loadMcpIntegration();
    if (typeof getReason === 'function') return getReason(env);
  } catch (e) {
    if (env.WALLE_MCP_AUTO_CONFIG_DEBUG === '1') {
      console.warn('[walle-mcp-auto-config] failed to load Wall-E MCP integration:', e.message);
    }
  }
  const value = String(env.WALLE_MCP_AUTO_CONFIG || '').trim().toLowerCase();
  if (value === '0' || value === 'false' || value === 'no' || value === 'off') return 'disabled';
  return '';
}

function ensureWalleMcpForAgentSession({
  cmd,
  wallePort,
  homeDir,
  env = process.env,
  logger = console,
  now = Date.now(),
  minIntervalMs = 30000,
} = {}) {
  if (!isMcpCapableAgentCommand(cmd)) return { skipped: 'not_mcp_capable_agent' };
  const skipReason = getMcpAutoConfigSkipReason(env);
  if (skipReason) return { skipped: skipReason };
  if (lastEnsureAt && now - lastEnsureAt < minIntervalMs) return { skipped: 'throttled' };
  lastEnsureAt = now;

  try {
    const { ensureMcpIntegrations } = loadMcpIntegration();
    const results = ensureMcpIntegrations(wallePort, { homeDir: homeDir || env.HOME || process.env.HOME });
    const changed = results.filter(r => r.kind === 'mcp_config' && (r.action === 'added' || r.action === 'updated'));
    const instructionChanged = results.filter(r => r.kind === 'agent_instructions' && (r.action === 'added' || r.action === 'updated'));
    const errors = results.filter(r => r.action === 'error');
    if (changed.length) {
      logger.log(`[ctm] Auto-configured Wall-E MCP for ${changed.length} AI tool(s) before agent launch`);
    }
    if (instructionChanged.length) {
      logger.log(`[ctm] Updated Wall-E memory-routing instructions for ${instructionChanged.length} AI agent(s) before launch`);
    }
    if (errors.length) {
      logger.warn(`[ctm] Wall-E MCP auto-config skipped ${errors.length} invalid config file(s): ${errors.map(r => r.tool).join(', ')}`);
    }
    return { results, changed: changed.length, instructionChanged: instructionChanged.length, errors: errors.length };
  } catch (err) {
    logger.warn(`[ctm] Wall-E MCP auto-config failed: ${err.message}`);
    return { error: err.message };
  }
}

function _resetWalleMcpAutoConfigState() {
  lastEnsureAt = 0;
}

module.exports = {
  ensureWalleMcpForAgentSession,
  getMcpAutoConfigSkipReason,
  isMcpAutoConfigDisabled,
  isMcpCapableAgentCommand,
  _resetWalleMcpAutoConfigState,
};
