/*
 * Runtime Web – Unified Serverless Framework for Full-Stack TypeScript Applications
 * Documentation: https://runtimeweb.com/docs/getting-started
 *
 * @template: ai-chat
 */

/**
 * Message Parsing Utilities
 *
 * Utilities for parsing AI model responses that may contain
 * reasoning tags and markdown content.
 *
 * @module utils/parse-message
 */

/**
 * Parsed message content with separated reasoning and main content.
 */
export interface ParsedMessage {
    /** Reasoning sections extracted from <reasoning> tags */
    reasoning: string[];
    /** Main content with reasoning tags removed */
    content: string;
}

/**
 * Regex pattern to match <reasoning>...</reasoning> tags.
 * Supports multiline content and multiple occurrences.
 */
const REASONING_PATTERN = /<reasoning>([\s\S]*?)<\/reasoning>/gi;

/**
 * Parses a message to extract reasoning sections and clean content.
 *
 * Some AI models (e.g., OpenAI models on Bedrock) include reasoning
 * in <reasoning> tags. This function extracts those sections for
 * separate display while preserving the main response content.
 *
 * @param rawContent - The raw message content from the AI model
 * @returns Parsed message with separated reasoning and content
 *
 * @example
 * ```typescript
 * const result = parseMessage('<reasoning>Thinking...</reasoning>Hello!');
 * // result.reasoning = ['Thinking...']
 * // result.content = 'Hello!'
 * ```
 */
export function parseMessage(rawContent: string): ParsedMessage {
    const reasoning: string[] = [];
    let content = rawContent;

    // Extract all reasoning sections
    let match: RegExpExecArray | null;
    while ((match = REASONING_PATTERN.exec(rawContent)) !== null) {
        reasoning.push(match[1].trim());
    }

    // Remove reasoning tags from content
    content = rawContent.replace(REASONING_PATTERN, '').trim();

    return { reasoning, content };
}

/**
 * Checks if a message contains reasoning tags.
 *
 * @param content - The message content to check
 * @returns True if the content contains reasoning tags
 */
export function hasReasoning(content: string): boolean {
    return REASONING_PATTERN.test(content);
}
