import type { StoredMessage } from '../db/messages.js';

const DEFAULT_MESSAGE_LIMIT = 25;
const MAX_MESSAGE_LIMIT = 250;
const MAX_TIME_WINDOW_SECONDS = 52 * 7 * 24 * 60 * 60;
const MAX_HISTORY_BYTES = 24 * 1024;

function getTodayStart(): number {
  const date = new Date();
  return Math.floor(new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() / 1000);
}

export function parseTimeWindow(question: string): { fromDate?: number; limit: number } {
  const normalized = question.toLowerCase();
  const now = Math.floor(Date.now() / 1000);
  const match = normalized.match(/(?:last|past)\s+(\d+)\s+(minute|hour|day|week)s?/);

  if (match) {
    const count = parseInt(match[1]!, 10);
    const multipliers: Record<string, number> = {
      minute: 60,
      hour: 3600,
      day: 86400,
      week: 604800,
    };
    const seconds = Math.min(count * multipliers[match[2]!]!, MAX_TIME_WINDOW_SECONDS);
    return { fromDate: Math.max(0, now - seconds), limit: MAX_MESSAGE_LIMIT };
  }

  if (/\blast\s+hour\b/.test(normalized)) return { fromDate: now - 3600, limit: MAX_MESSAGE_LIMIT };
  if (/\blast\s+week\b/.test(normalized)) return { fromDate: now - 604800, limit: MAX_MESSAGE_LIMIT };
  if (/\blast\s+day\b/.test(normalized) || /\byesterday\b/.test(normalized)) {
    return { fromDate: now - 86400, limit: MAX_MESSAGE_LIMIT };
  }
  if (/\btoday\b/.test(normalized)) return { fromDate: getTodayStart(), limit: MAX_MESSAGE_LIMIT };

  return { limit: DEFAULT_MESSAGE_LIMIT };
}

export function formatHistory(messages: StoredMessage[], maxBytes = MAX_HISTORY_BYTES): string {
  const lines = messages.map((message) => {
    const sender = message.username ? `@${message.username}` : (message.first_name ?? 'Unknown');
    const time = new Date(message.date * 1000).toLocaleString('he-IL', { timeZone: 'Asia/Jerusalem' });
    return `[${time}] ${sender}: ${message.text}`;
  });
  const selected: string[] = [];
  let bytes = 0;

  for (let index = lines.length - 1; index >= 0; index -= 1) {
    const line = lines[index]!;
    const separatorBytes = selected.length === 0 ? 0 : 1;
    const lineBytes = Buffer.byteLength(line, 'utf8');
    if (bytes + separatorBytes + lineBytes > maxBytes) continue;
    selected.unshift(line);
    bytes += separatorBytes + lineBytes;
  }

  return selected.join('\n');
}
