"use strict";
// src/test_indexer.ts
// v1.13.0 — Indexer + Retriever round-trip using a deterministic mock
// embedding provider. Verifies build/incremental update/retrieve and
// asserts that semantic similarity beats lexical-only when the query
// matches a chunk's "topic vector".
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const EmbeddingProvider_1 = require("./orchestrator/rag/EmbeddingProvider");
const Indexer_1 = require("./orchestrator/rag/Indexer");
const Retriever_1 = require("./orchestrator/rag/Retriever");
const SqliteVectorStore_1 = require("./orchestrator/rag/SqliteVectorStore");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
const DIM = 16;
class TopicEmbedding extends EmbeddingProvider_1.AbstractEmbeddingProvider {
    name() { return 'topic-mock'; }
    dim() { return DIM; }
    model() { return 'mock'; }
    async isAvailable() { return true; }
    async embed(text) {
        // Deterministic topic vector: count token frequencies in fixed buckets.
        const tokens = text.toLowerCase().match(/[a-z_][a-z0-9_]+/g) || [];
        const v = new Array(DIM).fill(0);
        for (const t of tokens) {
            let h = 0;
            for (let i = 0; i < t.length; i++)
                h = (h * 31 + t.charCodeAt(i)) >>> 0;
            v[h % DIM] += 1;
        }
        // L2-normalize so cosine distance is well-defined.
        let norm = 0;
        for (const x of v)
            norm += x * x;
        norm = Math.sqrt(norm) || 1;
        return v.map(x => x / norm);
    }
}
function mkTmp() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'rag-indexer-test-'));
}
async function main() {
    const root = mkTmp();
    const dbPath = path.join(root, 'index.db');
    try {
        // Three source files with distinct topics.
        fs.writeFileSync(path.join(root, 'auth.ts'), [
            'export function loginWithPassword(user: string, password: string) {',
            '  // verify password hash and issue a session token',
            '  return issueSessionToken(user);',
            '}',
            'function issueSessionToken(user: string) { return user + "-token"; }',
        ].join('\n'));
        fs.writeFileSync(path.join(root, 'pizza.ts'), [
            'export function bakePizza(temperature: number, minutes: number) {',
            '  // place dough in the oven, watch the cheese melt',
            '  return { temperature, minutes, status: "ready" };',
            '}',
        ].join('\n'));
        fs.writeFileSync(path.join(root, 'graph.ts'), [
            'export function shortestPath(graph: Record<string, string[]>, from: string, to: string) {',
            '  // breadth-first search through the dependency graph',
            '  return [from, to];',
            '}',
        ].join('\n'));
        const embed = new TopicEmbedding();
        const store = new SqliteVectorStore_1.SqliteVectorStore({ dim: DIM, dbPath });
        const indexer = new Indexer_1.Indexer();
        // 1. initial build
        const r1 = await indexer.build({ root, store, embed });
        assert(r1.indexedFiles === 3, `expected 3 indexed files, got ${r1.indexedFiles}`);
        assert(r1.upsertedChunks >= 3, `expected ≥3 chunks, got ${r1.upsertedChunks}`);
        console.log(`✓ scenario 1: initial build indexed ${r1.indexedFiles} files / ${r1.upsertedChunks} chunks`);
        // 2. incremental update with no changes → all skipped
        const r2 = await indexer.build({ root, store, embed });
        assert(r2.indexedFiles === 0, `incremental should skip all (got ${r2.indexedFiles})`);
        assert(r2.skippedFiles === 3, `incremental should skip 3 (got ${r2.skippedFiles})`);
        console.log(`✓ scenario 2: incremental no-op skipped all 3 files`);
        // 3. modify one file → only that file re-indexes
        await new Promise(r => setTimeout(r, 20));
        fs.appendFileSync(path.join(root, 'auth.ts'), '\nexport const SESSION_TTL_MIN = 60;\n');
        const r3 = await indexer.build({ root, store, embed });
        assert(r3.indexedFiles === 1, `expected 1 re-indexed file, got ${r3.indexedFiles}`);
        assert(r3.skippedFiles === 2, `expected 2 unchanged, got ${r3.skippedFiles}`);
        console.log(`✓ scenario 3: mtime delta re-indexed exactly 1 file`);
        // 4. retrieve "password login session" → auth.ts should win
        const ret = new Retriever_1.Retriever(embed, store);
        const hits = await ret.retrieve('password login session token', { topK: 3 });
        assert(hits.length > 0, 'expected at least 1 hit');
        assert(hits[0].file.endsWith('auth.ts'), `top hit should be auth.ts, got ${hits[0].file}`);
        console.log(`✓ scenario 4: top-1 hit for password/login is auth.ts (score=${hits[0].score.toFixed(3)})`);
        // 5. retrieve "shortest path graph" → graph.ts should win
        const hits2 = await ret.retrieve('shortest path graph dependency', { topK: 3 });
        assert(hits2[0].file.endsWith('graph.ts'), `top hit should be graph.ts, got ${hits2[0].file}`);
        console.log(`✓ scenario 5: top-1 hit for graph/path is graph.ts (score=${hits2[0].score.toFixed(3)})`);
        // 6. purge by file removes its chunks from search
        await store.deleteByFile(path.join(root, 'pizza.ts'));
        const hits3 = await ret.retrieve('pizza oven cheese', { topK: 3 });
        assert(!hits3.some(h => h.file.endsWith('pizza.ts')), 'pizza chunks should be gone after deleteByFile');
        console.log(`✓ scenario 6: deleteByFile removes chunks from retrieval`);
        await store.close();
        console.log('TEST_INDEXER_OK');
    }
    finally {
        try {
            fs.rmSync(root, { recursive: true, force: true });
        }
        catch { /* best effort */ }
    }
}
main().catch(err => {
    console.error(`TEST_INDEXER_FAIL: ${err instanceof Error ? err.message : String(err)}`);
    process.exit(1);
});
