import type { prisma } from "@capakraken/db";
import type { PermissionKey, SystemRole } from "@capakraken/shared";
import type { TRPCContext } from "../../trpc.js";

export type ToolContext = {
  db: typeof prisma;
  userId: string;
  userRole: string;
  permissions: Set<PermissionKey>;
  session?: TRPCContext["session"];
  dbUser?: TRPCContext["dbUser"];
  roleDefaults?: TRPCContext["roleDefaults"];
};

export interface ToolAccessRequirements {
  requiredPermissions?: PermissionKey[];
  allowedSystemRoles?: SystemRole[];
  requiresPlanningRead?: boolean;
  requiresCostView?: boolean;
  requiresAdvancedAssistant?: boolean;
  requiresResourceOverview?: boolean;
}

export interface ToolDef {
  type: "function";
  function: {
    name: string;
    description: string;
    parameters: Record<string, unknown>;
  };
  access?: ToolAccessRequirements;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type ToolExecutor = (params: any, ctx: ToolContext) => Promise<unknown>;

export function withToolAccess(
  tools: ToolDef[],
  accessByName: Partial<Record<string, ToolAccessRequirements>>,
): ToolDef[] {
  return tools.map((tool) => ({
    ...tool,
    ...(accessByName[tool.function.name]
      ? { access: accessByName[tool.function.name] }
      : {}),
  }));
}
