import { listSpecialists } from '../../engines/specialist-roster.js';
import { createEmbedder } from '../../engines/embedder.js';
import { computeSemanticScore, tokenizeSemanticText } from '../../engines/semantic-ranking.js';
function tokenize(text) {
    return tokenizeSemanticText(text);
}
const specialistEmbeddings = new Map();
export function matchNPAssets(signals, skills) {
    const embedder = createEmbedder();
    const signalText = [signals.domains.join(' '), signals.subGoalHints.join(' ')].join(' ').trim();
    const signalTokens = tokenize(signalText);
    const signalVector = embedder.embedSync(signalText);
    const rankedSkills = [...skills]
        .map((skill) => ({
        skill,
        score: scoreSemanticMatch(signalTokens, signalVector, [skill.name, skill.domain ?? '', skill.instructions ?? ''].join(' '), skill.embedding, embedder),
    }))
        .sort((left, right) => right.score - left.score)
        .map((entry) => entry.skill);
    const rankedSpecialists = listSpecialists()
        .map((specialist) => ({
        specialistId: specialist.specialistId,
        name: specialist.name,
        score: scoreSemanticMatch(signalTokens, signalVector, [specialist.name, specialist.division, specialist.description].join(' '), specialistEmbeddings.get(specialist.specialistId), embedder, specialist.specialistId),
    }))
        .sort((left, right) => right.score - left.score)
        .slice(0, 5)
        .map(({ specialistId, name }) => ({ specialistId, name }));
    return {
        skills: rankedSkills,
        specialists: rankedSpecialists,
    };
}
function scoreSemanticMatch(signalTokens, signalVector, artifactText, cachedEmbedding, embedder, cacheKey) {
    const embedding = Array.isArray(cachedEmbedding) && cachedEmbedding.length === signalVector.length
        ? cachedEmbedding
        : embedder.embedSync(artifactText);
    if (cacheKey) {
        specialistEmbeddings.set(cacheKey, embedding);
    }
    return computeSemanticScore({
        query: [...signalTokens].join(' '),
        queryVector: signalVector,
        candidateText: artifactText,
        candidateVector: embedding,
        lexicalTexts: [artifactText],
        embedder,
    }).final;
}
