// 遗留兼容：当前 AI 主链已转到 Hermes bridge，这里的 registry 仅保留给历史测试/兼容调用，不再作为前端主编排入口。
import type { AiAgentTool, AiAgentToolSet, ToolPermissions } from "./types";

export type ToolRegistry = {
  toolsById: Map<string, AiAgentTool>;
  toolSetsById: Map<string, AiAgentToolSet>;
  permissions: ToolPermissions;
};

export const createToolRegistry = (args: {
  tools: AiAgentTool[];
  toolSets: AiAgentToolSet[];
  permissions?: Partial<ToolPermissions>;
}): ToolRegistry => {
  const toolsById = new Map<string, AiAgentTool>();
  for (const t of args.tools) toolsById.set(t.id, t);

  const toolSetsById = new Map<string, AiAgentToolSet>();
  for (const s of args.toolSets) toolSetsById.set(s.id, s);

  const permissions: ToolPermissions = {
    read: args.permissions?.read ?? "allow",
    write: args.permissions?.write ?? "confirm",
  };

  return { toolsById, toolSetsById, permissions };
};

export const resolveAllowedToolIds = (args: {
  registry: ToolRegistry;
  mode: "auto" | "manual";
  toolSetIds?: string[];
  toolIds?: string[];
}) => {
  const allowed = new Set<string>();

  if (args.mode === "auto") {
    // v1：auto 默认启用 readonly；若显式传入 toolSets，则在这些集合内自动选择
    const toolSetIds = Array.isArray(args.toolSetIds) ? args.toolSetIds : [];
    if (toolSetIds.length) {
      for (const sid of toolSetIds) {
        const s = args.registry.toolSetsById.get(String(sid));
        s?.toolIds.forEach((id) => allowed.add(id));
      }
      if (allowed.size > 0) return allowed;
    }
    const readonly = args.registry.toolSetsById.get("toolset.readonly");
    readonly?.toolIds.forEach((id) => allowed.add(id));
    return allowed;
  }

  const toolSetIds = Array.isArray(args.toolSetIds) ? args.toolSetIds : [];
  for (const sid of toolSetIds) {
    const s = args.registry.toolSetsById.get(String(sid));
    s?.toolIds.forEach((id) => allowed.add(id));
  }

  const toolIds = Array.isArray(args.toolIds) ? args.toolIds : [];
  for (const tid of toolIds) {
    if (args.registry.toolsById.has(String(tid))) allowed.add(String(tid));
  }

  // 手动模式但用户未选：至少保留 readonly，避免完全不可用
  if (allowed.size === 0) {
    const readonly = args.registry.toolSetsById.get("toolset.readonly");
    readonly?.toolIds.forEach((id) => allowed.add(id));
  }

  return allowed;
};
