import type { AudioTranscriptionConfig } from '../models/media.js';
import type { Attachment } from '../channels/types.js';
import { isSupportedAudio, transcribeAudio } from '../models/media.js';
import { supportsAudioInput } from '../models/capabilities.js';
import { AgentOrchestrator, type DelegationConfig } from '../backends/index.js';
import { OutboundAttachmentCollector } from '../backends/native/attachments.js';
import type { ExternalBackend, ExternalBackendName } from '../backends/index.js';
import type { InboundMessage, OutboundMessage } from '../channels/index.js';
import { MemoryStore } from '../memory/index.js';
import type { Tool } from '../tools/types.js';
import { createMediaSendTool, createAgentDelegateTool } from '../tools/index.js';
import type { AgentDelegateDeps } from '../tools/index.js';
import { createSandboxedShellTool, createSandboxedProcessStartTool, SandboxManager } from '../sandbox/index.js';
import { MODEL_PROVIDERS, type Config, type ModelConfig, type ModelProvider } from '../config/index.js';
import { ModelRouter, type ModelTier } from '../models/index.js';
import { ToolRegistry, ToolExecutor } from '../tools/index.js';
import { SessionManager } from '../session/index.js';
import { AgentConfigRegistry, AgentRouter } from '../agents/index.js';
import type { CommandRegistry } from '../commands/index.js';
import type { ComponentRegistry } from '../intents/index.js';
import type { RoutingPolicy } from '../routing/index.js';
import { createClientFromConfig } from './models.js';
import type { SkillRegistry } from '../skills/index.js';
import { auditLogger } from '../audit/index.js';
import { randomUUID } from 'crypto';

function buildProviderConfigMap(config: Config): Partial<Record<ModelProvider, ModelConfig>> {
  const providerConfigs: Partial<Record<ModelProvider, ModelConfig>> = {};
  const modelConfigs: ModelConfig[] = [
    config.models.default,
    ...(config.models.fast ? [config.models.fast] : []),
    ...(config.models.complex ? [config.models.complex] : []),
    ...(config.models.local ? [config.models.local] : []),
    ...Object.values(config.models.local_providers ?? {}),
  ];

  for (const modelConfig of modelConfigs) {
    providerConfigs[modelConfig.provider] = modelConfig;
    if (modelConfig.fallback) {
      providerConfigs[modelConfig.fallback.provider] = modelConfig.fallback;
    }
  }

  return providerConfigs;
}

function tierFromUseCase(config: Config, useCaseRaw: unknown): ModelTier | undefined {
  if (typeof useCaseRaw !== 'string') {
    return undefined;
  }
  const normalized = useCaseRaw.trim().toLowerCase();
  if (!normalized) {
    return undefined;
  }

  const mappings: Array<{ tier: ModelTier; tags: string[] | undefined }> = [
    { tier: 'fast', tags: config.models.fast?.for },
    { tier: 'default', tags: config.models.default.for },
    { tier: 'complex', tags: config.models.complex?.for },
    { tier: 'local', tags: config.models.local?.for },
  ];

  for (const { tier, tags } of mappings) {
    if (!tags || tags.length === 0) {
      continue;
    }
    if (tags.some((tag) => tag.trim().toLowerCase() === normalized)) {
      return tier;
    }
  }

  return undefined;
}

function parseResearchPrefix(text: string): string | undefined {
  const trimmed = text.trim();
  const researchMatch = trimmed.match(/^research(?:\s*[:,-])?\s+(.+)$/i);
  if (researchMatch?.[1]) {
    return researchMatch[1].trim();
  }
  const lookupMatch = trimmed.match(/^(?:look\s+up|lookup)(?:\s*[:,-])?\s+(.+)$/i);
  if (lookupMatch?.[1]) {
    return lookupMatch[1].trim();
  }
  return undefined;
}

/**
 * Create the unified message handler for the channel registry.
 * Each channel+sender pair gets its own AgentOrchestrator backed by a persistent session.
 * The orchestrator wraps a NativeAgent and adds delegation to different model tiers.
 *
 * Returns both the message handler function and the agents map for usage tracking.
 */
export function createMessageRouter(deps: {
  sessionManager: SessionManager;
  modelRouter: ModelRouter;
  systemPrompt: string;
  toolRegistry: ToolRegistry;
  toolExecutor: ToolExecutor;
  config: Config;
  memoryStore?: MemoryStore;
  agentConfigRegistry?: AgentConfigRegistry;
  agentRouter?: AgentRouter;
  sandboxManager?: SandboxManager;
  commandRegistry?: CommandRegistry;
  intentRegistry?: ComponentRegistry;
  routingPolicy?: RoutingPolicy;
  skillRegistry?: SkillRegistry;
  externalBackends?: Partial<Record<ExternalBackendName, ExternalBackend>>;
  defaultName?: ExternalBackendName;
}): {
  handler: (msg: InboundMessage, reply: (response: OutboundMessage) => Promise<void>) => Promise<void>;
  agents: Map<string, { orchestrator: AgentOrchestrator; collector: OutboundAttachmentCollector }>;
} {
  // Cache agents by session ID + agent config name to avoid recreating on every message
  const agents = new Map<string, { orchestrator: AgentOrchestrator; collector: OutboundAttachmentCollector }>();
  const talkModeUntil = new Map<string, number>();

  function getOrCreateAgent(channel: string, senderId: string, metadata?: Record<string, unknown>, agentOverride?: string): { orchestrator: AgentOrchestrator; collector: OutboundAttachmentCollector } {
    // Resolve agent config name via routing (sender → channel → default fallback)
    const agentConfigName = agentOverride ?? deps.agentRouter?.resolve(channel, senderId);
    const agentConfig = agentConfigName ? deps.agentConfigRegistry?.get(agentConfigName) : undefined;

    // Cron job tier wins over agent config tier
    const tierFromMetadata = metadata?.modelTier as ModelTier | undefined;
    const tierFromUseCaseMetadata = tierFromUseCase(deps.config, metadata?.modelFor);

    // Include agent config name in cache key so different agents aren't shared
    let skillOverride = metadata?.skillOverride as string | undefined;
    if (skillOverride && deps.skillRegistry) {
      const s = deps.skillRegistry.get(skillOverride);
      if (!s || !s.available) {
        skillOverride = undefined;
      }
    }
    const baseSid = agentConfigName || skillOverride
      ? `${channel}:${senderId}:${agentConfigName ?? 'default'}:${skillOverride ?? 'none'}`
      : `${channel}:${senderId}`;
    const session = deps.sessionManager.getSession(channel, senderId);

    // Read per-session model tier override (persisted in SQLite)
    const sessionTierOverride = session.getConfig('modelTier') as ModelTier | undefined;

    // Resolution chain: metadata (explicit tier) → metadata modelFor -> session override -> agent config -> global default
    const effectiveTier = tierFromMetadata
      ?? tierFromUseCaseMetadata
      ?? sessionTierOverride
      ?? agentConfig?.modelTier
      ?? deps.config.agents.primary_tier
      ?? 'default';

    // Cache agents by tier too so switching tiers updates context-window heuristics.
    const sessionId = `${baseSid}:${effectiveTier}`;

    let entry = agents.get(sessionId);
    if (!entry) {
      // Use agent config overrides where available, falling back to global config
      let effectiveSystemPrompt = agentConfig?.systemPrompt ?? deps.systemPrompt;

      // If an active skill is specified, annotate the system prompt for clarity.
      const activeSkillName = skillOverride;
      const activeSkill = activeSkillName ? deps.skillRegistry?.get(activeSkillName) : undefined;
      if (activeSkillName) {
        effectiveSystemPrompt += `\n\n[Active skill: ${activeSkillName}. Tool access is capability-restricted and may be sandboxed.]`;
      }

      const modelsConfig = deps.config.models as Record<string, { provider?: string; model?: string; context_window?: number } | undefined>;
      const tierConfig = modelsConfig[effectiveTier] ?? deps.config.models.default;
      const effectiveProvider = tierConfig?.provider ?? deps.config.models.default.provider;
      const effectiveModelName = tierConfig?.model ?? deps.config.models.default.model;
      const effectiveContextWindow = tierConfig?.context_window ?? deps.config.models.default.context_window;

      const delegationConfig: DelegationConfig = {
        compaction: deps.config.agents.delegation.compaction ?? 'fast',
        memory_extraction: deps.config.agents.delegation.memory_extraction ?? 'fast',
        classification: deps.config.agents.delegation.classification ?? 'fast',
        tool_summarisation: deps.config.agents.delegation.tool_summarisation ?? 'fast',
        complex_reasoning: deps.config.agents.delegation.complex_reasoning ?? 'complex',
      };

      // Clone the tool registry and replace high-risk tools with sandboxed versions if configured.
      let effectiveToolRegistry = deps.toolRegistry;

      const skillEnvPreference = activeSkill?.manifest.permissions?.execution_environment;
      const executionEnvironment: 'host' | 'sandbox' = skillOverride
        ? (skillEnvPreference === 'host'
          ? 'host'
          : (deps.sandboxManager && deps.config.sandbox.enabled ? 'sandbox' : 'host'))
        : 'host';

      const useSandboxTools = executionEnvironment === 'sandbox' && deps.sandboxManager && deps.config.sandbox.enabled;

      if ((agentConfig?.sandbox || Boolean(skillOverride)) && useSandboxTools) {
        effectiveToolRegistry = deps.toolRegistry.clone();
        // Lazy sandbox: create the sandboxed tools with a deferred sandbox reference
        // The sandbox is created on first use via SandboxManager.getOrCreate()
        const sandboxSessionId = sessionId;
        const sandboxManager = deps.sandboxManager;
        if (!sandboxManager) {
          throw new Error('Sandbox manager unavailable for sandboxed agent execution');
        }

        // Create a proxy sandbox that lazily initializes
        const lazySandboxShell: Tool = {
          name: 'shell.exec',
          description: 'Execute a shell command inside a sandboxed container and return stdout/stderr.',
          inputSchema: {
            type: 'object',
            properties: {
              command: { type: 'string', description: 'The shell command to execute' },
              cwd: { type: 'string', description: 'Working directory inside the container (optional)' },
              timeout: { type: 'number', description: 'Timeout in milliseconds (default 30000)' },
            },
            required: ['command'],
          },
          execute: async (rawArgs: unknown) => {
            const sandbox = await sandboxManager.getOrCreate(sandboxSessionId);
            const tool = createSandboxedShellTool(sandbox);
            return tool.execute(rawArgs);
          },
        };

        const lazySandboxProcess: Tool = {
          name: 'process.start',
          description: 'Start a command in the background inside a sandboxed container.',
          inputSchema: {
            type: 'object',
            properties: {
              command: { type: 'string', description: 'The shell command to run in the background' },
              cwd: { type: 'string', description: 'Working directory inside the container (optional)' },
            },
            required: ['command'],
          },
          execute: async (rawArgs: unknown) => {
            const sandbox = await sandboxManager.getOrCreate(sandboxSessionId);
            const tool = createSandboxedProcessStartTool(sandbox);
            return tool.execute(rawArgs);
          },
        };

        effectiveToolRegistry.replace(lazySandboxShell);
        effectiveToolRegistry.replace(lazySandboxProcess);
      }

      // Create an attachment collector for this agent session
      const collector = new OutboundAttachmentCollector();

      // Clone the tool registry to register the media.send tool bound to this collector
      effectiveToolRegistry = effectiveToolRegistry.clone();
      effectiveToolRegistry.register(createMediaSendTool(collector));

      // Register agent.delegate tool with lazy orchestrator reference (resolved after construction)
      let resolveOrchestrator: ((o: AgentOrchestrator) => void) | undefined;
      if (deps.agentConfigRegistry && deps.agentConfigRegistry.list().length > 0) {
        let lazyOrchestrator: AgentOrchestrator | null = null;
        resolveOrchestrator = (o: AgentOrchestrator) => { lazyOrchestrator = o; };
        effectiveToolRegistry.register(createAgentDelegateTool({
          registry: deps.agentConfigRegistry,
          get orchestrator(): AgentOrchestrator {
            if (!lazyOrchestrator) {
              throw new Error('Agent orchestrator not yet initialized');
            }
            return lazyOrchestrator;
          },
        } as AgentDelegateDeps));
      }

      const toolPolicyContext = {
        agent: effectiveTier,
        provider: effectiveProvider,
        sessionId: session.id,
        channel,
        sender: senderId,
        tier: effectiveTier,
        autonomyLevel: deps.config.agents.autonomy_level ?? 'standard',
        skillName: activeSkillName,
        skillPermissions: activeSkill?.manifest.permissions,
        allowedSecretScopes: activeSkill?.manifest.permissions?.secrets,
        executionEnvironment,
      };

      const orchestrator = new AgentOrchestrator({
        modelRouter: deps.modelRouter,
        systemPrompt: effectiveSystemPrompt,
        session,
        toolRegistry: effectiveToolRegistry,
        toolExecutor: deps.toolExecutor,
        primaryTier: effectiveTier,
        delegation: delegationConfig,
        maxDelegationDepth: deps.config.agents.max_delegation_depth ?? 3,
        maxIterations: deps.config.agents.max_iterations,
        compaction: deps.config.compaction.enabled ? {
          thresholdPct: deps.config.compaction.threshold_pct,
          keepTurns: deps.config.compaction.keep_turns,
          summaryMaxTokens: deps.config.compaction.summary_max_tokens,
          importanceThreshold: deps.config.compaction.importance_threshold,
          proactive: {
            enabled: deps.config.compaction.proactive.enabled,
            warnPct: deps.config.compaction.proactive.warn_pct,
            checkpointPct: deps.config.compaction.proactive.checkpoint_pct,
            autoCompactPct: deps.config.compaction.proactive.auto_compact_pct,
            checkpointCooldownMs: deps.config.compaction.proactive.checkpoint_cooldown_ms,
            memoryNamespace: deps.config.compaction.proactive.memory_namespace,
          },
        } : undefined,
        modelName: effectiveModelName,
        contextWindow: effectiveContextWindow,
        memoryStore: deps.memoryStore,
        memoryAutoExtract: deps.config.memory?.auto_extract,
        memoryInjectionStrategy: deps.config.memory?.injection_strategy,
        memoryMaxInjectionTokens: deps.config.memory?.max_injection_tokens,
        toolPolicyContext,
        attachmentCollector: collector,
      });
      // Resolve the lazy orchestrator reference for agent.delegate
      resolveOrchestrator?.(orchestrator);

      entry = { orchestrator, collector };
      agents.set(sessionId, entry);
    }
    return entry;
  }

  const handler = async (msg: InboundMessage, reply: (response: OutboundMessage) => Promise<void>): Promise<void> => {
    let incomingText = msg.text;
    const talkMode = deps.config.audio?.talk_mode;
    if (talkMode?.enabled && incomingText.trim().length > 0) {
      const key = `${msg.channel}:${msg.senderId}`;
      const now = Date.now();
      const timeoutMs = talkMode.timeout_ms;
      const currentUntil = talkModeUntil.get(key) ?? 0;
      const lower = incomingText.trim().toLowerCase();

      if (talkMode.allow_manual_toggle) {
        if (lower === '/talk on') {
          talkModeUntil.set(key, now + timeoutMs);
          await reply({ text: `Talk mode enabled for ${Math.ceil(timeoutMs / 1000)}s.`, replyTo: msg.id });
          return;
        }
        if (lower === '/talk off') {
          talkModeUntil.delete(key);
          await reply({ text: 'Talk mode disabled.', replyTo: msg.id });
          return;
        }
        if (lower === '/talk status') {
          if (currentUntil <= now) {
            await reply({ text: 'Talk mode is idle (wake phrase required).', replyTo: msg.id });
          } else {
            await reply({ text: `Talk mode active for ${Math.ceil((currentUntil - now) / 1000)}s.`, replyTo: msg.id });
          }
          return;
        }
      }

      const phrase = talkMode.wake_phrase.trim();
      const wakeRegex = phrase
        ? new RegExp(`^\\s*${escapeRegex(phrase)}(?:[\\s,:!.-]+)?`, 'i')
        : null;
      const wakeMatched = Boolean(wakeRegex && wakeRegex.test(incomingText));

      if (wakeMatched && wakeRegex) {
        talkModeUntil.set(key, now + timeoutMs);
        incomingText = incomingText.replace(wakeRegex, '').trim();
        if (!incomingText) {
          await reply({ text: `Listening. Talk mode active for ${Math.ceil(timeoutMs / 1000)}s.`, replyTo: msg.id });
          return;
        }
      } else if (currentUntil > now) {
        talkModeUntil.set(key, now + timeoutMs);
      } else {
        return;
      }
    }

    let intentAgentOverride: string | undefined;
    let intentSkillOverride: string | undefined;
    if (!deps.config.intents?.enabled && deps.agentConfigRegistry?.get('research')) {
      const researchTask = parseResearchPrefix(incomingText);
      if (researchTask) {
        intentAgentOverride = 'research';
        incomingText = researchTask;
      }
    }
    if (deps.config.intents?.enabled && deps.intentRegistry) {
      const intentMatch = deps.intentRegistry.match(incomingText);

      if (intentMatch?.rule.target.type === 'agent') {
        let confidence = intentMatch.score;
        if (deps.config.history_index?.enabled) {
          const historySessionId = `${msg.channel}:${msg.senderId}`;
          const historyHits = deps.sessionManager.searchHistory(msg.text, {
            sessionId: historySessionId,
            limit: 1,
          });
          if (historyHits.length > 0 && historyHits[0].score >= (deps.config.history_index.min_score ?? 0.15)) {
            confidence = Math.min(1, confidence + (deps.config.history_index.routing_boost ?? 0.05));
          }
        }

        const decision = deps.routingPolicy
          ? deps.routingPolicy.decide({ confidence })
          : { path: 'fast' as const, reason: 'high_confidence' as const };

        console.log(`[routing] intent=${intentMatch.rule.name} confidence=${confidence.toFixed(3)} path=${decision.path} reason=${decision.reason}`);

        if (decision.path === 'fast') {
          intentAgentOverride = intentMatch.rule.target.name;
        }
      }

      if (intentMatch?.rule.target.type === 'skill') {
        let confidence = intentMatch.score;
        const decision = deps.routingPolicy
          ? deps.routingPolicy.decide({ confidence })
          : { path: 'fast' as const, reason: 'high_confidence' as const };

        console.log(`[routing] intent=${intentMatch.rule.name} confidence=${confidence.toFixed(3)} path=${decision.path} reason=${decision.reason}`);

        if (decision.path === 'fast') {
          intentSkillOverride = intentMatch.rule.target.name;
        }
      }
    }

    const effectiveMetadata = {
      ...(msg.metadata ?? {}),
      ...(intentSkillOverride ? { skillOverride: intentSkillOverride } : {}),
    };

    const agentConfigName = intentAgentOverride ?? deps.agentRouter?.resolve(msg.channel, msg.senderId);
    const agentConfig = agentConfigName ? deps.agentConfigRegistry?.get(agentConfigName) : undefined;
    const { orchestrator: agent, collector } = getOrCreateAgent(msg.channel, msg.senderId, effectiveMetadata, agentConfigName);

    const commandInput = msg.metadata?.isCommand && typeof msg.metadata.command === 'string'
      ? `/${msg.metadata.command}${msg.metadata.commandArgs ? ` ${msg.metadata.commandArgs}` : ''}`
      : incomingText;
    const metadataCommand = typeof msg.metadata?.command === 'string' ? msg.metadata.command : undefined;
    const parsedCommand = msg.metadata?.isCommand
      ? metadataCommand
      : commandInput.startsWith('/') ? commandInput.slice(1).split(/\s+/, 1)[0] : undefined;
    auditLogger?.userAction({
      session_id: `${msg.channel}:${msg.senderId}`,
      channel: msg.channel,
      sender: msg.senderId,
      source: 'channel',
      action_type: parsedCommand ? 'command' : 'message',
      content_length: commandInput.length,
      attachments_count: msg.attachments?.length ?? 0,
      command: parsedCommand,
    });

    if (deps.commandRegistry && deps.commandRegistry.isCommand(commandInput)) {
      const session = deps.sessionManager.getSession(msg.channel, msg.senderId);
      const commandResult = await deps.commandRegistry.execute(commandInput, {
        channel: msg.channel,
        senderId: msg.senderId,
        sessionId: session.id,
        rawInput: commandInput,
        services: {
          getStatus: () => {
            const requestedBackend = agentConfig?.backend ?? deps.defaultName;
            const backend = requestedBackend && requestedBackend !== 'native' && deps.externalBackends?.[requestedBackend]
              ? requestedBackend
              : 'native';
            return `Flynn is running. Active model tier: ${agent.getModelTier()}. Backend: ${backend}`;
          },
          getUsage: () => {
            const usage = agent.getUsage();
            const lines = [
              '**Token Usage**',
              '',
              `Primary: ${usage.primary.inputTokens.toLocaleString()} in / ${usage.primary.outputTokens.toLocaleString()} out (${usage.primary.calls} calls)`,
            ];

            const delegationEntries = Object.entries(usage.delegation);
            if (delegationEntries.length > 0) {
              lines.push('');
              lines.push('Delegation:');
              for (const [tier, stats] of delegationEntries) {
                lines.push(`  ${tier}: ${stats.inputTokens.toLocaleString()} in / ${stats.outputTokens.toLocaleString()} out (${stats.calls} calls)`);
              }
            }

            lines.push('');
            lines.push(`**Total:** ${usage.total.inputTokens.toLocaleString()} in / ${usage.total.outputTokens.toLocaleString()} out (${usage.total.calls} calls)`);

            if (usage.total.estimatedCost > 0) {
              lines.push(`**Estimated cost:** $${usage.total.estimatedCost.toFixed(4)}`);
            }

            return lines.join('\n');
          },
          getModel: () => {
            const currentTier = agent.getModelTier();
            const sessionOverride = session.getConfig('modelTier');
            const available = deps.modelRouter.getAvailableTiers();
            const labels = deps.modelRouter.getAllLabels();
            const lines = [`Active tier: ${currentTier}${sessionOverride ? ' (session override)' : ''}`];
            for (const tier of available) {
              const label = labels[tier] ?? 'unknown';
              const marker = tier === currentTier ? ' ←' : '';
              lines.push(`  ${tier}: ${label}${marker}`);
            }
            return lines.join('\n');
          },
          setModel: (tier) => {
            const raw = tier.trim();
            if (!raw) {
              return 'Usage: /model <tier>  OR  /model <tier> <provider/model>  OR  /model <tier> reset';
            }

            const parts = raw.split(/\s+/);
            const requestedTier = parts[0];

            const validTiers = deps.modelRouter.getAvailableTiers();
            if (!validTiers.includes(requestedTier as ModelTier)) {
              return `Model tier not available: ${requestedTier}`;
            }

            const modelTier = requestedTier as ModelTier;

            // /model <tier>
            if (parts.length === 1) {
              session.setConfig('modelTier', modelTier);
              agent.setModelTier(modelTier);
              const label = deps.modelRouter.getLabel(modelTier);
              return `Switched to model: ${modelTier} (${label})`;
            }

            const arg2 = parts[1];

            // /model <tier> reset — restore configured provider/model and re-enable fallbacks
            if (arg2.toLowerCase() === 'reset') {
              const configured: ModelConfig | undefined = modelTier === 'default'
                ? deps.config.models.default
                : modelTier === 'fast'
                  ? deps.config.models.fast
                  : modelTier === 'complex'
                    ? deps.config.models.complex
                    : modelTier === 'local'
                      ? deps.config.models.local
                      : undefined;
              if (!configured) {
                return `No configured model for tier: ${modelTier}`;
              }

              const client = createClientFromConfig(configured);
              const label = `${configured.provider}/${configured.model}`;
              deps.modelRouter.setClient(modelTier, client, label);
              deps.modelRouter.setTierStrict(modelTier, false);
              session.setConfig('modelTier', modelTier);
              agent.setModelTier(modelTier);
              return `Reset ${modelTier} to: ${label}`;
            }

            // /model <tier> <provider/model>
            const providerModel = arg2;
            if (!providerModel.includes('/')) {
              return 'Invalid format. Use: /model <tier> <provider/model> (e.g. /model default github/gpt-5-mini)';
            }

            const slashIdx = providerModel.indexOf('/');
            const provider = providerModel.slice(0, slashIdx);
            const model = providerModel.slice(slashIdx + 1);

            if (!MODEL_PROVIDERS.includes(provider as ModelProvider)) {
              return `Unknown provider "${provider}". Known providers: ${MODEL_PROVIDERS.join(', ')}`;
            }

            const providerType = provider as ModelProvider;
            const providerConfigs = buildProviderConfigMap(deps.config);
            const template = providerConfigs[providerType];

            try {
              const client = createClientFromConfig(
                template
                  ? { ...template, provider: providerType, model }
                  : { provider: providerType, model },
              );

              deps.modelRouter.setClient(modelTier, client, providerModel);
              deps.modelRouter.setTierStrict(modelTier, true);
              session.setConfig('modelTier', modelTier);
              agent.setModelTier(modelTier);

              const lines = [
                `Set ${modelTier} to: ${providerModel}`,
                `Fallbacks for ${modelTier} disabled (strict tier mode).`,
              ];
              if (parts.length > 2) {
                lines.push(`Note: ignored extra args: ${parts.slice(2).join(' ')}`);
              }
              return lines.join('\n');
            } catch (error) {
              const message = error instanceof Error ? error.message : String(error);
              return `Failed to switch ${modelTier} to ${providerModel}: ${message}`;
            }
          },
          compact: async () => {
            const result = await agent.compact();
            if (result && result.compactedCount > 0) {
              return `Compacted ${result.compactedCount} messages: ${result.tokensBefore} → ${result.tokensAfter} tokens`;
            }
            return 'Nothing to compact.';
          },
          reset: () => {
            agent.reset();
            session.deleteConfig('modelTier');
            return '';
          },

          delegateAgent: async (agentName: string, task: string) => {
            const target = agentName.trim();
            const message = task.trim();
            if (!target || !message) {
              return 'Usage: /research <question or task>';
            }
            if (!deps.agentConfigRegistry) {
              return 'No agent configurations are registered. Add agent_configs.research in config.';
            }
            const agentConfig = deps.agentConfigRegistry.get(target);
            if (!agentConfig) {
              const available = deps.agentConfigRegistry.list().map((c) => c.name);
              return `Agent "${target}" not found. Available agents: ${available.length > 0 ? available.join(', ') : 'none'}`;
            }

            const tier: ModelTier = agentConfig.modelTier ?? 'default';
            const systemPrompt = agentConfig.systemPrompt
              ?? `You are a sub-agent named "${target}". Complete the assigned task concisely and accurately.`;

            const result = await agent.delegate({
              tier,
              systemPrompt,
              message,
              maxTokens: 4096,
            });

            return `[Agent: ${target} | Tier: ${result.tier} | Tokens: ${result.usage.inputTokens}+${result.usage.outputTokens}]\n\n${result.content}`;
          },

          getElevation: () => {
            const untilRaw = session.getConfig('elevation.until_ms');
            const reason = session.getConfig('elevation.reason') ?? '';
            const id = session.getConfig('elevation.id') ?? '';
            if (!untilRaw || !id) {
              return 'Elevated mode: off';
            }
            const untilMs = Number.parseInt(untilRaw, 10);
            if (!Number.isFinite(untilMs)) {
              return 'Elevated mode: off';
            }
            const now = Date.now();
            if (untilMs <= now) {
              session.deleteConfig('elevation.until_ms');
              session.deleteConfig('elevation.reason');
              session.deleteConfig('elevation.id');
              auditLogger?.securityElevationExpired({
                session_id: session.id,
                channel: msg.channel,
                sender: msg.senderId,
                elevation_id: id,
                until_ms: untilMs,
                reason: reason || undefined,
              });
              return 'Elevated mode: off (expired)';
            }
            const remainingMs = untilMs - now;
            const remainingSec = Math.ceil(remainingMs / 1000);
            return `Elevated mode: on (${remainingSec}s remaining)${reason ? ` — ${reason}` : ''}`;
          },

          setElevation: (input: string) => {
            const raw = input.trim();
            const parts = raw.split(/\s+/);
            const hasYes = parts.includes('--yes') || parts.includes('--confirm');
            const filtered = parts.filter(p => p !== '--yes' && p !== '--confirm');

            if (filtered.length === 0) {
              return 'Usage: /elevate <duration> <reason...> --yes | /elevate off --yes';
            }

            if (filtered[0] === 'off') {
              if (!hasYes) {
                return 'Refusing to disable elevation without explicit confirmation. Use: /elevate off --yes';
              }
              const existingId = session.getConfig('elevation.id') ?? randomUUID();
              const existingUntil = session.getConfig('elevation.until_ms');
              const existingReason = session.getConfig('elevation.reason') ?? '';
              session.deleteConfig('elevation.until_ms');
              session.deleteConfig('elevation.reason');
              session.deleteConfig('elevation.id');
              auditLogger?.securityElevationDisabled({
                session_id: session.id,
                channel: msg.channel,
                sender: msg.senderId,
                elevation_id: existingId,
                until_ms: existingUntil ? Number.parseInt(existingUntil, 10) : undefined,
                reason: existingReason || undefined,
              });
              return 'Elevated mode: off';
            }

            if (!hasYes) {
              return 'Refusing to enable elevation without explicit confirmation. Use: /elevate <duration> <reason...> --yes';
            }

            const dur = filtered[0];
            const reason = filtered.slice(1).join(' ').trim();
            const ttlMs = (() => {
              const m = dur.match(/^(\d+)([smhd])$/i);
              if (!m) {
                return null;
              }
              const n = Number.parseInt(m[1], 10);
              if (!Number.isFinite(n) || n <= 0) {
                return null;
              }
              const unit = m[2].toLowerCase();
              if (unit === 's') {return n * 1000;}
              if (unit === 'm') {return n * 60_000;}
              if (unit === 'h') {return n * 3_600_000;}
              if (unit === 'd') {return n * 86_400_000;}
              return null;
            })();

            if (!ttlMs) {
              return 'Invalid duration. Use one of: 30s, 10m, 1h, 1d';
            }

            const untilMs = Date.now() + ttlMs;
            const id = randomUUID();
            session.setConfig('elevation.until_ms', String(untilMs));
            session.setConfig('elevation.id', id);
            if (reason) {
              session.setConfig('elevation.reason', reason);
            } else {
              session.deleteConfig('elevation.reason');
            }

            auditLogger?.securityElevationEnabled({
              session_id: session.id,
              channel: msg.channel,
              sender: msg.senderId,
              elevation_id: id,
              until_ms: untilMs,
              ttl_ms: ttlMs,
              reason: reason || undefined,
            });

            return `Elevated mode: on until ${new Date(untilMs).toISOString()}`;
          },

          getQueue: () => {
            const mode = session.getConfig('queue.mode') ?? deps.config.server.queue.mode;
            const cap = session.getConfig('queue.cap') ?? String(deps.config.server.queue.cap);
            const overflow = session.getConfig('queue.overflow') ?? deps.config.server.queue.overflow;
            const debounceMs = session.getConfig('queue.debounce_ms') ?? String(deps.config.server.queue.debounce_ms);
            const summarizeOverflow = session.getConfig('queue.summarize_overflow') ?? String(deps.config.server.queue.summarize_overflow);
            const source = session.getConfig('queue.mode')
              || session.getConfig('queue.cap')
              || session.getConfig('queue.overflow')
              || session.getConfig('queue.debounce_ms')
              || session.getConfig('queue.summarize_overflow')
              ? 'session override'
              : 'default config';
            return [
              '**Queue policy**',
              `mode: ${mode}`,
              `cap: ${cap}`,
              `overflow: ${overflow}`,
              `debounce_ms: ${debounceMs}`,
              `summarize_overflow: ${summarizeOverflow}`,
              `source: ${source}`,
            ].join('\n');
          },

          setQueue: (input: string) => {
            const [rawKey, ...rest] = input.trim().split(/\s+/);
            const value = rest.join(' ').trim();
            if (!rawKey || !value) {
              return 'Usage: /queue <mode|cap|overflow|debounce_ms|summarize_overflow> <value>';
            }
            const key = rawKey.toLowerCase();
            if (key === 'mode') {
              if (!['collect', 'followup', 'steer', 'steer_backlog', 'interrupt'].includes(value)) {
                return 'Invalid mode. Use one of: collect, followup, steer, steer_backlog, interrupt';
              }
              session.setConfig('queue.mode', value);
              return `Set queue.mode=${value} for this session`;
            }
            if (key === 'cap') {
              const cap = Number.parseInt(value, 10);
              if (!Number.isFinite(cap) || cap < 1 || cap > 1000) {
                return 'Invalid cap. Use an integer between 1 and 1000';
              }
              session.setConfig('queue.cap', String(cap));
              return `Set queue.cap=${cap} for this session`;
            }
            if (key === 'overflow') {
              if (value !== 'drop_old' && value !== 'drop_new') {
                return 'Invalid overflow. Use drop_old or drop_new';
              }
              session.setConfig('queue.overflow', value);
              return `Set queue.overflow=${value} for this session`;
            }
            if (key === 'debounce_ms') {
              const debounceMs = Number.parseInt(value, 10);
              if (!Number.isFinite(debounceMs) || debounceMs < 0 || debounceMs > 60_000) {
                return 'Invalid debounce_ms. Use an integer between 0 and 60000';
              }
              session.setConfig('queue.debounce_ms', String(debounceMs));
              return `Set queue.debounce_ms=${debounceMs} for this session`;
            }
            if (key === 'summarize_overflow') {
              const normalized = value.toLowerCase();
              if (normalized !== 'true' && normalized !== 'false') {
                return 'Invalid summarize_overflow. Use true or false';
              }
              session.setConfig('queue.summarize_overflow', normalized);
              return `Set queue.summarize_overflow=${normalized} for this session`;
            }
            return 'Unknown queue key. Use one of: mode, cap, overflow, debounce_ms, summarize_overflow';
          },

          resetQueue: () => {
            session.deleteConfig('queue.mode');
            session.deleteConfig('queue.cap');
            session.deleteConfig('queue.overflow');
            session.deleteConfig('queue.debounce_ms');
            session.deleteConfig('queue.summarize_overflow');
            return 'Reset session queue overrides.';
          },
        },
      });

      if (commandResult.handled) {
        if (commandResult.text.trim()) {
          await reply({ text: commandResult.text, replyTo: msg.id });
        }
        return;
      }
    }

    try {
      // Determine if the active model supports native audio input
      let effectiveTier: string = deps.config.agents.primary_tier ?? 'default';
      const session = deps.sessionManager.getSession(msg.channel, msg.senderId);
      const sessionTierOverride = session.getConfig('modelTier');
      const tierFromUseCaseMetadata = tierFromUseCase(deps.config, msg.metadata?.modelFor);

      if (msg.metadata?.modelTier) {
        effectiveTier = msg.metadata.modelTier as string;
      } else if (tierFromUseCaseMetadata) {
        effectiveTier = tierFromUseCaseMetadata;
      } else if (sessionTierOverride) {
        effectiveTier = sessionTierOverride;
      } else if (deps.agentRouter && deps.agentConfigRegistry) {
        const agentName = deps.agentRouter.resolve(msg.channel, msg.senderId);
        if (agentName) {
          const agentCfg = deps.agentConfigRegistry.get(agentName);
          if (agentCfg?.modelTier) {
            effectiveTier = agentCfg.modelTier;
          }
        }
      }

      // Look up provider/model for the effective tier
      const modelsConfig = deps.config.models as Record<string, { provider?: string; model?: string } | undefined>;
      const tierConfig = modelsConfig[effectiveTier] ?? deps.config.models.default;
      const modelProvider = tierConfig?.provider ?? deps.config.models.default.provider;
      const modelName = tierConfig?.model ?? deps.config.models.default.model;
      const supportsAudioOverride = (tierConfig as Record<string, unknown> | undefined)?.supports_audio as boolean | undefined;
      const nativeAudioSupported = supportsAudioInput(modelProvider, modelName, supportsAudioOverride);

      let messageText = incomingText;
      let attachments = msg.attachments;
      const audioAttachments = (msg.attachments ?? []).filter((a: Attachment) => isSupportedAudio(a));

      if (audioAttachments.length > 0 && !nativeAudioSupported) {
        // Model doesn't support native audio — transcribe via Whisper and strip audio attachments
        const audioConfig: AudioTranscriptionConfig | undefined = deps.config.audio?.enabled && deps.config.audio.provider
          ? {
            endpoint: deps.config.audio.provider.endpoint,
            apiKey: deps.config.audio.provider.api_key,
            model: deps.config.audio.provider.model,
          }
          : undefined;

        if (!audioConfig?.endpoint) {
          // Without transcription, we cannot safely send audio to a non-audio-capable model.
          // Fast-path a deterministic, user-friendly reply instead of invoking the agent loop.
          await reply({
            text:
              [
                'I received your voice message, but I cannot transcribe it yet because audio transcription is not configured.',
                '',
                'To enable voice messages, set `audio.enabled: true` and configure an `audio.provider` in `config.yaml` (OpenAI/Groq/custom Whisper-compatible `/v1/audio/transcriptions`).',
                '',
                'Workarounds:',
                '1. Paste the transcription text.',
                '2. Upload the audio file somewhere and send me a direct URL.',
              ].join('\n'),
            replyTo: msg.id,
          });
          return;
        }

        for (const att of audioAttachments) {
          const transcript = await transcribeAudio(att, audioConfig);
          messageText = `[Voice message]: ${transcript}\n\n${messageText}`;
        }
        // Remove audio attachments so buildUserMessage doesn't create audio content parts
        attachments = (msg.attachments ?? []).filter((a: Attachment) => !isSupportedAudio(a));
        if (attachments.length === 0) { attachments = undefined; }
      }
      // If native audio IS supported, we pass attachments through unchanged —
      // buildUserMessage() in the agent will create native audio content parts

      const requestedBackend = agentConfig?.backend ?? deps.defaultName;
      const selectedBackend = requestedBackend && requestedBackend !== 'native'
        ? deps.externalBackends?.[requestedBackend]
        : undefined;

      if (selectedBackend && (!attachments || attachments.length === 0)) {
        try {
          const history = toExternalHistory(session.getHistory());
          session.addMessage({ role: 'user', content: messageText });
          const response = await selectedBackend.process({
            prompt: messageText,
            history,
          });
          session.addMessage({ role: 'assistant', content: response });
          await reply({ text: response, replyTo: msg.id });
          return;
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error);
          console.warn(`External backend "${selectedBackend.name}" failed, falling back to native: ${message}`);
        }
      }

      let response: string;
      try {
        response = await agent.process(messageText, attachments);
      } catch (error) {
        const currentTier = agent.getModelTier();
        const canEscalate = deps.config.agents.auto_escalate && currentTier !== 'complex';
        if (!canEscalate) {
          throw error;
        }

        console.warn(`Auto-escalating session ${msg.channel}:${msg.senderId} from ${currentTier} to complex after processing failure.`);
        agent.setModelTier('complex');
        response = await agent.process(messageText, attachments);
      }
      const outboundAttachments = collector.drain();
      await reply({
        text: response,
        replyTo: msg.id,
        attachments: outboundAttachments.length > 0 ? outboundAttachments : undefined,
      });
    } catch (error) {
      console.error(`Error processing message from ${msg.channel}:${msg.senderId}:`, error);
      await reply({
        text: 'Sorry, an error occurred while processing your message.',
        replyTo: msg.id,
      });
    }
  };

  return { handler, agents };
}

function escapeRegex(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function toExternalHistory(history: Array<{ role: string; content: unknown }>): Array<{ role: 'user' | 'assistant'; content: string }> {
  return history
    .filter((message): message is { role: 'user' | 'assistant'; content: unknown } => (
      message.role === 'user' || message.role === 'assistant'
    ))
    .map((message) => ({
      role: message.role,
      content: messageContentToText(message.content),
    }))
    .filter((message) => message.content.trim().length > 0);
}

function messageContentToText(content: unknown): string {
  if (typeof content === 'string') {
    return content;
  }
  if (!Array.isArray(content)) {
    return '';
  }
  return content
    .map((part) => {
      if (!part || typeof part !== 'object') {
        return '';
      }
      const partObj = part as { type?: string; text?: string };
      if (partObj.type === 'text' && typeof partObj.text === 'string') {
        return partObj.text;
      }
      return '';
    })
    .filter(Boolean)
    .join('\n');
}
