import path from "node:path";
import { fileURLToPath } from "node:url";
const mcpBaseSharedRoot = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(mcpBaseSharedRoot, "../../../../..");
export function isJsonObject(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function readStringArray(value) {
    if (value === undefined)
        return undefined;
    if (!Array.isArray(value))
        return undefined;
    const strings = value.filter((item) => typeof item === "string");
    return strings.length === value.length ? strings : undefined;
}
export function cleanStringList(value) {
    const strings = readStringArray(value);
    if (strings === undefined)
        return undefined;
    return [...new Set(strings.map((item) => item.trim()).filter(Boolean))];
}
export function optionalTrimmedString(value) {
    if (value === undefined)
        return undefined;
    if (typeof value !== "string")
        return undefined;
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : undefined;
}
export function guardAccepted(guard) {
    if (!isJsonObject(guard))
        return false;
    return guard.accepted === true || guard.allowed === true;
}
export function mcpBaseToolSkillDocPath(toolId, storageGroup) {
    return path
        .join(repoRoot, "src", "storagePool", "baseToolStorage", "mcpBase", storageGroup, toolId, `${toolId}.md`)
        .split(path.sep)
        .join("/");
}
export function mcpBaseToolSourcePath(toolId, storageGroup) {
    return path
        .join(repoRoot, "src", "agentCore", "agent_executionEngine", "basic_toolLayer", "baseTools", "mcpBase", storageGroup, `${toolId}.ts`)
        .split(path.sep)
        .join("/");
}
export function mcpBaseToolStoragePracticePath(toolId, storageGroup) {
    return path
        .join(repoRoot, "src", "storagePool", "baseToolStorage", "mcpBase", storageGroup, toolId, "bestPractice.ts")
        .split(path.sep)
        .join("/");
}
export function jsonSchema(name, schema) {
    return { kind: "json-schema", name, schema };
}
export function createMcpBaseToolDefinition(options) {
    return {
        toolId: options.toolId,
        source: "builtin",
        family: "mcp",
        group: options.storageGroup,
        title: options.title,
        description: options.description,
        toolSkill: {
            docPath: mcpBaseToolSkillDocPath(options.toolId, options.storageGroup),
            summary: options.summary,
            riskLevel: options.riskLevel ?? "risky",
        },
        inputSchema: options.inputSchema ?? jsonSchema(`${options.toolId}.input`, { type: "object", additionalProperties: true }),
        outputSchema: options.outputSchema ?? jsonSchema(`${options.toolId}.output`, { type: "object", additionalProperties: true }),
        riskLevel: options.riskLevel ?? "risky",
        permissionHints: [...options.permissionHints],
        dependencies: options.dependencies,
        storagePolicy: options.storagePolicy ?? {
            storesMaterial: false,
            storesResult: true,
            storesAudit: true,
            reusable: true,
        },
        sourcePath: mcpBaseToolSourcePath(options.toolId, options.storageGroup),
        metadata: {
            storagePracticePath: mcpBaseToolStoragePracticePath(options.toolId, options.storageGroup),
            runtimeOwnsMcpClient: true,
            ...(options.metadata ?? {}),
        },
    };
}
export function buildMcpPracticeAuditMetadata(selection) {
    return {
        selectedPractice: selection.providerName,
        selectedPracticeSource: selection.sourceLabel,
        selectedPracticeSourceKind: selection.sourceKind,
        selectedPracticeSourcePath: selection.sourcePath,
        directCliSupport: selection.directCliSupport,
        sideEffectPolicy: selection.sideEffectPolicy,
        notes: selection.notes ?? [],
    };
}
export function adaptMcpToolResultToInvokeResult(result) {
    if (!result.ok) {
        return {
            ok: false,
            toolId: result.toolId,
            error: {
                code: result.error.code,
                message: result.error.message,
                publicSafe: true,
            },
            events: result.events,
        };
    }
    return {
        ok: true,
        toolId: result.toolId,
        output: result.output,
        events: result.events,
        metadata: {
            audit: result.audit,
        },
    };
}
export function createMcpCoreHandler(definition, invokeCore) {
    return {
        definition,
        async invoke(request) {
            return adaptMcpToolResultToInvokeResult(await invokeCore(request));
        },
    };
}
export function injectRuntimeInvocationMetadata(metadata, auditMetadata, request) {
    return {
        ...(auditMetadata ?? {}),
        runtimeId: request.runtimeId,
        sessionId: request.sessionId,
        toolCallId: request.toolCallId,
        ...(metadata ?? {}),
    };
}
