export const PRO_BLOCK_NODE_TYPE = 'pro_block'
export const PRO_TRIGGER_TEXT = '[PRO]'
export const PRO_DISPLAY_LABEL = 'PRO 模式'

const PRO_INSTRUCTION_PREFIX = '[PRO]{'
const PRO_INSTRUCTION_SUFFIX = '}'
const PRO_TRIGGER_RE = /^\[pro\]$/i

function normalizeMarkdownText(value = '') {
  return String(value || '').replace(/\r\n?/g, '\n')
}

export function escapeProBlockContent(value = '') {
  return normalizeMarkdownText(value)
    .replace(/\\/g, '\\\\')
    .replace(/\n/g, '\\n')
    .replace(/]/g, '\\]')
    .replace(/}/g, '\\}')
}

export function unescapeProBlockContent(value = '') {
  const normalized = String(value || '')
  let result = ''

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

    const next = normalized[index + 1]
    if (next === 'n') {
      result += '\n'
    } else {
      result += next
    }
    index += 1
  }

  return result
}

export function serializeProBlockSyntax(instruction = '') {
  const normalized = normalizeMarkdownText(instruction).trim()
  if (!normalized) return PRO_TRIGGER_TEXT
  return `${PRO_INSTRUCTION_PREFIX}${escapeProBlockContent(normalized)}${PRO_INSTRUCTION_SUFFIX}`
}

export function parseProBlockSyntax(value = '') {
  const text = normalizeMarkdownText(value).trim()
  if (!text) return null

  if (PRO_TRIGGER_RE.test(text)) {
    return {
      instruction: '',
      autoStart: false,
    }
  }

  const prefix = text.slice(0, PRO_INSTRUCTION_PREFIX.length)
  if (prefix.toLowerCase() === PRO_INSTRUCTION_PREFIX.toLowerCase() && text.endsWith(PRO_INSTRUCTION_SUFFIX)) {
    return {
      instruction: unescapeProBlockContent(
        text.slice(PRO_INSTRUCTION_PREFIX.length, text.length - PRO_INSTRUCTION_SUFFIX.length)
      ).trim(),
      autoStart: false,
    }
  }

  return null
}
