/**
 * Timer System - Delay calculation module
 *
 * Calculates realistic response delays including:
 * - Configurable base delay range
 * - Typing duration based on message length
 * - Night time multiplier for slower responses during night hours
 *
 * Requirements: 5.1, 5.5
 */

export interface TimerConfig {
  baseDelay: { min: number; max: number };         // Base delay range (seconds)
  busyScenarioDelay: { min: number; max: number }; // Busy scenario delay (minutes)
  typingSpeedCps: number;                          // Characters per second typing speed
  nightHours: { start: number; end: number };      // Night hours (e.g., 23-07)
  nightMultiplier: number;                         // Night delay multiplier (e.g., 2.5)
}

export const DEFAULT_TIMER_CONFIG: TimerConfig = {
  baseDelay: { min: 5, max: 30 },
  busyScenarioDelay: { min: 15, max: 45 },
  typingSpeedCps: 5,
  nightHours: { start: 23, end: 7 },
  nightMultiplier: 2.5,
};

/**
 * Returns a random number between min and max (inclusive).
 */
function randomBetween(min: number, max: number): number {
  return min + Math.random() * (max - min);
}

/**
 * Checks if the given hour falls within night hours.
 * Night hours wrap around midnight (e.g., 23:00 to 07:00).
 */
export function isNightTime(hour: number, config: TimerConfig): boolean {
  const { start, end } = config.nightHours;
  if (start > end) {
    // Wraps around midnight: e.g., 23-07 means hour >= 23 OR hour < 7
    return hour >= start || hour < end;
  }
  // Non-wrapping range: e.g., 1-5 means hour >= 1 AND hour < 5
  return hour >= start && hour < end;
}

/**
 * Calculates typing animation duration based on message length and typing speed.
 * Returns duration in seconds.
 */
export function calculateTypingDuration(messageLength: number, cps: number): number {
  if (messageLength <= 0) return 0;
  if (cps <= 0) return 0;
  return messageLength / cps;
}

/**
 * Calculates total response delay in seconds.
 *
 * Total delay = base delay (with optional night multiplier) + typing duration
 */
export function calculateDelay(config: TimerConfig, messageLength: number, hour: number): number {
  let delay = randomBetween(config.baseDelay.min, config.baseDelay.max);

  if (isNightTime(hour, config)) {
    delay *= config.nightMultiplier;
  }

  const typingDuration = calculateTypingDuration(messageLength, config.typingSpeedCps);
  return delay + typingDuration;
}
