// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only

import { POLICY_TRIGGERS, type PackPolicyFactory, type PolicyRule } from '@lumenflow/kernel';
import { SIDEKICK_POLICY_ID_PREFIX } from './constants.js';

export const SIDEKICK_APPROVAL_REQUIRED_TOOL_NAMES = [
  'task:cancel',
  'memory:forget',
  'channel:delete',
  'routine:delete',
] as const;

const SIDEKICK_APPROVAL_REQUIRED_TOOL_NAME_SET = new Set<string>(
  SIDEKICK_APPROVAL_REQUIRED_TOOL_NAMES,
);

export function isSidekickApprovalRequiredToolName(toolName: string): boolean {
  return SIDEKICK_APPROVAL_REQUIRED_TOOL_NAME_SET.has(toolName);
}

export const createSidekickPolicyFactory: PackPolicyFactory = async () => {
  if (SIDEKICK_APPROVAL_REQUIRED_TOOL_NAME_SET.size === 0) {
    return [];
  }

  const approvalRule: PolicyRule = {
    id: `${SIDEKICK_POLICY_ID_PREFIX}.destructive-approval`,
    trigger: POLICY_TRIGGERS.ON_TOOL_REQUEST,
    decision: 'approval_required',
    reason: 'Destructive Sidekick tools require explicit approval before execution.',
    when: (context) =>
      typeof context.tool_name === 'string' &&
      isSidekickApprovalRequiredToolName(context.tool_name.trim()),
  };

  return [approvalRule];
};
