import type { KittyVisibility, MessageSource, NotificationAction } from "./types.ts";

export function parseMessageSource(value: string | undefined): MessageSource {
  const normalized = value?.trim().toLowerCase();
  if (normalized === "user" || normalized === "none") return normalized;
  return "assistant";
}

export function parseMessageMax(value: string | undefined): number {
  return parseBoundedInteger(value, 80, 0, 500);
}

export function parseMinDurationMs(value: string | undefined): number {
  const seconds = parseBoundedNumber(value, 3, 0, 3600);
  return Math.round(seconds * 1000);
}

export function parseEnabled(value: string | undefined): boolean {
  if (value === undefined) return true;
  return !["0", "false", "no", "off"].includes(value.trim().toLowerCase());
}

export function parseKittyVisibility(value: string | undefined): KittyVisibility {
  const normalized = value?.trim().toLowerCase();
  if (normalized === "always" || normalized === "unfocused" || normalized === "invisible") return normalized;
  return "always";
}

export function parseNotificationAction(value: string | undefined): NotificationAction {
  return value?.trim().toLowerCase() === "none" ? "none" : "focus";
}

function parseBoundedInteger(value: string | undefined, fallback: number, min: number, max: number): number {
  const parsed = Number.parseInt(value || String(fallback), 10);
  if (!Number.isFinite(parsed)) return fallback;
  return Math.max(min, Math.min(parsed, max));
}

function parseBoundedNumber(value: string | undefined, fallback: number, min: number, max: number): number {
  const normalized = value?.trim();
  const parsed = Number(normalized ? normalized : fallback);
  if (!Number.isFinite(parsed)) return fallback;
  return Math.max(min, Math.min(parsed, max));
}
