import { buildKnowledgeInjectionPrompt, selectKnowledgeForTask, } from '../state/knowledge-injection.js';
function normalizeKnowledgeFetchMode(fetchMode) {
    if (!fetchMode)
        return {};
    return {
        fetchMode,
        allowPrivateHosts: fetchMode === 'allow-private-hosts',
    };
}
function appendKnowledgeIntentMetadata(metadata, fetchMode, ingestMode) {
    if (!metadata && !fetchMode)
        return {
            knowledgeIntent: {
                ingestMode,
            },
        };
    return {
        ...(metadata ?? {}),
        knowledgeIntent: {
            ingestMode,
            ...(fetchMode ? { remoteFetchMode: fetchMode } : {}),
        },
    };
}
export function createMemoryApi(memoryRegistry) {
    return Object.freeze({
        add: (input) => memoryRegistry.add(input),
        search: (filter = {}) => memoryRegistry.search(filter),
        searchSemantic: (filter = {}) => memoryRegistry.searchSemantic(filter),
        vectorStats: () => memoryRegistry.vectorStats(),
        rebuildVectors: () => memoryRegistry.rebuildVectors(),
        rebuildVectorsAsync: () => memoryRegistry.rebuildVectorsAsync(),
        doctor: () => memoryRegistry.doctor(),
        reviewQueue: (limit = 10) => memoryRegistry.reviewQueue(limit),
        exportBundle: (filter = {}) => memoryRegistry.exportBundle(filter),
        importBundle: (bundle) => memoryRegistry.importBundle(bundle),
        get: (id) => memoryRegistry.get(id),
        getAll: () => memoryRegistry.getAll(),
        link: (fromId, toId, relation) => memoryRegistry.link(fromId, toId, relation),
        linksFor: (id) => memoryRegistry.linksFor(id),
        update: (id, patch) => (memoryRegistry.update(id, patch)),
        review: (id, patch) => memoryRegistry.review(id, patch),
        delete: (id) => memoryRegistry.delete(id),
        explain: (task, writeScope = [], limit = 3) => {
            const injections = selectKnowledgeForTask(memoryRegistry, task, writeScope, limit);
            return {
                injections,
                prompt: buildKnowledgeInjectionPrompt(injections),
            };
        },
    });
}
export function createKnowledgeApi(knowledgeService, options = {}) {
    return Object.freeze({
        status: Object.freeze({
            get: () => knowledgeService.getStatus(),
            lint: () => knowledgeService.lint(),
            reindex: () => knowledgeService.reindex(),
        }),
        sources: Object.freeze({
            list: (limit = 100) => knowledgeService.listSources(limit),
            query: (input = {}) => knowledgeService.querySources(input),
        }),
        graph: Object.freeze({
            nodes: Object.freeze({
                list: (limit = 100) => knowledgeService.listNodes(limit),
                query: (input = {}) => knowledgeService.queryNodes(input),
            }),
            issues: Object.freeze({
                list: (limit = 100) => knowledgeService.listIssues(limit),
                query: (input = {}) => knowledgeService.queryIssues(input),
            }),
            extractions: Object.freeze({
                list: (limit = 100, sourceId) => knowledgeService.listExtractions(limit, sourceId),
                get: (id) => knowledgeService.getExtraction(id),
                getBySourceId: (sourceId) => knowledgeService.getSourceExtraction(sourceId),
            }),
            items: Object.freeze({
                get: (id) => knowledgeService.getItem(id),
                getMany: (ids) => knowledgeService.getItems(ids),
                neighbors: (kind, id, input = {}) => knowledgeService.getNeighbors(kind, id, input),
                search: (query, limit = 10) => knowledgeService.search(query, limit),
            }),
        }),
        usage: Object.freeze({
            list: (limit = 100, input = {}) => knowledgeService.listUsageRecords(limit, input),
            record: (input) => knowledgeService.recordUsage(input),
        }),
        connectors: Object.freeze({
            list: () => knowledgeService.listConnectors(),
            get: (id) => knowledgeService.getConnector(id),
            doctor: (id) => knowledgeService.doctorConnector(id),
            register: (connector, options = {}) => knowledgeService.registerConnector(connector, options),
        }),
        ingest: Object.freeze({
            url: (input) => knowledgeService.ingestUrl({
                ...input,
                ...normalizeKnowledgeFetchMode(input.fetchMode),
                metadata: appendKnowledgeIntentMetadata(input.metadata, input.fetchMode, 'url'),
            }),
            artifact: (input) => knowledgeService.ingestArtifact({
                ...input,
                ...normalizeKnowledgeFetchMode(input.fetchMode),
                metadata: appendKnowledgeIntentMetadata(input.metadata, input.fetchMode, 'artifact'),
            }),
            bookmarksFile: (input) => knowledgeService.importBookmarksFromFile(input),
            urlsFile: (input) => knowledgeService.importUrlsFromFile(input),
            bookmarkSeeds: (seeds, sessionId, sourceType, connectorId) => knowledgeService.ingestBookmarkSeeds(seeds, sessionId, sourceType, connectorId),
            withConnector: (connectorId, input, sessionId) => knowledgeService.ingestWithConnector(connectorId, input, sessionId),
            connectorInput: (input) => knowledgeService.ingestConnectorInput(input),
        }),
        packets: Object.freeze({
            build: (task, writeScope = [], limit = 10, options = {}) => knowledgeService.buildPacket(task, writeScope, limit, options),
            buildSync: (task, writeScope = [], limit = 10, options = {}) => knowledgeService.buildPacketSync(task, writeScope, limit, options),
            buildPrompt: (task, writeScope = [], limit = 10, options = {}) => knowledgeService.buildPromptPacket(task, writeScope, limit, options),
            buildPromptSync: (task, writeScope = [], limit = 10, options = {}) => knowledgeService.buildPromptPacketSync(task, writeScope, limit, options),
        }),
        projections: Object.freeze({
            listTargets: (limit = 25) => knowledgeService.listProjectionTargets(limit),
            render: (input) => knowledgeService.renderProjection(input),
            materialize: (input) => knowledgeService.materializeProjection(input),
        }),
        jobs: Object.freeze({
            list: () => knowledgeService.listJobs(),
            get: (id) => knowledgeService.getJob(id),
            runs: (limit = 100, jobId) => knowledgeService.listJobRuns(limit, jobId),
            run: (id, input = {}) => knowledgeService.runJob(id, input),
            schedules: Object.freeze({
                list: (limit = 100) => knowledgeService.listSchedules(limit),
                get: (id) => knowledgeService.getSchedule(id),
                save: (input) => knowledgeService.saveSchedule(input),
                delete: (id) => knowledgeService.deleteSchedule(id),
                setEnabled: (id, enabled) => knowledgeService.setScheduleEnabled(id, enabled),
            }),
        }),
        consolidation: Object.freeze({
            candidates: (limit = 100, input = {}) => knowledgeService.listConsolidationCandidates(limit, input),
            getCandidate: (id) => knowledgeService.getConsolidationCandidate(id),
            reports: (limit = 100) => knowledgeService.listConsolidationReports(limit),
            getReport: (id) => knowledgeService.getConsolidationReport(id),
            decide: (candidateId, decision, input = {}) => knowledgeService.decideConsolidationCandidate(candidateId, decision, input),
        }),
        ...(options.memoryRegistry ? { memory: createMemoryApi(options.memoryRegistry) } : {}),
    });
}
