/*
 * 文件定位：ToolabilityPool / TAP 高级工具系统 / Office 工具集合 / PDF 工具。
 * 核心目的：提供 办公文档基础工具 / PDF 工具 中的“编码 PDF”基础能力原语。
 * 能力要求1：需要定义该能力的输入、输出、错误、权限需求和可观测事件。
 * 能力要求2：这些 Office 能力由 TAP 高级工具系统承接，不再作为 baseTool 完成目标。
 * 能力要求3：TAP 负责 Office 能力的治理、审批、组合和专业能力库承接。
 * 边界：承接 Office 高级工具能力，不回写到 agentCore baseTools。
 * 对接：通过 TAP 复用转交与 runtime 官方模块桥接接通，并保留治理、审批和审计边界。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
export const pdfEncodeDescriptor = {
    toolId: "office.pdfEncode",
    capability: "encode-pdf",
    route: "toolabilityPool.officeBase.Portable_Document_Format",
    defaultDryRun: true,
    tapOwnsApproval: true,
    permissionsRequired: ["filesystem:readwrite"],
    unsafeSideEffects: false,
};
const sourceFormats = ["markdown", "html", "images", "structured-content"];
const pageSizes = ["a4", "letter", "legal", "runtime-default"];
function isBlank(value) {
    return typeof value !== "string" || value.trim().length === 0;
}
function invocationId(context) {
    return context?.invocationId?.trim() || "office.pdfEncode:dry-run";
}
function cleanList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
function auditEvent(type, context, outputPath, metadata) {
    return {
        type,
        toolId: pdfEncodeDescriptor.toolId,
        invocationId: invocationId(context),
        dryRun: true,
        outputPath,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context, outputPath) {
    return {
        ok: false,
        toolId: pdfEncodeDescriptor.toolId,
        error: {
            code,
            message,
            boundary,
            safeForRuntimeInspection: true,
            internalDetailExposed: false,
        },
        audit: [auditEvent("agentCore.basicTool.office.pdfEncode.rejected", context, outputPath, { code })],
        events: ["basicTool.office.pdfEncode.rejected"],
    };
}
function normalizeRelativePath(value) {
    const normalized = value?.trim().replaceAll("\\", "/").replace(/\/+/g, "/") ?? "";
    const parts = normalized.split("/");
    if (normalized.length === 0 ||
        normalized.includes("\0") ||
        normalized.startsWith("/") ||
        parts.some((part) => part === "..")) {
        return undefined;
    }
    return parts.filter((part) => part !== "." && part.length > 0).join("/");
}
function normalizeSourceFormat(sourceFormat, context, outputPath) {
    if (isBlank(sourceFormat)) {
        return failure("MISSING_SOURCE_FORMAT", "office.pdfEncode requires target.sourceFormat", "input", context, outputPath);
    }
    if (sourceFormats.includes(sourceFormat)) {
        return sourceFormat;
    }
    return failure("INVALID_SOURCE_FORMAT", "office.pdfEncode sourceFormat must be markdown, html, images, or structured-content", "input", context, outputPath);
}
function normalizePageSize(pageSize, context, outputPath) {
    if (pageSize === undefined || pageSize.trim() === "") {
        return "runtime-default";
    }
    if (pageSizes.includes(pageSize)) {
        return pageSize;
    }
    return failure("INVALID_PAGE_SIZE", "office.pdfEncode pageSize must be a4, letter, legal, or runtime-default", "input", context, outputPath);
}
function resolveScopes(context, outputPath) {
    const requested = cleanList(context?.requestedScopes);
    const allowed = cleanList(context?.allowedScopes);
    if (requested.length === 0) {
        return [];
    }
    const denied = requested.filter((scope) => !allowed.includes(scope));
    if (denied.length > 0) {
        return failure("SCOPE_DENIED", `office.pdfEncode scope ${denied[0]} is outside runtime governance`, "scope", context, outputPath);
    }
    return requested;
}
function normalizeTarget(target, context) {
    if (isBlank(context?.workspaceRoot)) {
        return failure("MISSING_WORKSPACE_ROOT", "office.pdfEncode requires context.workspaceRoot for scope auditing", "input", context);
    }
    if (isBlank(target?.outputPath)) {
        return failure("MISSING_OUTPUT_PATH", "office.pdfEncode requires target.outputPath", "input", context);
    }
    const outputPath = normalizeRelativePath(target?.outputPath);
    if (outputPath === undefined) {
        return failure("OUTPUT_OUT_OF_SCOPE", "office.pdfEncode outputPath must stay inside the declared workspace scope", "scope", context);
    }
    if (isBlank(target?.sourceLabel)) {
        return failure("MISSING_SOURCE_LABEL", "office.pdfEncode requires target.sourceLabel for audit and provenance", "input", context, outputPath);
    }
    const sourceFormat = normalizeSourceFormat(target?.sourceFormat, context, outputPath);
    if (typeof sourceFormat !== "string") {
        return sourceFormat;
    }
    const pageSize = normalizePageSize(target?.pageSize, context, outputPath);
    if (typeof pageSize === "object") {
        return pageSize;
    }
    return {
        outputPath,
        sourceFormat,
        sourceLabel: target?.sourceLabel?.trim() ?? "",
        title: target?.title?.trim() || undefined,
        pageSize,
    };
}
function operationPreview(target) {
    return [
        "encode",
        `from=${target.sourceFormat}`,
        `source=${target.sourceLabel}`,
        `output=${target.outputPath}`,
        `page-size=${target.pageSize ?? "runtime-default"}`,
    ];
}
export function planPdfEncode(request = {}) {
    const target = normalizeTarget(request.target, request.context);
    if ("ok" in target) {
        return target;
    }
    if (request.context?.dryRun === false) {
        return failure("REAL_EXECUTION_BLOCKED", "office.pdfEncode only returns a guarded dry-run plan in the first implementation", "contract", request.context, target.outputPath);
    }
    if (request.context?.contract?.accepted === false) {
        return failure("CONTRACT_REJECTED", request.context.contract.reason ?? "office.pdfEncode was rejected by runtime contract surface", "contract", request.context, target.outputPath);
    }
    if (request.context?.governance?.accepted === false) {
        return failure("GOVERNANCE_REJECTED", request.context.governance.reason ?? "office.pdfEncode was rejected by runtime governance", "governance", request.context, target.outputPath);
    }
    const acceptedScopes = resolveScopes(request.context, target.outputPath);
    if (!Array.isArray(acceptedScopes)) {
        return acceptedScopes;
    }
    return {
        ok: true,
        toolId: pdfEncodeDescriptor.toolId,
        plan: {
            kind: "agentCore.basicTool.office.pdfEncode",
            toolId: pdfEncodeDescriptor.toolId,
            capability: pdfEncodeDescriptor.capability,
            workspaceRoot: request.context?.workspaceRoot?.trim() ?? "",
            target,
            operationPreview: operationPreview(target),
            dryRun: true,
            executionBlocked: true,
            requiredPermissions: pdfEncodeDescriptor.permissionsRequired,
            requiresTapApproval: true,
            unsafeSideEffects: false,
            acceptedScopes,
            resultEnvelope: {
                outputPath: target.outputPath,
                bytesWritten: 0,
                pageCount: 0,
                artifactAvailable: false,
            },
        },
        audit: [
            auditEvent("agentCore.basicTool.office.pdfEncode.dryRun", request.context, target.outputPath, {
                sourceFormat: target.sourceFormat,
                sourceLabel: target.sourceLabel,
            }),
        ],
        events: ["basicTool.office.pdfEncode.dryRun"],
    };
}
