import { describe, expect, it } from 'vitest';
import { mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { MemoryStore } from './store.js';
import { QmdSearch } from './qmd-search.js';

describe('QmdSearch', () => {
  it('finds relevant markdown lines with heading-aware scoring', async () => {
    const dir = mkdtempSync(join(tmpdir(), 'flynn-qmd-search-'));
    try {
      const store = new MemoryStore({ dir, maxContextTokens: 2000 });
      store.write(
        'user',
        [
          '# Preferences',
          '- Favorite editor is Neovim',
          '- Uses TypeScript daily',
          '',
          '# Projects',
          '- QMD backend prototype for memory search',
        ].join('\n'),
        'replace',
      );
      store.write('sessions/abc123', '- Discussed QMD ranking for markdown memory.', 'replace');

      const qmd = new QmdSearch(store, { topK: 5, minScore: 0.1 });
      const results = await qmd.search('qmd memory search');

      expect(results.length).toBeGreaterThan(0);
      expect(results[0].source).toBe('qmd');
      expect(results.some((r) => r.namespace === 'user')).toBe(true);
      expect(results.some((r) => r.namespace === 'sessions/abc123')).toBe(true);
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  it('returns empty results for empty query', async () => {
    const dir = mkdtempSync(join(tmpdir(), 'flynn-qmd-search-'));
    try {
      const store = new MemoryStore({ dir, maxContextTokens: 2000 });
      store.write('user', 'hello world', 'replace');
      const qmd = new QmdSearch(store);
      const results = await qmd.search('   ');
      expect(results).toEqual([]);
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });
});
