import type {
  AgentBuiltinToolConfig,
  AgentBuiltinToolsConfig,
  AgentExecutionConfig,
} from './types';

export const AGENT_BUILTIN_TOOL_KEYS = [
  'read',
  'write',
  'patch',
  'shell',
  'artifactPublish',
] as const;

export type AgentBuiltinToolKey = (typeof AGENT_BUILTIN_TOOL_KEYS)[number];

type AgentBuiltinToolsInput = Partial<
  Record<AgentBuiltinToolKey, Partial<AgentBuiltinToolConfig>>
> & {
  schemaVersion?: number;
  shellApprovalRiskConfirmed?: boolean;
};

const DEFAULT_BUILTIN_TOOLS: AgentBuiltinToolsConfig = {
  schemaVersion: 1,
  read: { approvalRequired: false, enabled: true },
  write: { approvalRequired: false, enabled: true },
  patch: { approvalRequired: false, enabled: true },
  shell: { approvalRequired: true, enabled: true },
  artifactPublish: { approvalRequired: false, enabled: true },
};

/**
 * 创建新 Agent 使用的内置工具默认配置。
 *
 * @returns 五项工具全部启用、仅 Shell 默认确认的独立配置副本。
 */
export function createDefaultBuiltinTools(): AgentBuiltinToolsConfig {
  return {
    artifactPublish: { ...DEFAULT_BUILTIN_TOOLS.artifactPublish },
    patch: { ...DEFAULT_BUILTIN_TOOLS.patch },
    read: { ...DEFAULT_BUILTIN_TOOLS.read },
    schemaVersion: 1,
    shell: { ...DEFAULT_BUILTIN_TOOLS.shell },
    write: { ...DEFAULT_BUILTIN_TOOLS.write },
  };
}

/**
 * 将接口中的内置工具配置补全为稳定的五项结构。
 *
 * @param value 接口返回的可选配置。
 * @returns 可直接用于表单和保存载荷的规范化配置。
 */
export function normalizeBuiltinTools(
  value?: AgentBuiltinToolsInput,
): AgentBuiltinToolsConfig {
  const defaults = createDefaultBuiltinTools();
  const normalizeTool = (key: AgentBuiltinToolKey) => ({
    approvalRequired:
      value?.[key]?.approvalRequired ?? defaults[key].approvalRequired,
    enabled: value?.[key]?.enabled ?? defaults[key].enabled,
  });
  const normalized: AgentBuiltinToolsConfig = {
    artifactPublish: normalizeTool('artifactPublish'),
    patch: normalizeTool('patch'),
    read: normalizeTool('read'),
    schemaVersion: 1,
    shell: normalizeTool('shell'),
    write: normalizeTool('write'),
  };
  if (value && 'shellApprovalRiskConfirmed' in value) {
    normalized.shellApprovalRiskConfirmed = Boolean(
      value.shellApprovalRiskConfirmed,
    );
  }
  return normalized;
}

/**
 * 构造保存和草稿试用共用的执行配置。
 *
 * @param value 当前执行配置。
 * @param canDisableShellApproval 当前用户是否可关闭 Shell 调用确认。
 * @returns 已补齐默认值并落实 Shell 权限边界的配置。
 */
export function buildAgentExecutionConfig(
  value: AgentExecutionConfig | undefined,
  canDisableShellApproval: boolean,
): AgentExecutionConfig {
  const builtinTools = normalizeBuiltinTools(value?.builtinTools);
  if (!canDisableShellApproval) {
    builtinTools.shell.approvalRequired = true;
  }
  if (builtinTools.shell.approvalRequired) {
    delete builtinTools.shellApprovalRiskConfirmed;
  }
  return {
    ...value,
    builtinTools,
    documentContextBudgetTokens: Math.max(
      1,
      Math.trunc(Number(value?.documentContextBudgetTokens) || 20_000),
    ),
  };
}
