import { defineStore } from 'pinia'
import { ref } from 'vue'
import wikiApi from '../api/wiki.api'
import { useLoadable } from '../composables/useLoadable'
import type { WikiPageWithContent } from '../lib/interfaces/wiki.interface'

export interface EngineHighlight {
  title: string
  text: string
}

// Landing-page digest of a wiki engine page. Convention: every engine-tagged
// page opens with an intro paragraph, then a "What You Get" heading as its
// first heading, with the feature bullets underneath.
export interface EngineDigest {
  intro: string
  highlightsTitle: string
  highlights: EngineHighlight[]
}

const HIGHLIGHTS_HEADING = 'what you get'
const MAX_HIGHLIGHTS = 6

// Inline markdown (links, bold, code) stripped so the text reads as plain prose.
function stripInline(md: string): string {
  return md
    .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
    .replace(/\*\*([^*]+)\*\*/g, '$1')
    .replace(/[*_`]/g, '')
    .replace(/\s+/g, ' ')
    .trim()
}

export function getEngineDigest(content: string): EngineDigest {
  const digest: EngineDigest = { intro: '', highlightsTitle: '', highlights: [] }
  let inHighlights = false

  for (const raw of (content || '').split('\n')) {
    const line = raw.trim()
    if (!line || /^([-*_])\1{2,}$/.test(line)) continue

    const heading = line.match(/^#{1,6}\s+(.*)$/)
    if (heading) {
      // The section ends at the next heading; and if the page's first heading
      // is not "What You Get", it doesn't follow the convention — no highlights.
      if (inHighlights) break
      const title = stripInline(heading[1])
      if (title.toLowerCase() !== HIGHLIGHTS_HEADING) break
      inHighlights = true
      digest.highlightsTitle = title
      continue
    }

    if (inHighlights) {
      const bullet = line.match(/^[-*]\s+(.*)$/)
      if (!bullet) continue
      const lead = bullet[1].match(/^\*\*([^*]+)\*\*\s*[:—–-]?\s*(.*)$/)
      digest.highlights.push(
        lead
          ? { title: stripInline(lead[1]), text: stripInline(lead[2]) }
          : { title: '', text: stripInline(bullet[1]) },
      )
      continue
    }

    // First prose line (paragraph or blockquote) before the heading is the intro.
    if (!digest.intro) {
      digest.intro = stripInline(line.replace(/^>\s*/, ''))
    }
  }

  digest.highlights = digest.highlights.slice(0, MAX_HIGHLIGHTS)
  return digest
}

export const useEnginesStore = defineStore('engines', () => {
  const pages = ref<WikiPageWithContent[]>([])
  const { loading, error, withCache, invalidate } = useLoadable()

  async function fetch() {
    await withCache(async () => {
      pages.value = await wikiApi.listEnginePages()
    })
  }

  function getCleanPreview(content: string): string {
    if (!content) return ''
    return content.replace(/[#*`_[\]()>|-]/g, '').replace(/\s+/g, ' ').trim().slice(0, 260) + '...'
  }

  return { pages, loading, error, fetch, getCleanPreview, getEngineDigest, invalidate }
})
