import { describe, it, expect, vi, afterEach } from 'vitest';
import { AgentRouter } from '../agents/router.js';
import { AgentConfigRegistry } from '../agents/registry.js';
import type { ModelTier } from '../models/router.js';
import { createMessageRouter } from './routing.js';
import { AgentOrchestrator } from '../backends/index.js';
import { CommandRegistry, registerBuiltinCommands } from '../commands/index.js';
import { ComponentRegistry } from '../intents/index.js';
import { RoutingPolicy } from '../routing/index.js';

describe('daemon agent routing integration', () => {
  it('resolves agent config for channel messages', () => {
    const registry = new AgentConfigRegistry();
    registry.loadFromConfig({
      assistant: { system_prompt: 'Be helpful.', model_tier: 'default', tool_profile: 'messaging', sandbox: false },
      coder: { system_prompt: 'Write code.', model_tier: 'complex', tool_profile: 'coding', sandbox: true },
    });

    const router = new AgentRouter({
      default_agent: 'assistant',
      channels: { discord: 'coder' },
      senders: { 'telegram:admin': 'coder' },
    });

    // Discord user gets coder
    const discordAgent = router.resolve('discord', 'user123');
    expect(discordAgent).toBe('coder');
    expect(registry.get(discordAgent!)!.systemPrompt).toBe('Write code.');

    // Telegram admin gets coder
    const telegramAdmin = router.resolve('telegram', 'admin');
    expect(telegramAdmin).toBe('coder');

    // Random telegram user gets assistant
    const telegramUser = router.resolve('telegram', 'random');
    expect(telegramUser).toBe('assistant');
    expect(registry.get(telegramUser!)!.systemPrompt).toBe('Be helpful.');
  });

  it('uses default agent when no routing configured', () => {
    const router = new AgentRouter({ channels: {}, senders: {} });
    expect(router.resolve('telegram', '123')).toBeUndefined();
  });

  it('model tier precedence: metadata > agent config > global default', () => {
    // This test documents the tier resolution precedence used by createMessageRouter.
    // The actual resolution logic: tierFromMetadata ?? agentConfig?.modelTier ?? primary_tier ?? 'default'
    function resolveTier(
      metadataTier: ModelTier | undefined,
      agentTier: ModelTier | undefined,
      globalTier: ModelTier | undefined,
    ): ModelTier {
      return metadataTier ?? agentTier ?? globalTier ?? 'default';
    }

    // With all three set, metadata wins
    expect(resolveTier('fast', 'complex', 'default')).toBe('fast');

    // Without metadata, agent config wins
    expect(resolveTier(undefined, 'complex', 'default')).toBe('complex');

    // Without metadata or agent config, global wins
    expect(resolveTier(undefined, undefined, 'default')).toBe('default');

    // Without anything, falls back to 'default'
    expect(resolveTier(undefined, undefined, undefined)).toBe('default');
  });
});

describe('daemon command fast-path integration', () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('handles known reset command without calling agent.process', async () => {
    const processSpy = vi.spyOn(AgentOrchestrator.prototype, 'process');
    const session = {
      id: 'telegram:user-1',
      addMessage: vi.fn(),
      getHistory: vi.fn(() => []),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
      getConfig: vi.fn(() => undefined),
      setConfig: vi.fn(),
      deleteConfig: vi.fn(),
    };

    const commandRegistry = new CommandRegistry();
    registerBuiltinCommands(commandRegistry);

    const router = createMessageRouter({
      sessionManager: {
        getSession: vi.fn(() => session),
      } as any,
      modelRouter: {
        getAvailableTiers: () => ['fast', 'default', 'complex', 'local'],
        getAllLabels: () => ({ fast: 'fast', default: 'default', complex: 'complex', local: 'local' }),
        getLabel: (tier: string) => tier,
      } as any,
      systemPrompt: 'test prompt',
      toolRegistry: {
        clone() { return this; },
        register: vi.fn(),
      } as any,
      toolExecutor: {} as any,
      config: {
        agents: {
          primary_tier: 'default',
          delegation: {
            compaction: 'fast',
            memory_extraction: 'fast',
            classification: 'fast',
            tool_summarisation: 'fast',
            complex_reasoning: 'complex',
          },
          max_delegation_depth: 3,
          max_iterations: 10,
        },
        compaction: { enabled: false },
        models: { default: { provider: 'anthropic', model: 'claude' } },
      } as any,
      commandRegistry,
    });

    const reply = vi.fn(async () => {});
    await router.handler({
      id: 'm1',
      channel: 'telegram',
      senderId: 'user-1',
      text: '/reset',
      metadata: { isCommand: true, command: 'reset' },
    } as any, reply);

    expect(processSpy).not.toHaveBeenCalled();
    expect(session.deleteConfig).toHaveBeenCalledWith('modelTier');
  });

  it('handles model command via fast-path and persists tier override', async () => {
    const processSpy = vi.spyOn(AgentOrchestrator.prototype, 'process');
    const setModelTierSpy = vi.spyOn(AgentOrchestrator.prototype, 'setModelTier');
    const session = {
      id: 'telegram:user-4',
      addMessage: vi.fn(),
      getHistory: vi.fn(() => []),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
      getConfig: vi.fn(() => undefined),
      setConfig: vi.fn(),
      deleteConfig: vi.fn(),
    };

    const commandRegistry = new CommandRegistry();
    registerBuiltinCommands(commandRegistry);

    const router = createMessageRouter({
      sessionManager: {
        getSession: vi.fn(() => session),
      } as any,
      modelRouter: {
        getAvailableTiers: () => ['fast', 'default', 'complex', 'local'],
        getAllLabels: () => ({ fast: 'fast', default: 'default', complex: 'complex', local: 'local' }),
        getLabel: (tier: string) => tier,
      } as any,
      systemPrompt: 'test prompt',
      toolRegistry: {
        clone() { return this; },
        register: vi.fn(),
      } as any,
      toolExecutor: {} as any,
      config: {
        agents: {
          primary_tier: 'default',
          delegation: {
            compaction: 'fast',
            memory_extraction: 'fast',
            classification: 'fast',
            tool_summarisation: 'fast',
            complex_reasoning: 'complex',
          },
          max_delegation_depth: 3,
          max_iterations: 10,
        },
        compaction: { enabled: false },
        models: { default: { provider: 'anthropic', model: 'claude' } },
      } as any,
      commandRegistry,
    });

    const reply = vi.fn(async () => {});
    await router.handler({
      id: 'm4',
      channel: 'telegram',
      senderId: 'user-4',
      text: '/model fast',
      metadata: { isCommand: true, command: 'model', commandArgs: 'fast' },
    } as any, reply);

    expect(processSpy).not.toHaveBeenCalled();
    expect(setModelTierSpy).toHaveBeenCalledWith('fast');
    expect(session.setConfig).toHaveBeenCalledWith('modelTier', 'fast');
  });

  it('uses intent match to override agent target', async () => {
    const session = {
      id: 'telegram:user-2',
      addMessage: vi.fn(),
      getHistory: vi.fn(() => []),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
      getConfig: vi.fn(() => undefined),
      setConfig: vi.fn(),
      deleteConfig: vi.fn(),
    };

    const commandRegistry = new CommandRegistry();
    registerBuiltinCommands(commandRegistry);

    const intentRegistry = new ComponentRegistry({ matchThreshold: 0.5 });
    intentRegistry.register({
      name: 'deploy-route',
      patterns: ['deploy *'],
      target: { type: 'agent', name: 'coder' },
      priority: 10,
      enabled: true,
    });

    const agentConfigRegistry = new AgentConfigRegistry();
    agentConfigRegistry.loadFromConfig({
      assistant: { model_tier: 'default', sandbox: false },
      coder: { model_tier: 'complex', sandbox: false },
    });

    const agentRouter = new AgentRouter({
      default_agent: 'assistant',
      channels: {},
      senders: {},
    });

    const router = createMessageRouter({
      sessionManager: {
        getSession: vi.fn(() => session),
      } as any,
      modelRouter: {
        getAvailableTiers: () => ['fast', 'default', 'complex', 'local'],
        getAllLabels: () => ({ fast: 'fast', default: 'default', complex: 'complex', local: 'local' }),
        getLabel: (tier: string) => tier,
      } as any,
      systemPrompt: 'test prompt',
      toolRegistry: {
        clone() { return this; },
        register: vi.fn(),
      } as any,
      toolExecutor: {} as any,
      config: {
        intents: { enabled: true },
        agents: {
          primary_tier: 'default',
          delegation: {
            compaction: 'fast',
            memory_extraction: 'fast',
            classification: 'fast',
            tool_summarisation: 'fast',
            complex_reasoning: 'complex',
          },
          max_delegation_depth: 3,
          max_iterations: 10,
        },
        compaction: { enabled: false },
        models: { default: { provider: 'anthropic', model: 'claude' } },
      } as any,
      commandRegistry,
      intentRegistry,
      agentConfigRegistry,
      agentRouter,
    });

    await router.handler({
      id: 'm2',
      channel: 'telegram',
      senderId: 'user-2',
      text: 'deploy backend now',
      metadata: { isCommand: true, command: 'reset' },
    } as any, vi.fn(async () => {}));

    const keys = Array.from(router.agents.keys());
    expect(keys.some(key => key.includes(':coder'))).toBe(true);
  });

  it('falls back to llm path when confidence is below fast threshold', async () => {
    const session = {
      id: 'telegram:user-3',
      addMessage: vi.fn(),
      getHistory: vi.fn(() => []),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
      getConfig: vi.fn(() => undefined),
      setConfig: vi.fn(),
      deleteConfig: vi.fn(),
    };

    const commandRegistry = new CommandRegistry();
    registerBuiltinCommands(commandRegistry);

    const intentRegistry = new ComponentRegistry({ matchThreshold: 0.5 });
    intentRegistry.register({
      name: 'deploy-route',
      patterns: ['deploy *'],
      target: { type: 'agent', name: 'coder' },
      priority: 10,
      enabled: true,
    });

    const routingPolicy = new RoutingPolicy({
      enabled: true,
      fastPathThreshold: 0.99,
      llmThreshold: 0.2,
      defaultPath: 'llm',
    });

    const agentConfigRegistry = new AgentConfigRegistry();
    agentConfigRegistry.loadFromConfig({
      assistant: { model_tier: 'default', sandbox: false },
      coder: { model_tier: 'complex', sandbox: false },
    });

    const agentRouter = new AgentRouter({
      default_agent: 'assistant',
      channels: {},
      senders: {},
    });

    const router = createMessageRouter({
      sessionManager: {
        getSession: vi.fn(() => session),
      } as any,
      modelRouter: {
        getAvailableTiers: () => ['fast', 'default', 'complex', 'local'],
        getAllLabels: () => ({ fast: 'fast', default: 'default', complex: 'complex', local: 'local' }),
        getLabel: (tier: string) => tier,
      } as any,
      systemPrompt: 'test prompt',
      toolRegistry: {
        clone() { return this; },
        register: vi.fn(),
      } as any,
      toolExecutor: {} as any,
      config: {
        intents: { enabled: true },
        agents: {
          primary_tier: 'default',
          delegation: {
            compaction: 'fast',
            memory_extraction: 'fast',
            classification: 'fast',
            tool_summarisation: 'fast',
            complex_reasoning: 'complex',
          },
          max_delegation_depth: 3,
          max_iterations: 10,
        },
        compaction: { enabled: false },
        models: { default: { provider: 'anthropic', model: 'claude' } },
      } as any,
      commandRegistry,
      intentRegistry,
      routingPolicy,
      agentConfigRegistry,
      agentRouter,
    });

    await router.handler({
      id: 'm3',
      channel: 'telegram',
      senderId: 'user-3',
      text: 'deploy backend now',
      metadata: { isCommand: true, command: 'reset' },
    } as any, vi.fn(async () => {}));

    const keys = Array.from(router.agents.keys());
    expect(keys.some(key => key.includes(':assistant'))).toBe(true);
  });
});

describe('daemon audio routing integration', () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('fast-path replies for voice attachments when transcription is not configured and model does not support audio', async () => {
    const processSpy = vi.spyOn(AgentOrchestrator.prototype, 'process');

    const session = {
      id: 'telegram:user-voice-1',
      addMessage: vi.fn(),
      getHistory: vi.fn(() => []),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
      getConfig: vi.fn(() => undefined),
      setConfig: vi.fn(),
      deleteConfig: vi.fn(),
    };

    const commandRegistry = new CommandRegistry();
    registerBuiltinCommands(commandRegistry);

    const router = createMessageRouter({
      sessionManager: { getSession: vi.fn(() => session) } as any,
      modelRouter: {
        getAvailableTiers: () => ['default'],
        getAllLabels: () => ({ default: 'default' }),
        getLabel: (tier: string) => tier,
      } as any,
      systemPrompt: 'test prompt',
      toolRegistry: { clone() { return this; }, register: vi.fn() } as any,
      toolExecutor: {} as any,
      config: {
        agents: {
          primary_tier: 'default',
          delegation: {
            compaction: 'default',
            memory_extraction: 'default',
            classification: 'default',
            tool_summarisation: 'default',
            complex_reasoning: 'default',
          },
          max_delegation_depth: 1,
          max_iterations: 3,
        },
        compaction: { enabled: false },
        // Anthropic doesn't support native audio; ensures routing hits the non-audio path.
        models: { default: { provider: 'anthropic', model: 'claude' } },
        audio: { enabled: false },
      } as any,
      commandRegistry,
    });

    const reply = vi.fn(async () => {});
    await router.handler({
      id: 'v1',
      channel: 'telegram',
      senderId: 'user-voice-1',
      text: '',
      attachments: [{ mimeType: 'audio/ogg', data: 'ZGF0YQ==', filename: 'voice.ogg' }],
      timestamp: Date.now(),
    } as any, reply);

    expect(processSpy).not.toHaveBeenCalled();
    expect(reply).toHaveBeenCalledTimes(1);
    const msg = (reply.mock.calls[0] as unknown as any[])[0] as { text?: string };
    expect(String(msg.text)).toContain('audio transcription is not configured');
  });

  it('transcribes voice attachments when transcription is configured, then strips audio before calling agent.process', async () => {
    const processSpy = vi.spyOn(AgentOrchestrator.prototype, 'process').mockResolvedValue('ok');

    // Mock transcription endpoint call.
    const fetchSpy = vi.spyOn(globalThis, 'fetch' as any).mockResolvedValue({
      ok: true,
      status: 200,
      statusText: 'OK',
      json: async () => ({ text: 'hello world' }),
    } as any);

    const session = {
      id: 'telegram:user-voice-2',
      addMessage: vi.fn(),
      getHistory: vi.fn(() => []),
      clear: vi.fn(),
      replaceHistory: vi.fn(),
      getConfig: vi.fn(() => undefined),
      setConfig: vi.fn(),
      deleteConfig: vi.fn(),
    };

    const commandRegistry = new CommandRegistry();
    registerBuiltinCommands(commandRegistry);

    const router = createMessageRouter({
      sessionManager: { getSession: vi.fn(() => session) } as any,
      modelRouter: {
        getAvailableTiers: () => ['default'],
        getAllLabels: () => ({ default: 'default' }),
        getLabel: (tier: string) => tier,
      } as any,
      systemPrompt: 'test prompt',
      toolRegistry: { clone() { return this; }, register: vi.fn() } as any,
      toolExecutor: {} as any,
      config: {
        agents: {
          primary_tier: 'default',
          delegation: {
            compaction: 'default',
            memory_extraction: 'default',
            classification: 'default',
            tool_summarisation: 'default',
            complex_reasoning: 'default',
          },
          max_delegation_depth: 1,
          max_iterations: 3,
        },
        compaction: { enabled: false },
        models: { default: { provider: 'anthropic', model: 'claude' } },
        audio: {
          enabled: true,
          provider: { type: 'openai', endpoint: 'https://example.com/v1/audio/transcriptions', api_key: 'sk-test', model: 'whisper-1' },
        },
      } as any,
      commandRegistry,
    });

    const reply = vi.fn(async () => {});
    await router.handler({
      id: 'v2',
      channel: 'telegram',
      senderId: 'user-voice-2',
      text: 'caption',
      attachments: [
        { mimeType: 'audio/ogg', data: 'ZGF0YQ==', filename: 'voice.ogg' },
        { mimeType: 'image/jpeg', data: 'aW1n', filename: 'img.jpg' },
      ],
      timestamp: Date.now(),
    } as any, reply);

    expect(fetchSpy).toHaveBeenCalled();
    expect(processSpy).toHaveBeenCalledTimes(1);
    const [calledText, calledAttachments] = processSpy.mock.calls[0] ?? [];
    expect(String(calledText)).toContain('[Voice message]: hello world');
    expect(String(calledText)).toContain('caption');
    const atts = calledAttachments as any[] | undefined;
    expect(atts?.some(a => a.mimeType === 'audio/ogg')).toBe(false);
    expect(atts?.some(a => a.mimeType === 'image/jpeg')).toBe(true);
  });
});
