import { normalizeAccountId } from "../routing/session-key.js";
import type { ClawdbotConfig } from "./config.js";

export type GroupPolicyProvider = "whatsapp" | "telegram" | "imessage";

export type ProviderGroupConfig = {
  requireMention?: boolean;
};

export type ProviderGroupPolicy = {
  allowlistEnabled: boolean;
  allowed: boolean;
  groupConfig?: ProviderGroupConfig;
  defaultConfig?: ProviderGroupConfig;
};

type ProviderGroups = Record<string, ProviderGroupConfig>;

function resolveProviderGroups(
  cfg: ClawdbotConfig,
  provider: GroupPolicyProvider,
  accountId?: string | null,
): ProviderGroups | undefined {
  const normalizedAccountId = normalizeAccountId(accountId);
  const providerConfig = (cfg as Record<string, unknown>)[provider] as
    | {
        accounts?: Record<string, { groups?: ProviderGroups }>;
        groups?: ProviderGroups;
      }
    | undefined;
  if (!providerConfig) return undefined;
  const accountGroups =
    providerConfig.accounts?.[normalizedAccountId]?.groups ??
    providerConfig.accounts?.[
      Object.keys(providerConfig.accounts ?? {}).find(
        (key) => key.toLowerCase() === normalizedAccountId.toLowerCase(),
      ) ?? ""
    ]?.groups;
  return accountGroups ?? providerConfig.groups;
}

export function resolveProviderGroupPolicy(params: {
  cfg: ClawdbotConfig;
  provider: GroupPolicyProvider;
  groupId?: string | null;
  accountId?: string | null;
}): ProviderGroupPolicy {
  const { cfg, provider } = params;
  const groups = resolveProviderGroups(cfg, provider, params.accountId);
  const allowlistEnabled = Boolean(groups && Object.keys(groups).length > 0);
  const normalizedId = params.groupId?.trim();
  const groupConfig = normalizedId && groups ? groups[normalizedId] : undefined;
  const defaultConfig = groups?.["*"];
  const allowAll =
    allowlistEnabled && Boolean(groups && Object.hasOwn(groups, "*"));
  const allowed =
    !allowlistEnabled ||
    allowAll ||
    (normalizedId
      ? Boolean(groups && Object.hasOwn(groups, normalizedId))
      : false);
  return {
    allowlistEnabled,
    allowed,
    groupConfig,
    defaultConfig,
  };
}

export function resolveProviderGroupRequireMention(params: {
  cfg: ClawdbotConfig;
  provider: GroupPolicyProvider;
  groupId?: string | null;
  accountId?: string | null;
  requireMentionOverride?: boolean;
  overrideOrder?: "before-config" | "after-config";
}): boolean {
  const { requireMentionOverride, overrideOrder = "after-config" } = params;
  const { groupConfig, defaultConfig } = resolveProviderGroupPolicy(params);
  const configMention =
    typeof groupConfig?.requireMention === "boolean"
      ? groupConfig.requireMention
      : typeof defaultConfig?.requireMention === "boolean"
        ? defaultConfig.requireMention
        : undefined;

  if (
    overrideOrder === "before-config" &&
    typeof requireMentionOverride === "boolean"
  ) {
    return requireMentionOverride;
  }
  if (typeof configMention === "boolean") return configMention;
  if (
    overrideOrder !== "before-config" &&
    typeof requireMentionOverride === "boolean"
  ) {
    return requireMentionOverride;
  }
  return true;
}
