"use strict";
// src/test_graph_path_normalization.ts
// v1.14.1 — Issue #11 regression.
//
// Before: `graph deps Brain.ts` and `graph deps src/orchestrator/Brain.ts`
// both returned "no dependencies recorded" — only the absolute path worked.
// Fix: GraphStore.findFilesBySuffix() + GraphCommand path resolver accept
// any of {absolute, cwd-relative, bare basename, suffix}.
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 GraphStore_1 = require("./orchestrator/graph/GraphStore");
const SymbolExtractor_1 = require("./orchestrator/graph/SymbolExtractor");
const DependencyExtractor_1 = require("./orchestrator/graph/DependencyExtractor");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function withTmpDb(fn) {
    const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'graph-paths-'));
    const dbPath = path.join(tmp, 'codebase.db');
    try {
        return fn(dbPath);
    }
    finally {
        try {
            fs.rmSync(tmp, { recursive: true, force: true });
        }
        catch { /* */ }
    }
}
function seedStore(store, tmpRoot) {
    // Two project files: Brain.ts imports ./helper. Helper.ts is a leaf.
    const brain = path.join(tmpRoot, 'src', 'orchestrator', 'Brain.ts');
    const helper = path.join(tmpRoot, 'src', 'orchestrator', 'helper.ts');
    fs.mkdirSync(path.dirname(brain), { recursive: true });
    fs.writeFileSync(helper, `export function ping(): string { return 'pong'; }\n`);
    fs.writeFileSync(brain, `import { ping } from './helper';\nexport class Brain { say(): string { return ping(); } }\n`);
    for (const f of [brain, helper]) {
        const src = fs.readFileSync(f, 'utf-8');
        store.putSymbols((0, SymbolExtractor_1.extractSymbols)(f, src));
        store.putEdges((0, DependencyExtractor_1.extractDependencies)(f, src));
    }
    return { brain, helper };
}
function scenarioSuffixMatch() {
    withTmpDb((dbPath) => {
        const tmpRoot = path.dirname(dbPath);
        const store = new GraphStore_1.GraphStore({ dbPath });
        try {
            const { brain } = seedStore(store, tmpRoot);
            const byBare = store.findFilesBySuffix('Brain.ts');
            assert(byBare.length === 1, `bare basename should match exactly one file, got ${byBare.length}`);
            assert(byBare[0] === brain, `bare basename should resolve to abs path of Brain.ts, got ${byBare[0]}`);
            const byMid = store.findFilesBySuffix('orchestrator/Brain.ts');
            assert(byMid.length === 1, `partial suffix should also match`);
            assert(byMid[0] === brain, `partial suffix resolves to same abs path`);
            const byMiss = store.findFilesBySuffix('NotInRepo.ts');
            assert(byMiss.length === 0, `unknown basename should match nothing`);
        }
        finally {
            store.close();
        }
    });
    console.log('✅ scenario 1: findFilesBySuffix matches bare basename + partial path');
}
function scenarioMultipleMatches() {
    withTmpDb((dbPath) => {
        const tmpRoot = path.dirname(dbPath);
        const store = new GraphStore_1.GraphStore({ dbPath });
        try {
            // Two files share the same basename in different subdirs.
            const a = path.join(tmpRoot, 'src', 'a', 'Index.ts');
            const b = path.join(tmpRoot, 'src', 'b', 'Index.ts');
            fs.mkdirSync(path.dirname(a), { recursive: true });
            fs.mkdirSync(path.dirname(b), { recursive: true });
            fs.writeFileSync(a, `export const A = 1;\n`);
            fs.writeFileSync(b, `export const B = 2;\n`);
            for (const f of [a, b]) {
                const src = fs.readFileSync(f, 'utf-8');
                store.putSymbols((0, SymbolExtractor_1.extractSymbols)(f, src));
            }
            const matches = store.findFilesBySuffix('Index.ts');
            assert(matches.length === 2, `expected 2 matches for ambiguous Index.ts, got ${matches.length}`);
            // Disambiguate via longer suffix.
            const aOnly = store.findFilesBySuffix('a/Index.ts');
            assert(aOnly.length === 1 && aOnly[0] === a, `longer suffix narrows to single match`);
        }
        finally {
            store.close();
        }
    });
    console.log('✅ scenario 2: ambiguous basename returns all candidates; longer suffix disambiguates');
}
function scenarioDepsWithSuffix() {
    withTmpDb((dbPath) => {
        const tmpRoot = path.dirname(dbPath);
        const store = new GraphStore_1.GraphStore({ dbPath });
        try {
            const { brain, helper } = seedStore(store, tmpRoot);
            // findDependencies always wants the canonical abs path, but the
            // GraphCommand resolver should accept the bare basename and look up.
            const resolved = store.findFilesBySuffix('Brain.ts');
            assert(resolved[0] === brain, 'precondition');
            const edges = store.findDependencies(resolved[0]);
            assert(edges.length === 1, `Brain.ts should have 1 edge (./helper), got ${edges.length}`);
            assert(edges[0].resolvedFile === helper, `relative import should resolve to helper.ts`);
            assert(edges[0].resolvedFile !== undefined, `(project, ...) qualifier requires resolvedFile`);
        }
        finally {
            store.close();
        }
    });
    console.log('✅ scenario 3: deps lookup via suffix yields resolved project edge');
}
try {
    scenarioSuffixMatch();
    scenarioMultipleMatches();
    scenarioDepsWithSuffix();
    console.log('TEST_GRAPH_PATH_NORMALIZATION_OK');
}
catch (err) {
    console.error('TEST_GRAPH_PATH_NORMALIZATION_FAIL', err);
    process.exit(1);
}
