import { hashText } from '../cache.js';
import { redactGraphText } from '../query.js';
function specIdFromPath(path) {
    return path.split('/').find((part) => /^SPEC-\d+$/i.test(part));
}
function basename(path) {
    return path.split('/').slice(-1)[0] ?? path;
}
function node(args) {
    return {
        id: args.id,
        type: args.type,
        label: redactGraphText(args.label, args.policy),
        source: 'handoff-extractor',
        evidence: [{ path: args.source.path, hash: args.source.hash }],
        updatedAt: new Date().toISOString(),
    };
}
function edge(from, to, type, source) {
    return {
        id: `edge:${hashText(`${from}:${type}:${to}:${source.id}`)}`,
        from,
        to,
        type,
        source: 'handoff-extractor',
        confidence: 'medium',
        classification: 'extracted',
        evidence: { path: source.path, hash: source.hash },
        updatedAt: new Date().toISOString(),
    };
}
export function extractHandoffGraph(source, policy) {
    const specId = specIdFromPath(source.path);
    if (specId === undefined) {
        return { nodes: [], edges: [] };
    }
    const specNodeId = `spec:${specId}`;
    const handoffId = `handoff:${specId}:${hashText(source.path).slice(0, 10)}`;
    const nodes = [
        node({ id: handoffId, type: 'handoff', label: basename(source.path), source, policy }),
    ];
    const edges = [edge(specNodeId, handoffId, 'references', source)];
    for (const match of source.content.matchAll(/`((?:src|tests|planu)\/[^`]+)`/g)) {
        const path = (match[1] ?? '').trim();
        if (path.length === 0) {
            continue;
        }
        const type = path.startsWith('tests/') ? 'test' : 'file';
        const id = `${type}:${path}`;
        nodes.push(node({ id, type, label: path, source, policy }));
        edges.push(edge(handoffId, id, type === 'test' ? 'tests' : 'references', source));
    }
    return { nodes, edges };
}
//# sourceMappingURL=handoff-extractor.js.map