/*
 * 文件定位：ToolabilityPool / TAP 高级工具系统 / Office 工具集合 / 表格工具。
 * 核心目的：提供 办公文档基础工具 / 表格工具 中的“编码表格”基础能力原语。
 * 能力要求1：需要定义该能力的输入、输出、错误、权限需求和可观测事件。
 * 能力要求2：这些 Office 能力由 TAP 高级工具系统承接，不再作为 baseTool 完成目标。
 * 能力要求3：TAP 负责 Office 能力的治理、审批、组合和专业能力库承接。
 * 边界：承接 Office 高级工具能力，不回写到 agentCore baseTools。
 * 对接：通过 TAP 复用转交与 runtime 官方模块桥接接通，并保留治理、审批和审计边界。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
export const officeTableEncodeDescriptor = {
    toolId: "office.tableEncode",
    capability: "encode-table",
    route: "toolabilityPool.officeBase.spreadsheet",
    defaultDryRun: true,
    tapOwnsApproval: true,
    permissionsRequired: ["filesystem:write", "office:write"],
    unsafeSideEffects: true,
};
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.tableEncode:dry-run";
}
function auditEvent(type, context, targetPath, metadata) {
    return {
        type,
        toolId: officeTableEncodeDescriptor.toolId,
        invocationId: invocationId(context),
        dryRun: dryRunEnabled(context),
        targetPath,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context, targetPath) {
    return {
        ok: false,
        toolId: officeTableEncodeDescriptor.toolId,
        error: { code, message, boundary, publicSafe: true },
        audit: [auditEvent("agentCore.basicTool.office.tableEncode.rejected", context, targetPath, { code })],
        events: ["basicTool.office.tableEncode.rejected"],
    };
}
function normalizePath(outputPath, context) {
    const normalized = outputPath?.trim() ?? "";
    if (normalized.length === 0) {
        return failure("MISSING_OUTPUT_PATH", "office.tableEncode requires target.outputPath", "input", context);
    }
    return normalized;
}
function normalizeRoot(root) {
    const trimmed = root.trim();
    return trimmed === "/" ? trimmed : trimmed.replace(/\/+$/, "");
}
function ensureScope(outputPath, context) {
    const allowedRoots = cleanList(context?.allowedFileRoots).map(normalizeRoot);
    if (allowedRoots.length === 0) {
        return undefined;
    }
    const allowed = allowedRoots.some((root) => outputPath === root || outputPath.startsWith(`${root}/`));
    if (allowed) {
        return undefined;
    }
    return failure("SCOPE_REJECTED", "office.tableEncode target output is outside the allowed file roots", "scope", context, outputPath);
}
function ensurePermissions(outputPath, context) {
    const granted = cleanList(context?.grantedPermissions);
    if (granted.length === 0) {
        return undefined;
    }
    const missing = officeTableEncodeDescriptor.permissionsRequired.filter((permission) => !granted.includes(permission));
    if (missing.length === 0) {
        return undefined;
    }
    return failure("PERMISSION_DENIED", `office.tableEncode is missing permissions: ${missing.join(", ")}`, "permission", context, outputPath);
}
function ensureDryRunOnly(outputPath, context) {
    if (dryRunEnabled(context)) {
        return undefined;
    }
    return failure("REAL_EXECUTION_BLOCKED", "office.tableEncode only returns a guarded dry-run encode plan in the first implementation", "contract", context, outputPath);
}
function normalizeFormat(format, context, outputPath) {
    if (format === undefined || format === "xlsx") {
        return "xlsx";
    }
    if (format === "csv" || format === "tsv") {
        return format;
    }
    return failure("INVALID_FORMAT", "office.tableEncode target.format must be xlsx, csv, or tsv", "input", context, outputPath);
}
function normalizeSheets(sheets, context, outputPath) {
    if (sheets === undefined || sheets.length === 0) {
        return failure("MISSING_SHEETS", "office.tableEncode requires at least one target sheet", "input", context, outputPath);
    }
    if (sheets.length > 50) {
        return failure("RESOURCE_LIMIT_EXCEEDED", "office.tableEncode supports at most 50 sheets in the first implementation", "input", context, outputPath);
    }
    const normalized = [];
    for (const sheet of sheets) {
        const name = sheet.name?.trim() ?? "";
        if (name.length === 0) {
            return failure("MISSING_SHEET_NAME", "office.tableEncode sheet.name is required", "input", context, outputPath);
        }
        if (sheet.rows === undefined || sheet.rows.length === 0) {
            return failure("MISSING_ROWS", "office.tableEncode sheet.rows must contain at least one row", "input", context, outputPath);
        }
        if (sheet.rows.length > 10000) {
            return failure("RESOURCE_LIMIT_EXCEEDED", "office.tableEncode supports at most 10000 rows per sheet", "input", context, outputPath);
        }
        normalized.push({
            name,
            rows: sheet.rows.map((row) => [...row]),
        });
    }
    return normalized;
}
function normalizeTarget(target, context) {
    const outputPath = normalizePath(target?.outputPath, context);
    if (typeof outputPath !== "string") {
        return outputPath;
    }
    const format = normalizeFormat(target?.format, context, outputPath);
    if (typeof format !== "string") {
        return format;
    }
    const sheets = normalizeSheets(target?.sheets, context, outputPath);
    if ("ok" in sheets) {
        return sheets;
    }
    return {
        outputPath,
        format,
        sheets,
        overwrite: target?.overwrite === true,
    };
}
function rowCount(sheets) {
    return sheets.reduce((sum, sheet) => sum + sheet.rows.length, 0);
}
function cellCount(sheets) {
    return sheets.reduce((sum, sheet) => sum + sheet.rows.reduce((rowSum, row) => rowSum + row.length, 0), 0);
}
export function planOfficeTableEncode(request = {}) {
    const target = normalizeTarget(request.target, request.context);
    if ("ok" in target) {
        return target;
    }
    const scopeFailure = ensureScope(target.outputPath, request.context);
    if (scopeFailure !== undefined) {
        return scopeFailure;
    }
    const permissionFailure = ensurePermissions(target.outputPath, request.context);
    if (permissionFailure !== undefined) {
        return permissionFailure;
    }
    const realExecutionFailure = ensureDryRunOnly(target.outputPath, request.context);
    if (realExecutionFailure !== undefined) {
        return realExecutionFailure;
    }
    return {
        ok: true,
        toolId: officeTableEncodeDescriptor.toolId,
        output: {
            kind: "agentCore.basicTool.office.tableEncode",
            target,
            dryRun: true,
            executionBlocked: true,
            permissionsRequired: officeTableEncodeDescriptor.permissionsRequired,
            unsafeSideEffects: true,
            writePlan: {
                format: target.format,
                sheetCount: target.sheets.length,
                rowCount: rowCount(target.sheets),
                cellCount: cellCount(target.sheets),
                overwrite: target.overwrite,
            },
        },
        audit: [
            auditEvent("agentCore.basicTool.office.tableEncode.dryRun", request.context, target.outputPath, {
                format: target.format,
                sheetCount: target.sheets.length,
                overwrite: target.overwrite,
            }),
        ],
        events: ["basicTool.office.tableEncode.dryRun"],
    };
}
