import { describe, it, expect } from 'vitest';
import type { Config } from '../../config/index.js';
import { ObservabilityCollector } from './observability.js';

function createConfig(): Config {
  return {
    models: {
      default: { provider: 'ollama', model: 'llama3.2' },
      fast: { provider: 'openai', model: 'gpt-4o-mini' },
      complex: { provider: 'anthropic', model: 'claude-3-7-sonnet' },
    },
    memory: {
      embedding: {
        provider: 'openai',
        model: 'text-embedding-3-small',
      },
    },
    audio: {
      enabled: true,
      provider: {
        type: 'custom',
        endpoint: 'http://localhost:18801/v1/audio/transcriptions',
      },
    },
    web_search: {
      provider: 'brave',
      api_key: 'test-brave-key',
      endpoint: undefined,
      max_results: 5,
    },
  } as unknown as Config;
}

describe('ObservabilityCollector', () => {
  it('collects sources and tracks restart counters in sampled series', async () => {
    let now = 1_700_000_000_000;
    let flynnPid = 100;

    const runner = async (command: string, args: string[]) => {
      const key = `${command} ${args.join(' ')}`;

      if (key === 'systemctl show flynn.service --property=LoadState,ActiveState,SubState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: `LoadState=loaded\nActiveState=active\nSubState=running\nDescription=Flynn daemon\nExecMainPID=${flynnPid}\nResult=success\n`,
          stderr: '',
        };
      }

      if (key === 'systemctl --user show ollama.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: 'LoadState=loaded\nActiveState=active\nSubState=running\nUnitFileState=enabled\nDescription=Ollama\nExecMainPID=211\nResult=success\n',
          stderr: '',
        };
      }

      if (key === 'systemctl --user show llama-server.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: 'LoadState=loaded\nActiveState=inactive\nSubState=dead\nUnitFileState=enabled\nDescription=llama.cpp\nExecMainPID=0\nResult=success\n',
          stderr: '',
        };
      }

      if (key === 'docker compose -f docker-compose.yml config --profiles') {
        return { stdout: 'voice\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml --profile voice config --services') {
        return { stdout: 'flynn\nwhisper-server\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml --profile voice ps --all --format json') {
        return { stdout: '[]', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml --profile voice ps whisper-server --format json') {
        return {
          stdout: JSON.stringify([
            {
              Name: 'flynn-whisper-server-1',
              Service: 'whisper-server',
              State: 'running',
              Health: 'healthy',
              Status: 'Up 2 minutes (healthy)',
            },
          ]),
          stderr: '',
        };
      }

      throw new Error(`Unexpected command: ${key}`);
    };

    const collector = new ObservabilityCollector({
      config: createConfig(),
      runner,
      now: () => now,
      samplingIntervalMs: 300_000,
    });

    await collector.forceSample();
    now += 30_000;
    flynnPid = 101;
    await collector.forceSample();

    const sources = await collector.listSources();
    expect(sources.map((entry) => entry.id)).toEqual(expect.arrayContaining([
      'systemd:flynn',
      'systemd-user:ollama',
      'systemd-user:llamacpp',
      'docker:whisper',
    ]));

    const series = await collector.getSeries({ windowMinutes: 60, bucketSeconds: 30 });
    const flynnSeries = series.series.find((entry) => entry.sourceId === 'systemd:flynn');
    expect(flynnSeries).toBeTruthy();
    expect(flynnSeries?.points.length).toBeGreaterThanOrEqual(2);
    expect(flynnSeries?.points[flynnSeries.points.length - 1]?.restartCount).toBe(1);
  });

  it('returns redacted journal logs for systemd sources', async () => {
    let now = 1_700_000_000_000;

    const runner = async (command: string, args: string[]) => {
      const key = `${command} ${args.join(' ')}`;

      if (key === 'systemctl show flynn.service --property=LoadState,ActiveState,SubState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: 'LoadState=loaded\nActiveState=active\nSubState=running\nDescription=Flynn daemon\nExecMainPID=777\nResult=success\n',
          stderr: '',
        };
      }

      if (key === 'systemctl --user show ollama.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=Ollama\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }

      if (key === 'systemctl --user show llama-server.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=llama.cpp\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml config --profiles') {
        return { stdout: '', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml config --services') {
        return { stdout: 'flynn\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml ps --all --format json') {
        return { stdout: '[]', stderr: '' };
      }

      if (key === 'journalctl -u flynn.service --since 600 seconds ago --no-pager --output short-iso-precise -n 200') {
        return {
          stdout: '2026-02-23 10:10:10.000000+0000 host flynn[777]: Authorization: Bearer super-secret-token-value\n',
          stderr: '',
        };
      }

      throw new Error(`Unexpected command: ${key}`);
    };

    const collector = new ObservabilityCollector({
      config: createConfig(),
      runner,
      now: () => now,
    });

    await collector.forceSample();
    const logs = await collector.getServiceLogs({ sourceId: 'systemd:flynn', sinceSeconds: 600 });

    expect(logs.sourceId).toBe('systemd:flynn');
    expect(logs.redacted).toBe(true);
    expect(logs.lines).toHaveLength(1);
    expect(logs.lines[0]?.text).toContain('[REDACTED_BEARER]');
    expect(logs.lines[0]?.level).toBe('info');
  });

  it('parses docker logs with levels and timestamps', async () => {
    let now = 1_700_000_000_000;

    const runner = async (command: string, args: string[]) => {
      const key = `${command} ${args.join(' ')}`;

      if (key === 'systemctl show flynn.service --property=LoadState,ActiveState,SubState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: 'LoadState=loaded\nActiveState=active\nSubState=running\nDescription=Flynn daemon\nExecMainPID=777\nResult=success\n',
          stderr: '',
        };
      }

      if (key === 'systemctl --user show ollama.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=Ollama\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }

      if (key === 'systemctl --user show llama-server.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=llama.cpp\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml config --profiles') {
        return { stdout: 'voice\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml --profile voice config --services') {
        return { stdout: 'flynn\nwhisper-server\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml --profile voice ps --all --format json') {
        return { stdout: '[]', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml --profile voice ps whisper-server --format json') {
        return {
          stdout: JSON.stringify([
            {
              Name: 'flynn-whisper-server-1',
              Service: 'whisper-server',
              State: 'running',
              Health: 'healthy',
              Status: 'Up 2 minutes (healthy)',
            },
          ]),
          stderr: '',
        };
      }

      if (key === 'docker compose -f docker-compose.yml config --profiles') {
        return { stdout: 'voice\n', stderr: '' };
      }

      if (key === 'docker compose -f docker-compose.yml --profile voice logs --timestamps --tail 120 --since 300s whisper-server') {
        return {
          stdout: 'whisper-server  | 2026-02-23T10:10:10Z warning: queue depth high\n',
          stderr: '',
        };
      }

      throw new Error(`Unexpected command: ${key}`);
    };

    const collector = new ObservabilityCollector({
      config: createConfig(),
      runner,
      now: () => now,
    });

    await collector.forceSample();
    const logs = await collector.getServiceLogs({ sourceId: 'docker:whisper', lines: 120, sinceSeconds: 300 });

    expect(logs.sourceId).toBe('docker:whisper');
    expect(logs.lines).toHaveLength(1);
    expect(logs.lines[0]?.level).toBe('warn');
    expect(typeof logs.lines[0]?.ts).toBe('number');
    expect(logs.lines[0]?.text).toContain('queue depth high');
  });

  it('falls back to process-running Flynn status when not launched under systemd', async () => {
    const originalInvocationId = process.env.INVOCATION_ID;
    const originalJournalStream = process.env.JOURNAL_STREAM;
    const originalSystemdExecPid = process.env.SYSTEMD_EXEC_PID;
    delete process.env.INVOCATION_ID;
    delete process.env.JOURNAL_STREAM;
    delete process.env.SYSTEMD_EXEC_PID;

    const runner = async (command: string, args: string[]) => {
      const key = `${command} ${args.join(' ')}`;
      if (key === 'systemctl show flynn.service --property=LoadState,ActiveState,SubState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: 'LoadState=loaded\nActiveState=inactive\nSubState=dead\nDescription=Flynn daemon\nExecMainPID=0\nResult=success\n',
          stderr: '',
        };
      }
      if (key === 'systemctl --user show ollama.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=Ollama\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }
      if (key === 'systemctl --user show llama-server.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=llama.cpp\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }
      if (key === 'docker compose -f docker-compose.yml config --profiles') {
        return { stdout: '', stderr: '' };
      }
      if (key === 'docker compose -f docker-compose.yml config --services') {
        return { stdout: 'flynn\n', stderr: '' };
      }
      if (key === 'docker compose -f docker-compose.yml ps --all --format json') {
        return { stdout: '[]', stderr: '' };
      }
      throw new Error(`Unexpected command: ${key}`);
    };

    try {
      const collector = new ObservabilityCollector({
        config: createConfig(),
        runner,
      });
      await collector.forceSample();
      const sources = await collector.listSources();
      const flynn = sources.find((entry) => entry.id === 'systemd:flynn');
      expect(flynn?.status).toBe('running');
      expect(flynn?.logCapable).toBe(false);
    } finally {
      if (originalInvocationId === undefined) {
        delete process.env.INVOCATION_ID;
      } else {
        process.env.INVOCATION_ID = originalInvocationId;
      }
      if (originalJournalStream === undefined) {
        delete process.env.JOURNAL_STREAM;
      } else {
        process.env.JOURNAL_STREAM = originalJournalStream;
      }
      if (originalSystemdExecPid === undefined) {
        delete process.env.SYSTEMD_EXEC_PID;
      } else {
        process.env.SYSTEMD_EXEC_PID = originalSystemdExecPid;
      }
    }
  });

  it('prefers user-level Flynn unit when it is active', async () => {
    const originalInvocationId = process.env.INVOCATION_ID;
    process.env.INVOCATION_ID = 'unit-test';

    const runner = async (command: string, args: string[]) => {
      const key = `${command} ${args.join(' ')}`;
      if (key === 'systemctl show flynn.service --property=LoadState,ActiveState,SubState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: 'LoadState=loaded\nActiveState=inactive\nSubState=dead\nDescription=Flynn daemon\nExecMainPID=0\nResult=success\n',
          stderr: '',
        };
      }
      if (key === 'systemctl --user show flynn.service --property=LoadState,ActiveState,SubState,Description,ExecMainPID,Result --no-pager') {
        return {
          stdout: 'LoadState=loaded\nActiveState=active\nSubState=running\nDescription=Flynn daemon\nExecMainPID=4242\nResult=success\n',
          stderr: '',
        };
      }
      if (key === 'systemctl --user show ollama.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=Ollama\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }
      if (key === 'systemctl --user show llama-server.service --property=LoadState,ActiveState,SubState,UnitFileState,Description,ExecMainPID,Result --no-pager') {
        return { stdout: 'LoadState=not-found\nActiveState=inactive\nSubState=dead\nDescription=llama.cpp\nExecMainPID=0\nResult=not-found\n', stderr: '' };
      }
      if (key === 'docker compose -f docker-compose.yml config --profiles') {
        return { stdout: '', stderr: '' };
      }
      if (key === 'docker compose -f docker-compose.yml config --services') {
        return { stdout: 'flynn\n', stderr: '' };
      }
      if (key === 'docker compose -f docker-compose.yml ps --all --format json') {
        return { stdout: '[]', stderr: '' };
      }
      if (key === 'journalctl --user -u flynn.service --since 900 seconds ago --no-pager --output short-iso-precise -n 200') {
        return {
          stdout: '2026-02-23 12:10:10.000000+0000 host flynn[4242]: user scope log line\n',
          stderr: '',
        };
      }
      throw new Error(`Unexpected command: ${key}`);
    };

    try {
      const collector = new ObservabilityCollector({
        config: createConfig(),
        runner,
      });
      await collector.forceSample();
      const sources = await collector.listSources();
      const flynn = sources.find((entry) => entry.id === 'systemd:flynn');
      expect(flynn?.status).toBe('running');
      expect(flynn?.runtime).toBe('systemd_user');
      expect(flynn?.kind).toBe('systemd_user');
      expect(flynn?.logCapable).toBe(true);

      const logs = await collector.getServiceLogs({ sourceId: 'systemd:flynn' });
      expect(logs.lines[0]?.text).toContain('user scope log line');
    } finally {
      if (originalInvocationId === undefined) {
        delete process.env.INVOCATION_ID;
      } else {
        process.env.INVOCATION_ID = originalInvocationId;
      }
    }
  });
});
