/*
 * 文件定位：ToolabilityPool / TAP 高级工具系统 / Office 工具集合 / 表格工具。
 * 核心目的：提供 办公文档基础工具 / 表格工具 中的“视觉检查表格”基础能力原语。
 * 能力要求1：需要定义该能力的输入、输出、错误、权限需求和可观测事件。
 * 能力要求2：这些 Office 能力由 TAP 高级工具系统承接，不再作为 baseTool 完成目标。
 * 能力要求3：TAP 负责 Office 能力的治理、审批、组合和专业能力库承接。
 * 边界：承接 Office 高级工具能力，不回写到 agentCore baseTools。
 * 对接：通过 TAP 复用转交与 runtime 官方模块桥接接通，并保留治理、审批和审计边界。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
export const officeTableVisionCheckDescriptor = {
    toolId: "office.tableVisionCheck",
    capability: "vision-check-table",
    route: "toolabilityPool.officeBase.spreadsheet",
    defaultDryRun: true,
    tapOwnsApproval: true,
    permissionsRequired: ["filesystem:read", "office:read", "vision:analyze"],
    unsafeSideEffects: false,
};
const allowedChecks = [
    "layout",
    "overflow",
    "mergedCells",
    "numberFormat",
    "visualDiff",
];
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.tableVisionCheck:dry-run";
}
function auditEvent(type, context, targetPath, metadata) {
    return {
        type,
        toolId: officeTableVisionCheckDescriptor.toolId,
        invocationId: invocationId(context),
        dryRun: dryRunEnabled(context),
        targetPath,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context, targetPath) {
    return {
        ok: false,
        toolId: officeTableVisionCheckDescriptor.toolId,
        error: { code, message, boundary, publicSafe: true },
        audit: [auditEvent("agentCore.basicTool.office.tableVisionCheck.rejected", context, targetPath, { code })],
        events: ["basicTool.office.tableVisionCheck.rejected"],
    };
}
function normalizePath(workbookPath, context) {
    const normalized = workbookPath?.trim() ?? "";
    if (normalized.length === 0) {
        return failure("MISSING_WORKBOOK_PATH", "office.tableVisionCheck requires target.workbookPath", "input", context);
    }
    return normalized;
}
function normalizeRoot(root) {
    const trimmed = root.trim();
    return trimmed === "/" ? trimmed : trimmed.replace(/\/+$/, "");
}
function ensurePathInScope(pathValue, context) {
    const allowedRoots = cleanList(context?.allowedFileRoots).map(normalizeRoot);
    if (allowedRoots.length === 0) {
        return true;
    }
    return allowedRoots.some((root) => pathValue === root || pathValue.startsWith(`${root}/`));
}
function ensureScope(target, context) {
    if (!ensurePathInScope(target.workbookPath, context)) {
        return failure("SCOPE_REJECTED", "office.tableVisionCheck target workbook is outside the allowed file roots", "scope", context, target.workbookPath);
    }
    if (target.referenceImagePath !== undefined && !ensurePathInScope(target.referenceImagePath, context)) {
        return failure("SCOPE_REJECTED", "office.tableVisionCheck reference image is outside the allowed file roots", "scope", context, target.referenceImagePath);
    }
    return undefined;
}
function ensurePermissions(workbookPath, context) {
    const granted = cleanList(context?.grantedPermissions);
    if (granted.length === 0) {
        return undefined;
    }
    const missing = officeTableVisionCheckDescriptor.permissionsRequired.filter((permission) => !granted.includes(permission));
    if (missing.length === 0) {
        return undefined;
    }
    return failure("PERMISSION_DENIED", `office.tableVisionCheck is missing permissions: ${missing.join(", ")}`, "permission", context, workbookPath);
}
function ensureDryRunOnly(workbookPath, context) {
    if (dryRunEnabled(context)) {
        return undefined;
    }
    return failure("REAL_EXECUTION_BLOCKED", "office.tableVisionCheck only returns a guarded dry-run vision check plan in the first implementation", "contract", context, workbookPath);
}
function normalizeRange(range, context, workbookPath) {
    const normalized = range?.trim();
    if (normalized === undefined || normalized.length === 0) {
        return undefined;
    }
    if (/^[A-Za-z]{1,3}[1-9]\d*(?::[A-Za-z]{1,3}[1-9]\d*)?$/.test(normalized)) {
        return normalized.toUpperCase();
    }
    return failure("INVALID_RANGE", "office.tableVisionCheck target.range must be an A1 cell or A1 range", "input", context, workbookPath);
}
function normalizeChecks(checks, referenceImagePath, context, workbookPath) {
    if (checks === undefined || checks.length === 0) {
        return failure("MISSING_CHECKS", "office.tableVisionCheck requires at least one target check", "input", context, workbookPath);
    }
    const normalized = cleanList(checks);
    for (const check of normalized) {
        if (!allowedChecks.includes(check)) {
            return failure("INVALID_CHECK", "office.tableVisionCheck target.checks contains an unsupported check", "input", context, workbookPath);
        }
    }
    if (normalized.includes("visualDiff") && referenceImagePath === undefined) {
        return failure("MISSING_REFERENCE_IMAGE", "office.tableVisionCheck visualDiff requires target.referenceImagePath", "input", context, workbookPath);
    }
    return normalized;
}
function normalizeMaxFindings(maxFindings, context, workbookPath) {
    if (maxFindings === undefined) {
        return 50;
    }
    if (Number.isInteger(maxFindings) && maxFindings > 0 && maxFindings <= 1000) {
        return maxFindings;
    }
    return failure("INVALID_RESOURCE_LIMIT", "office.tableVisionCheck target.maxFindings must be a positive integer no greater than 1000", "input", context, workbookPath);
}
function normalizeTarget(target, context) {
    const workbookPath = normalizePath(target?.workbookPath, context);
    if (typeof workbookPath !== "string") {
        return workbookPath;
    }
    const range = normalizeRange(target?.range, context, workbookPath);
    if (range !== undefined && typeof range !== "string") {
        return range;
    }
    const referenceImagePath = target?.referenceImagePath?.trim() || undefined;
    const checks = normalizeChecks(target?.checks, referenceImagePath, context, workbookPath);
    if ("ok" in checks) {
        return checks;
    }
    const maxFindings = normalizeMaxFindings(target?.maxFindings, context, workbookPath);
    if (typeof maxFindings !== "number") {
        return maxFindings;
    }
    return {
        workbookPath,
        sheetName: target?.sheetName?.trim() || undefined,
        range,
        checks,
        referenceImagePath,
        maxFindings,
    };
}
export function planOfficeTableVisionCheck(request = {}) {
    const target = normalizeTarget(request.target, request.context);
    if ("ok" in target) {
        return target;
    }
    const scopeFailure = ensureScope(target, request.context);
    if (scopeFailure !== undefined) {
        return scopeFailure;
    }
    const permissionFailure = ensurePermissions(target.workbookPath, request.context);
    if (permissionFailure !== undefined) {
        return permissionFailure;
    }
    const realExecutionFailure = ensureDryRunOnly(target.workbookPath, request.context);
    if (realExecutionFailure !== undefined) {
        return realExecutionFailure;
    }
    return {
        ok: true,
        toolId: officeTableVisionCheckDescriptor.toolId,
        output: {
            kind: "agentCore.basicTool.office.tableVisionCheck",
            target,
            dryRun: true,
            executionBlocked: true,
            permissionsRequired: officeTableVisionCheckDescriptor.permissionsRequired,
            unsafeSideEffects: false,
            resultEnvelope: {
                workbookPath: target.workbookPath,
                sheetName: target.sheetName,
                range: target.range,
                findings: [],
                truncated: false,
                metadata: {
                    checks: target.checks,
                    referenceImagePath: target.referenceImagePath,
                    maxFindings: target.maxFindings,
                    requiresRenderedSnapshot: true,
                    providerCallPlanned: false,
                },
            },
        },
        audit: [
            auditEvent("agentCore.basicTool.office.tableVisionCheck.dryRun", request.context, target.workbookPath, {
                sheetName: target.sheetName,
                range: target.range,
                checks: target.checks,
                referenceImagePath: target.referenceImagePath,
            }),
        ],
        events: ["basicTool.office.tableVisionCheck.dryRun"],
    };
}
