/*
 * 文件定位：ToolabilityPool / TAP 高级工具系统 / Office 工具集合 / 演示文稿工具。
 * 核心目的：提供 办公文档基础工具 / 演示文稿工具 中的“定位演示文稿视觉区域”基础能力原语。
 * 能力要求1：需要定义该能力的输入、输出、错误、权限需求和可观测事件。
 * 能力要求2：这些 Office 能力由 TAP 高级工具系统承接，不再作为 baseTool 完成目标。
 * 能力要求3：TAP 负责 Office 能力的治理、审批、组合和专业能力库承接。
 * 边界：承接 Office 高级工具能力，不回写到 agentCore baseTools。
 * 对接：通过 TAP 复用转交与 runtime 官方模块桥接接通，并保留治理、审批和审计边界。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
export const officeSlidesVisionPositionDescriptor = {
    toolId: "office.slidesVisionPosition",
    capability: "position-slide-visual-region",
    route: "toolabilityPool.officeBase.presentations",
    defaultDryRun: true,
    tapOwnsApproval: true,
    permissionsRequired: ["filesystem:read", "office:read", "vision:read"],
    unsafeSideEffects: false,
};
function cleanList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
function dryRunEnabled(context) {
    return context?.dryRun !== false;
}
function invocationId(context) {
    return context?.invocationId?.trim() || "office.slidesVisionPosition:dry-run";
}
function auditEvent(type, context, targetPath, metadata) {
    return {
        type,
        toolId: officeSlidesVisionPositionDescriptor.toolId,
        invocationId: invocationId(context),
        dryRun: dryRunEnabled(context),
        targetPath,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context, targetPath) {
    return {
        ok: false,
        toolId: officeSlidesVisionPositionDescriptor.toolId,
        error: { code, message, boundary, publicSafe: true },
        audit: [auditEvent("agentCore.basicTool.office.slidesVisionPosition.rejected", context, targetPath, { code })],
        events: ["basicTool.office.slidesVisionPosition.rejected"],
    };
}
function normalizePath(presentationPath, context) {
    const normalized = presentationPath?.trim() ?? "";
    if (normalized.length === 0) {
        return failure("MISSING_PRESENTATION_PATH", "office.slidesVisionPosition requires target.presentationPath", "input", context);
    }
    return normalized;
}
function normalizeRoot(root) {
    const trimmed = root.trim();
    return trimmed === "/" ? trimmed : trimmed.replace(/\/+$/, "");
}
function ensureScope(presentationPath, context) {
    const allowedRoots = cleanList(context?.allowedFileRoots).map(normalizeRoot);
    if (allowedRoots.length === 0) {
        return undefined;
    }
    const allowed = allowedRoots.some((root) => presentationPath === root || presentationPath.startsWith(`${root}/`));
    if (allowed) {
        return undefined;
    }
    return failure("SCOPE_REJECTED", "office.slidesVisionPosition target presentation is outside the allowed file roots", "scope", context, presentationPath);
}
function ensurePermissions(presentationPath, context) {
    const granted = cleanList(context?.grantedPermissions);
    if (granted.length === 0) {
        return undefined;
    }
    const missing = officeSlidesVisionPositionDescriptor.permissionsRequired.filter((permission) => !granted.includes(permission));
    if (missing.length === 0) {
        return undefined;
    }
    return failure("PERMISSION_DENIED", `office.slidesVisionPosition is missing permissions: ${missing.join(", ")}`, "permission", context, presentationPath);
}
function ensureDryRunOnly(presentationPath, context) {
    if (dryRunEnabled(context)) {
        return undefined;
    }
    return failure("REAL_EXECUTION_BLOCKED", "office.slidesVisionPosition only returns a guarded dry-run vision-position plan in the first implementation", "contract", context, presentationPath);
}
function normalizeSlideNumber(slideNumber, context, presentationPath) {
    if (Number.isInteger(slideNumber) && slideNumber !== undefined && slideNumber > 0) {
        return slideNumber;
    }
    return failure("INVALID_SLIDE_NUMBER", "office.slidesVisionPosition target.slideNumber must be a positive integer", "input", context, presentationPath);
}
function normalizeCoordinateSpace(coordinateSpace, context, presentationPath) {
    if (coordinateSpace === undefined || coordinateSpace === "slide-pixels") {
        return "slide-pixels";
    }
    if (coordinateSpace === "normalized") {
        return "normalized";
    }
    return failure("INVALID_COORDINATE_SPACE", "office.slidesVisionPosition target.coordinateSpace must be slide-pixels or normalized", "input", context, presentationPath);
}
function normalizeMaxCandidates(maxCandidates, context, presentationPath) {
    if (maxCandidates === undefined) {
        return 5;
    }
    if (Number.isInteger(maxCandidates) && maxCandidates > 0 && maxCandidates <= 50) {
        return maxCandidates;
    }
    return failure("INVALID_RESOURCE_LIMIT", "office.slidesVisionPosition target.maxCandidates must be between 1 and 50", "input", context, presentationPath);
}
function normalizeTarget(target, context) {
    const presentationPath = normalizePath(target?.presentationPath, context);
    if (typeof presentationPath !== "string") {
        return presentationPath;
    }
    const slideNumber = normalizeSlideNumber(target?.slideNumber, context, presentationPath);
    if (typeof slideNumber !== "number") {
        return slideNumber;
    }
    const query = target?.query?.trim() ?? "";
    if (query.length === 0) {
        return failure("MISSING_QUERY", "office.slidesVisionPosition requires target.query describing the visual region to locate", "input", context, presentationPath);
    }
    const coordinateSpace = normalizeCoordinateSpace(target?.coordinateSpace, context, presentationPath);
    if (typeof coordinateSpace !== "string") {
        return coordinateSpace;
    }
    const maxCandidates = normalizeMaxCandidates(target?.maxCandidates, context, presentationPath);
    if (typeof maxCandidates !== "number") {
        return maxCandidates;
    }
    return {
        presentationPath,
        slideNumber,
        query,
        coordinateSpace,
        maxCandidates,
    };
}
export function planOfficeSlidesVisionPosition(request = {}) {
    const target = normalizeTarget(request.target, request.context);
    if ("ok" in target) {
        return target;
    }
    const scopeFailure = ensureScope(target.presentationPath, request.context);
    if (scopeFailure !== undefined) {
        return scopeFailure;
    }
    const permissionFailure = ensurePermissions(target.presentationPath, request.context);
    if (permissionFailure !== undefined) {
        return permissionFailure;
    }
    const realExecutionFailure = ensureDryRunOnly(target.presentationPath, request.context);
    if (realExecutionFailure !== undefined) {
        return realExecutionFailure;
    }
    return {
        ok: true,
        toolId: officeSlidesVisionPositionDescriptor.toolId,
        output: {
            kind: "agentCore.basicTool.office.slidesVisionPosition",
            target,
            dryRun: true,
            executionBlocked: true,
            permissionsRequired: officeSlidesVisionPositionDescriptor.permissionsRequired,
            unsafeSideEffects: false,
            resultEnvelope: {
                presentationPath: target.presentationPath,
                slideNumber: target.slideNumber,
                query: target.query,
                candidates: [],
                pendingVisionExecution: true,
            },
        },
        audit: [
            auditEvent("agentCore.basicTool.office.slidesVisionPosition.dryRun", request.context, target.presentationPath, {
                slideNumber: target.slideNumber,
                query: target.query,
                coordinateSpace: target.coordinateSpace,
                maxCandidates: target.maxCandidates,
            }),
        ],
        events: ["basicTool.office.slidesVisionPosition.dryRun"],
    };
}
