/*
 * 文件定位：ToolabilityPool / TAP 高级工具系统 / Office 工具集合 / PDF 工具。
 * 核心目的：提供 办公文档基础工具 / PDF 工具 中的“读取 PDF”基础能力原语。
 * 能力要求1：需要定义该能力的输入、输出、错误、权限需求和可观测事件。
 * 能力要求2：这些 Office 能力由 TAP 高级工具系统承接，不再作为 baseTool 完成目标。
 * 能力要求3：TAP 负责 Office 能力的治理、审批、组合和专业能力库承接。
 * 边界：承接 Office 高级工具能力，不回写到 agentCore baseTools。
 * 对接：通过 TAP 复用转交与 runtime 官方模块桥接接通，并保留治理、审批和审计边界。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
export const pdfReadDescriptor = {
    toolId: "office.pdfRead",
    capability: "read-pdf",
    route: "toolabilityPool.officeBase.Portable_Document_Format",
    defaultDryRun: true,
    tapOwnsApproval: true,
    permissionsRequired: ["filesystem:read"],
    unsafeSideEffects: false,
};
const readViews = ["text", "metadata", "outline", "page-preview"];
function isBlank(value) {
    return typeof value !== "string" || value.trim().length === 0;
}
function invocationId(context) {
    return context?.invocationId?.trim() || "office.pdfRead:dry-run";
}
function cleanList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
function auditEvent(type, context, sourcePath, metadata) {
    return {
        type,
        toolId: pdfReadDescriptor.toolId,
        invocationId: invocationId(context),
        dryRun: true,
        sourcePath,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context, sourcePath) {
    return {
        ok: false,
        toolId: pdfReadDescriptor.toolId,
        error: {
            code,
            message,
            boundary,
            safeForRuntimeInspection: true,
            internalDetailExposed: false,
        },
        audit: [auditEvent("agentCore.basicTool.office.pdfRead.rejected", context, sourcePath, { code })],
        events: ["basicTool.office.pdfRead.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 normalizeView(view, context) {
    if (view === undefined || view.trim() === "") {
        return "text";
    }
    if (readViews.includes(view)) {
        return view;
    }
    return failure("INVALID_READ_VIEW", "office.pdfRead target.view must be text, metadata, outline, or page-preview", "input", context);
}
function validatePageRange(pageRange, context, sourcePath) {
    if (pageRange === undefined) {
        return undefined;
    }
    if (Number.isInteger(pageRange.startPage) &&
        Number.isInteger(pageRange.endPage) &&
        pageRange.startPage > 0 &&
        pageRange.endPage >= pageRange.startPage) {
        return undefined;
    }
    return failure("INVALID_PAGE_RANGE", "office.pdfRead pageRange must use positive startPage and endPage values", "input", context, sourcePath);
}
function validateMaxPages(maxPages, context, sourcePath) {
    if (maxPages === undefined) {
        return undefined;
    }
    if (Number.isInteger(maxPages) && maxPages > 0) {
        return undefined;
    }
    return failure("INVALID_MAX_PAGES", "office.pdfRead maxPages must be a positive integer", "input", context, sourcePath);
}
function resolveScopes(context, sourcePath) {
    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.pdfRead scope ${denied[0]} is outside runtime governance`, "scope", context, sourcePath);
    }
    return requested;
}
function normalizeTarget(target, context) {
    if (isBlank(context?.workspaceRoot)) {
        return failure("MISSING_WORKSPACE_ROOT", "office.pdfRead requires context.workspaceRoot for scope auditing", "input", context);
    }
    if (isBlank(target?.sourcePath)) {
        return failure("MISSING_SOURCE_PATH", "office.pdfRead requires target.sourcePath", "input", context);
    }
    const sourcePath = normalizeRelativePath(target?.sourcePath);
    if (sourcePath === undefined) {
        return failure("SOURCE_OUT_OF_SCOPE", "office.pdfRead sourcePath must stay inside the declared workspace scope", "scope", context);
    }
    const view = normalizeView(target?.view, context);
    if (typeof view !== "string") {
        return view;
    }
    const pageRangeFailure = validatePageRange(target?.pageRange, context, sourcePath);
    if (pageRangeFailure !== undefined) {
        return pageRangeFailure;
    }
    const maxPagesFailure = validateMaxPages(target?.maxPages, context, sourcePath);
    if (maxPagesFailure !== undefined) {
        return maxPagesFailure;
    }
    return {
        sourcePath,
        view,
        pageRange: target?.pageRange,
        maxPages: target?.maxPages,
    };
}
function operationPreview(target) {
    return [
        "read",
        target.sourcePath,
        `view=${target.view ?? "text"}`,
        ...(target.pageRange === undefined ? [] : [`pages=${target.pageRange.startPage}-${target.pageRange.endPage}`]),
        ...(target.maxPages === undefined ? [] : [`max-pages=${target.maxPages}`]),
    ];
}
export function planPdfRead(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.pdfRead only returns a guarded dry-run plan in the first implementation", "contract", request.context, target.sourcePath);
    }
    if (request.context?.contract?.accepted === false) {
        return failure("CONTRACT_REJECTED", request.context.contract.reason ?? "office.pdfRead was rejected by runtime contract surface", "contract", request.context, target.sourcePath);
    }
    if (request.context?.governance?.accepted === false) {
        return failure("GOVERNANCE_REJECTED", request.context.governance.reason ?? "office.pdfRead was rejected by runtime governance", "governance", request.context, target.sourcePath);
    }
    const acceptedScopes = resolveScopes(request.context, target.sourcePath);
    if (!Array.isArray(acceptedScopes)) {
        return acceptedScopes;
    }
    return {
        ok: true,
        toolId: pdfReadDescriptor.toolId,
        plan: {
            kind: "agentCore.basicTool.office.pdfRead",
            toolId: pdfReadDescriptor.toolId,
            capability: pdfReadDescriptor.capability,
            workspaceRoot: request.context?.workspaceRoot?.trim() ?? "",
            target,
            operationPreview: operationPreview(target),
            dryRun: true,
            executionBlocked: true,
            requiredPermissions: pdfReadDescriptor.permissionsRequired,
            requiresTapApproval: false,
            unsafeSideEffects: false,
            acceptedScopes,
            resultEnvelope: {
                pages: [],
                metadata: {},
                outline: [],
            },
        },
        audit: [
            auditEvent("agentCore.basicTool.office.pdfRead.dryRun", request.context, target.sourcePath, {
                view: target.view,
                maxPages: target.maxPages,
            }),
        ],
        events: ["basicTool.office.pdfRead.dryRun"],
    };
}
