'use strict';

const { getDefaultClient, getDefaultModel } = require('../llm/client');

const SYSTEM_PROMPT = `You are a dictation post-processor. Your ONLY job is to add punctuation and fix capitalization in speech-to-text output. Rules:
- Add periods, commas, question marks, exclamation marks where appropriate
- Fix capitalization (sentence starts, proper nouns)
- For Chinese text, use Chinese punctuation (，。？！、）
- For mixed Chinese/English text, keep both languages, use appropriate punctuation for each
- Fix obvious speech recognition errors (e.g., homophones) only if very confident
- Do NOT change wording, rephrase, summarize, or add content
- Do NOT add quotes, markdown, or any wrapper — return ONLY the corrected text
- If the text is already well-punctuated, return it unchanged`;

/**
 * Refine dictation text using LLM.
 * @param {string} text - Raw SR transcript
 * @param {string} [lang] - Language code (e.g., 'en-US', 'zh-CN')
 * @param {string} [context] - Mode context ('dictation', 'dictation-chat', 'dictation-prompt')
 * @returns {Promise<{refined: string, lang: string}>}
 */
async function refine(text, lang, context) {
  if (!text || !text.trim()) return { refined: text, lang: lang || 'en-US' };

  const client = getDefaultClient();
  if (!client) return { refined: text, lang: lang || 'en-US' };

  const langHint = lang ? ` The speaker's language setting is ${lang}.` : '';
  const contextHint = context === 'dictation-chat' ? ' This is informal chat.' :
                      context === 'dictation-prompt' ? ' This is a technical prompt.' : '';

  const userMsg = `Add punctuation and fix capitalization.${langHint}${contextHint}\n\nRaw text: ${text}`;

  try {
    const model = getDefaultModel();
    const result = await client.chat(
      [
        { role: 'system', content: SYSTEM_PROMPT },
        { role: 'user', content: userMsg }
      ],
      { model, maxTokens: Math.max(200, text.length * 2), temperature: 0 }
    );

    // Extract text from result — handle different provider response formats
    let refined = '';
    if (typeof result === 'string') refined = result;
    else if (result && result.content) {
      if (typeof result.content === 'string') refined = result.content;
      else if (Array.isArray(result.content)) {
        refined = result.content
          .filter(b => b.type === 'text')
          .map(b => b.text)
          .join('');
      }
    }

    return { refined: refined.trim() || text, lang: lang || 'en-US' };
  } catch (err) {
    // LLM unavailable — return original text (graceful degradation)
    console.warn('[listening/refine] LLM refinement failed:', err.message);
    return { refined: text, lang: lang || 'en-US' };
  }
}

module.exports = { refine };
