export const TEAMS_MAX_CHARS = 4000;

export function chunkText(text: string): string[] {
  if (text.length <= TEAMS_MAX_CHARS) return [text];
  const chunks: string[] = [];
  let remaining = text;
  while (remaining.length > 0) {
    if (remaining.length <= TEAMS_MAX_CHARS) {
      chunks.push(remaining);
      break;
    }
    let breakAt = remaining.lastIndexOf("\n", TEAMS_MAX_CHARS);
    if (breakAt < TEAMS_MAX_CHARS / 2) {
      breakAt = remaining.lastIndexOf(" ", TEAMS_MAX_CHARS);
    }
    if (breakAt < TEAMS_MAX_CHARS / 2) {
      breakAt = TEAMS_MAX_CHARS;
    }
    chunks.push(remaining.slice(0, breakAt));
    remaining = remaining.slice(breakAt).trimStart();
  }
  return chunks;
}

export function stripMentionTags(text: string): string {
  return text.replace(/<at[^>]*>.*?<\/at>/gi, "").trim();
}

export function wasBotMentioned(
  activity: { recipient?: { id?: string }; entities?: Array<{ type?: string; mentioned?: { id?: string } }> },
): boolean {
  const botId = activity.recipient?.id;
  if (!botId) return false;
  const entities = activity.entities;
  if (!entities) return false;
  return entities.some((e) => e.type === "mention" && e.mentioned?.id === botId);
}

export function normalizeConversationId(raw: string): string {
  return raw.split(";")[0] ?? raw;
}

export function escapeXml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}

export function sanitizeFilename(name: string): string {
  return name.replace(/[^a-zA-Z0-9._-]/g, "_");
}

/**
 * Accumulate streamed text. Each chunk from the caller should be the full
 * accumulated text so far. If it extends the prior content, we use it as-is.
 * If it's shorter or unrelated, we append it.
 */
export function accumulateStreamText(prior: string, incoming: string): string {
  if (incoming.startsWith(prior)) {
    return incoming;
  }
  return prior + incoming;
}
