import path from "node:path";
import { fileURLToPath } from "node:url";
const shellSharedRoot = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(shellSharedRoot, "../../../../../");
export function shellToolSkillDocPath(toolId, storageGroup = "shellExecution") {
    return path
        .join(repoRoot, "src", "storagePool", "baseToolStorage", "shellBase", storageGroup, toolId, `${toolId}.md`)
        .split(path.sep)
        .join("/");
}
export function shellToolSourcePath(toolId, storageGroup = "shellExecution") {
    return path
        .join(repoRoot, "src", "agentCore", "agent_executionEngine", "basic_toolLayer", "baseTools", "shellBase", storageGroup, `${toolId}.ts`)
        .split(path.sep)
        .join("/");
}
export function shellToolStoragePracticePath(toolId, storageGroup = "shellExecution") {
    return path
        .join(repoRoot, "src", "storagePool", "baseToolStorage", "shellBase", storageGroup, toolId, "bestPractice.ts")
        .split(path.sep)
        .join("/");
}
export function jsonSchema(name, schema) {
    return {
        kind: "json-schema",
        name,
        schema,
    };
}
export function createShellBaseToolDefinition(options) {
    const storageGroup = options.storageGroup ?? "shellExecution";
    return {
        toolId: options.toolId,
        source: "builtin",
        family: "shell",
        group: storageGroup,
        title: options.title,
        description: options.description,
        toolSkill: {
            docPath: shellToolSkillDocPath(options.toolId, 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: true,
            storesResult: true,
            storesAudit: true,
            reusable: false,
        },
        sourcePath: shellToolSourcePath(options.toolId, storageGroup),
        metadata: {
            storagePracticePath: shellToolStoragePracticePath(options.toolId, storageGroup),
            ...(options.metadata ?? {}),
        },
    };
}
function normalizePracticeSource(practice) {
    if (typeof practice.source === "string") {
        return {
            sourceLabel: practice.source,
            sourceKind: undefined,
            sourcePath: undefined,
        };
    }
    return {
        sourceLabel: practice.source.label,
        sourceKind: practice.source.kind,
        sourcePath: practice.source.path,
    };
}
export function orderShellPractices(practices, preferredProvider) {
    if (preferredProvider === undefined) {
        return practices;
    }
    return [
        ...practices.filter((practice) => practice.providerName === preferredProvider),
        ...practices.filter((practice) => practice.providerName !== preferredProvider),
    ];
}
export function selectShellPractice(practices, preferredProvider) {
    const selected = orderShellPractices(practices, preferredProvider)[0];
    if (selected === undefined) {
        return {
            providerName: "praxis-native",
            sourceLabel: "Praxis native runtime fallback",
            sourceKind: "praxis-native",
            directCliSupport: false,
            sideEffectPolicy: "runtime-governed",
            notes: ["No provider practice metadata was registered for this shell tool."],
        };
    }
    return {
        providerName: selected.providerName,
        ...normalizePracticeSource(selected),
        directCliSupport: selected.directCliSupport,
        sideEffectPolicy: selected.sideEffectPolicy,
        notes: selected.notes ?? [],
    };
}
export function selectShellProviderPractice(practices, dependencies, fallbackPractice) {
    const orderedPractices = dependencies.preferredProvider === undefined
        ? practices
        : [
            ...practices.filter((practice) => practice.providerName === dependencies.preferredProvider),
            ...practices.filter((practice) => practice.providerName !== dependencies.preferredProvider),
        ];
    const selectedPractice = orderedPractices[0];
    if (selectedPractice !== undefined) {
        return {
            providerName: selectedPractice.providerName,
            practice: selectedPractice,
            provider: selectedPractice.createProvider?.(dependencies),
        };
    }
    return {
        providerName: fallbackPractice.providerName,
        practice: fallbackPractice,
        provider: fallbackPractice.createProvider?.(dependencies),
    };
}
export function buildShellPracticeAuditMetadata(selection) {
    return {
        selectedPractice: selection.providerName,
        selectedPracticeSource: selection.sourceLabel,
        selectedPracticeSourceKind: selection.sourceKind,
        selectedPracticeSourcePath: selection.sourcePath,
        directCliSupport: selection.directCliSupport,
        sideEffectPolicy: selection.sideEffectPolicy,
    };
}
export function adaptShellToolResultToInvokeResult(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 createShellCoreHandler(definition, invokeCore) {
    return {
        definition,
        async invoke(request) {
            return adaptShellToolResultToInvokeResult(await invokeCore(request));
        },
    };
}
export function injectRuntimeInvocationMetadata(metadata, auditMetadata, request) {
    return {
        ...(auditMetadata ?? {}),
        runtimeId: request.runtimeId,
        sessionId: request.sessionId,
        toolCallId: request.toolCallId,
        ...(metadata ?? {}),
    };
}
export function attachShellAuditMetadata(audit, metadata) {
    return (audit ?? []).map((event) => ({
        ...event,
        metadata: {
            ...(event.metadata ?? {}),
            ...metadata,
        },
    }));
}
