import { MemoryCache } from '../src/cache.js';
import { MemoryKnowledgeStore } from '../src/storage/memory-store.js';
import { HashModelProvider } from '../src/model/provider.js';
import { IngestionService } from '../src/ingest/service.js';
import { RetrievalService } from '../src/retrieval/service.js';
import { KnowledgeSafetyService } from '../src/security/knowledge-safety.js';
import { readFileSync } from 'node:fs';
const config = {
    env: 'test',
    port: 3027,
    databaseUrl: '',
    redisUrl: '',
    store: 'memory',
    cache: 'memory',
    autoMigrate: false,
    modelProvider: 'hash',
    embeddingDimensions: 1536,
    openAiEmbeddingModel: 'text-embedding-3-small',
    contextCacheTtlSeconds: 60,
    maxRequestBytes: 10 * 1024 * 1024,
    maxIngestContentBytes: 2 * 1024 * 1024,
    backupDir: '.tuberosa/test-backups',
    backupIntervalSeconds: 0,
    backupStartupDelaySeconds: 0,
    backupRetentionCount: 24,
    backupRetentionMaxAgeDays: 30,
    backupWriteThrough: false,
    backupWriteThroughThrottleSeconds: 600,
    physicalMirrorDebounceMs: 500,
    errorLogDir: '.tuberosa/test-error-logs',
    errorLogMaxBytes: 256 * 1024,
    errorLogAutoCapture: true,
    errorLogCaptureClientErrors: false,
};
async function main() {
    const fixture = JSON.parse(readFileSync('eval/retrieval-fixtures.json', 'utf-8'));
    const store = new MemoryKnowledgeStore();
    const cache = new MemoryCache();
    const provider = new HashModelProvider(config.embeddingDimensions);
    const safety = new KnowledgeSafetyService();
    const ingestion = new IngestionService(store, provider, { safety });
    const retrieval = new RetrievalService(store, cache, provider, config, safety);
    for (const item of fixture.knowledge) {
        const { evalId, ...rest } = item;
        await ingestion.ingestKnowledge({ ...rest, project: rest.project ?? fixture.project, metadata: { ...(rest.metadata ?? {}), evalId } });
    }
    const opsLabels = [...store['knowledge'].values()].find((k) => k.metadata?.evalId === 'ops-noisy-with-symbol')?.labels;
    const mediaLabels = [...store['knowledge'].values()].find((k) => k.metadata?.evalId === 'media-upload-entrypoint')?.labels;
    console.log('ops-noisy labels:', JSON.stringify(opsLabels, null, 2));
    console.log('media-upload labels:', JSON.stringify(mediaLabels, null, 2));
    const pack = await retrieval.searchContext({
        prompt: 'Update the SenderQueue retry policy in src/email/sender-queue.ts.',
        project: fixture.project,
        debug: true,
        bypassCache: true,
    });
    console.log('pack keys:', Object.keys(pack));
    console.log('classified domain:', pack.classified?.domain);
    const sections = pack.sections ?? [];
    for (const s of sections) {
        console.log(`section ${s.title} (${s.category}) candidates:`);
        for (const c of s.items ?? []) {
            console.log(`  ${c.knowledgeId} :: ${c.metadata?.evalId} :: score=${c.finalScore}`);
        }
    }
    const events = (pack.debug?.suppressionEvents ?? []);
    console.log('suppression events:');
    for (const e of events) {
        console.log(`  k=${e.knowledgeId} reason=${e.reason} delta=${e.deltaScore} ev=${e.evidence}`);
    }
}
main().catch((err) => {
    console.error(err);
    process.exit(1);
});
