/**
 * Queries the SQLite index for daily block counts to drive
 * the TimelineRail density dots.
 */
import { ref, watch } from "vue"
import { useWorkspaceStore } from "~/stores/workspace"

export function useTimelineDensity() {
  const ws = useWorkspaceStore()
  const densityMap = ref<Map<string, number>>(new Map())

  async function refresh() {
    const db = ws.db
    if (!db) {
      densityMap.value = new Map()
      return
    }
    try {
      const rows = await db.select<{ page_path: string; count: number }[]>(
        "SELECT page_path, COUNT(*) as count FROM blocks GROUP BY page_path",
      )
      const map = new Map<string, number>()
      for (const row of rows) {
        // Extract date from journal path: .../journals/YYYY-MM-DD.md
        const match = row.page_path.match(/journals\/(\d{4}-\d{2}-\d{2})\.md$/)
        if (match) {
          map.set(match[1], row.count)
        }
      }
      densityMap.value = map
    } catch (e) {
      console.warn("[useTimelineDensity] failed to query index:", e)
      densityMap.value = new Map()
    }
  }

  watch(
    () => ws.db,
    () => {
      refresh()
    },
    { immediate: true },
  )

  return { densityMap, refresh }
}
