/**
 * Content Plan Parser
 * Parses raw text from content plan PDFs into structured letter data.
 * Supports three project formats: AT (numizm.at), RU (numizmat.ru), KB (coinsbolhov)
 */

// Markers that end text/skip accumulation
const MARKER_RE = /^(Письмо\s+\d|Тема:|Прехедер:|Баннер|ТЗ для дизайнера|Картинка|Монета:|Текст:|Текст между|Товар|Блоки с товарами|Кнопка|Гиперссылка:|Ссылка:|Заголовок:)/i

// Product IDs line: numbers separated by commas/spaces (at least one 3+ digit number)
const PRODUCT_IDS_RE = /^[\d,\s]+$/
const HAS_PRODUCT_ID = /\d{3,}/

// URL line
const URL_RE = /^https?:\/\//i

/**
 * Detect project format from project name
 */
export function detectFormat(projectName) {
  const n = (projectName || '').toLowerCase()
  if (n.includes('numizm.at') || n === 'at' || n.includes('нумизм.ат')) return 'at'
  if (n.includes('numizmatru') || n.includes('нумизмат.ру') || n.includes('numizmat.ru')) return 'ru'
  if (n.includes('kb') || n.includes('кб') || n.includes('coinsbolhov') || n.includes('coinsbolshov')) return 'kb'
  return 'at' // default
}

/**
 * Parse product IDs from a line, handling all formats
 */
function parseProductIds(line) {
  return line
    .replace(/,/g, ' ')
    .split(/\s+/)
    .map(s => s.trim())
    .filter(s => /^\d{3,}$/.test(s))
}

/**
 * Main parser
 * @param {string} text - Raw text from content plan
 * @returns {Array<{subject: string, preheader: string, blocks: Array}>}
 */
export function parseContentPlan(text) {
  const lines = text.split('\n').map(l => l.trim())
  const letters = []
  let current = null
  let skipMode = false  // inside "ТЗ для дизайнера" section
  let textAccum = null  // accumulating text block
  let productAccum = null // accumulating product IDs (for single-per-line format)

  function flushText() {
    if (textAccum && textAccum.content.trim()) {
      current.blocks.push({ type: 'text', content: textAccum.content.trim() })
    }
    textAccum = null
  }

  function flushProducts() {
    if (productAccum && productAccum.ids.length > 0) {
      // Split into blocks of 1-3 IDs each
      const ids = [...productAccum.ids]
      while (ids.length > 0) {
        const chunk = ids.splice(0, Math.min(3, ids.length))
        // If remainder is 1 and we took 3, balance: [2,2] instead of [3,1]
        if (ids.length === 1 && chunk.length === 3) {
          ids.unshift(chunk.pop())
        }
        current.blocks.push({ type: 'products', ids: chunk })
      }
    }
    productAccum = null
  }

  function flushAll() {
    flushText()
    flushProducts()
  }

  function startLetter() {
    if (current) {
      flushAll()
      letters.push(current)
    }
    current = { subject: '', preheader: '', blocks: [] }
    skipMode = false
    textAccum = null
    productAccum = null
  }

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]
    const trimmed = line

    // Empty line
    if (!trimmed) {
      // End text accumulation on double empty line
      continue
    }

    // Letter separator
    if (/^Письмо\s+\d+/i.test(trimmed)) {
      startLetter()
      continue
    }

    if (!current) continue

    // Subject
    const subjectMatch = trimmed.match(/^Тема:\s*(.*)/i)
    if (subjectMatch) {
      skipMode = false
      flushAll()
      current.subject = subjectMatch[1].trim()
      continue
    }

    // Preheader
    const preheaderMatch = trimmed.match(/^Прехедер:\s*(.*)/i)
    if (preheaderMatch) {
      skipMode = false
      flushAll()
      // Preheader can span multiple lines
      let ph = preheaderMatch[1].trim()
      // Look ahead for continuation (non-marker lines)
      while (i + 1 < lines.length && lines[i + 1].trim() && !MARKER_RE.test(lines[i + 1].trim()) && !URL_RE.test(lines[i + 1].trim()) && !PRODUCT_IDS_RE.test(lines[i + 1].trim())) {
        i++
        ph += ' ' + lines[i].trim()
      }
      current.preheader = ph
      continue
    }

    // Banner
    if (/^Баннер/i.test(trimmed)) {
      skipMode = false
      flushAll()
      current.blocks.push({ type: 'banner' })
      continue
    }

    // Skip designer instructions
    if (/^ТЗ для дизайнера/i.test(trimmed)) {
      skipMode = true
      flushAll()
      continue
    }

    // Skip image/coin references and URLs
    if (/^Картинка|^Монета:/i.test(trimmed)) {
      skipMode = true
      continue
    }
    if (URL_RE.test(trimmed)) {
      // Check if this is a "Ссылка:" URL for hyperlink
      if (i > 0 && /^Ссылка:/i.test(lines[i - 1]?.trim() || '')) {
        // Already handled by Гиперссылка
      }
      continue
    }
    if (/^Ссылка:/i.test(trimmed)) {
      continue // URL on next line, skip
    }

    // Exit skip mode on any marker
    if (skipMode) {
      if (MARKER_RE.test(trimmed)) {
        skipMode = false
        // Fall through to process this line as a marker
      } else {
        continue // Still skipping
      }
    }

    // Heading (numizmatRU, KB)
    const headingMatch = trimmed.match(/^Заголовок:\s*(.*)/i)
    if (headingMatch) {
      flushAll()
      let heading = headingMatch[1].trim()
      // If empty, next non-empty line is the heading text
      if (!heading) {
        while (i + 1 < lines.length) {
          i++
          const next = lines[i].trim()
          if (next && !MARKER_RE.test(next)) {
            heading = next
            break
          }
          if (MARKER_RE.test(next)) { i--; break }
        }
      }
      if (heading) current.blocks.push({ type: 'heading', content: heading })
      continue
    }

    // Text block
    const textMatch = trimmed.match(/^Текст(?:\s+между\s+\S+)?:\s*(.*)/i)
    if (textMatch) {
      flushAll()
      const firstLine = textMatch[1].trim()
      textAccum = { content: firstLine }
      continue
    }

    // Product markers
    if (/^(?:Товар[ыа]?|Блоки с товарами)[\s:(]/i.test(trimmed) || /^(?:Товар[ыа]?|Блоки с товарами)\s*$/i.test(trimmed)) {
      flushText()
      if (!productAccum) productAccum = { ids: [] }
      // Check if IDs are on the same line after ":"
      const afterColon = trimmed.replace(/^[^:]*:?\s*/, '')
      if (afterColon && PRODUCT_IDS_RE.test(afterColon) && HAS_PRODUCT_ID.test(afterColon)) {
        productAccum.ids.push(...parseProductIds(afterColon))
      }
      continue
    }

    // Button
    const buttonMatch = trimmed.match(/^Кнопка:?\s*[«"]?(.+?)[»"]?\s*$/i)
    if (buttonMatch) {
      flushAll()
      current.blocks.push({ type: 'button', text: buttonMatch[1].trim() })
      continue
    }

    // Hyperlink (KB format)
    const hyperlinkMatch = trimmed.match(/^Гиперссылка:\s*(.*)/i)
    if (hyperlinkMatch) {
      flushAll()
      current.blocks.push({ type: 'button', text: hyperlinkMatch[1].trim() })
      continue
    }

    // Product IDs line (no marker, just numbers)
    if (PRODUCT_IDS_RE.test(trimmed) && HAS_PRODUCT_ID.test(trimmed)) {
      flushText()
      if (!productAccum) productAccum = { ids: [] }
      productAccum.ids.push(...parseProductIds(trimmed))
      continue
    }

    // Plain text line — accumulate into text block or start new one
    if (textAccum) {
      textAccum.content += (textAccum.content ? ' ' : '') + trimmed
    } else if (productAccum) {
      // Text after products — flush products, start text
      flushProducts()
      textAccum = { content: trimmed }
    } else {
      // Standalone text line (no marker) — start text block
      textAccum = { content: trimmed }
    }
  }

  // Flush final letter
  if (current) {
    flushAll()
    letters.push(current)
  }

  return letters
}
