export const INPUT_BLOCK_NODE_TYPE = 'input_block'

const MAX_RECORDING_DURATION_MS = 10 * 60 * 1000 // 10 minutes

/**
 * Normalize line endings and trim.
 */
function normalizeMarkdownText(value = '') {
  return String(value || '').replace(/\r\n?/g, '\n')
}

/**
 * Escape special characters for safe storage in node attrs.
 */
export function escapeInputBlockContent(value = '') {
  return normalizeMarkdownText(value)
    .replace(/\\/g, '\\\\')
    .replace(/\n/g, '\\n')
}

/**
 * Unescape stored content back to readable text.
 */
export function unescapeInputBlockContent(value = '') {
  const normalized = String(value || '').replace(/\r\n?/g, '\n')
  let result = ''

  for (let index = 0; index < normalized.length; index += 1) {
    const char = normalized[index]
    if (char !== '\\' || index === normalized.length - 1) {
      result += char
    } else {
      const next = normalized[index + 1]
      if (next === 'n') {
        result += '\n'
      } else {
        result += next
      }
    }
  }

  return result
}

/**
 * Serialize to the [INPUT]{instr}***text*** or [INPUT] format.
 */
export function serializeInputBlockSyntax(instruction = '', text = '') {
  const normalizedInstr = normalizeMarkdownText(instruction).trim()
  if (!normalizedInstr) return '[INPUT]'

  const instrPart = `[INPUT]{${escapeInputBlockContent(normalizedInstr)}}`
  if (!text) return instrPart

  const normalizedText = escapeInputBlockContent(text.trim())
  if (!normalizedText) return instrPart

  // Format: [INPUT]{instructions}***用户输入的文本***
  return `${instrPart}***${normalizedText}***`
}

/**
 * Parse markdown syntax back to structured data.
 */
export function parseInputBlockSyntax(value = '') {
  const text = normalizeMarkdownText(value).trim()
  if (!text) return null

  // Match full pattern: [INPUT]{instr}***userText*** or [INPUT]***text***
  const fullMatch = text.match(/^(\[INPUT\](?:\s*\{([^\}]*)\})?)?\*\*([\s\S]*?)\*\*\*$/i)
  if (fullMatch) {
    return {
      instruction: fullMatch[2] || '',
      userInputText: fullMatch[3].trim()
    }
  }

  // Match just the trigger: [INPUT] or [INPUT]{instr}
  const triggerMatch = text.match(/^\[INPUT\](?:\s*\{([^\}]*)\})?$/i)
  if (triggerMatch) {
    return {
      instruction: triggerMatch[1] || '',
      userInputText: ''
    }
  }

  return null
}

/**
 * Get the display label for an instruction. Returns empty string if no instruction.
 */
export function getInputInstructionDisplay(instruction = '') {
  return normalizeMarkdownText(instruction).trim() || ''
}

/**
 * Check if the recording duration has exceeded the maximum.
 */
export function isRecordingExpired(startTimestamp = 0) {
  if (!startTimestamp) return false
  const elapsed = Date.now() - startTimestamp
  return elapsed > MAX_RECORDING_DURATION_MS
}
