import { translate } from "../../shared/i18n.js";

const PROFILE_LABEL_KEYS = {
  ":read-only": "composer.permission.readOnly",
  ":workspace": "composer.permission.workspace",
  ":danger-full-access": "composer.permission.fullAccess"
};

const APPROVAL_POLICY_LABEL_KEYS = {
  untrusted: "composer.alwaysAsk",
  "on-failure": "composer.askOnFailure",
  "on-request": "composer.askWhenNeeded",
  never: "composer.neverAsk"
};

const english = (key, values) => translate("en", key, values);

export function selectedOrDefaultModel(models = [], selected = "") {
  return models.find((model) => model.model === selected || model.id === selected)
    ?? models.find((model) => model.isDefault)
    ?? models[0];
}

export function effectiveEffort(model, selected = "") {
  return selected || model?.defaultReasoningEffort || "medium";
}

export function effortLabel(value, t = english) {
  return t(`composer.effort.${value ?? "medium"}`);
}

export function reasoningEffortOptions(model, t = english) {
  const efforts = model?.reasoningEfforts;
  if (!Array.isArray(efforts)) return [];
  return efforts.map((effort) => ({ id: effort.id, label: effortLabel(effort.id, t), description: effort.description ?? "" }));
}

export function selectablePermissionProfiles(profiles = []) {
  return profiles.filter((profile) => profile?.allowed && typeof profile.id === "string" && profile.id);
}

export function permissionLabel(profiles = [], id = "", t = english) {
  const profile = profiles.find((item) => item.id === id);
  return PROFILE_LABEL_KEYS[id] ? t(PROFILE_LABEL_KEYS[id]) : profile?.id || t("composer.permission.workspace");
}

export function permissionDescription(profile, t = english) {
  if (profile?.description) return profile.description;
  if (profile?.id === ":read-only") return t("composer.permission.readOnly.description");
  if (profile?.id === ":workspace") return t("composer.permission.workspace.description");
  if (profile?.id === ":danger-full-access") return t("composer.permission.fullAccess.description");
  return "";
}

export function approvalPolicyLabel(policy, t = english) {
  return t(APPROVAL_POLICY_LABEL_KEYS[policy] ?? "composer.askWhenNeeded");
}

export function closeComposerModelMenu(menu, modelPicker) {
  if (menu) menu.open = false;
  if (modelPicker) modelPicker.open = false;
}

export function closeComposerPermissionMenu(menu) {
  if (menu) menu.open = false;
}

export function requiresFullAccessConfirmation(currentProfile, nextProfile) {
  return nextProfile === ":danger-full-access" && currentProfile !== ":danger-full-access";
}

export function modelButtonLabel(models, options, t = english) {
  const model = selectedOrDefaultModel(models, options.model);
  const modelName = model?.displayName || model?.model || t("composer.defaultModel");
  return `${modelName} · ${effortLabel(effectiveEffort(model, options.effort), t)}`;
}
