/**
 * Queries the SQLite index for pages (with backlink counts) and tags
 * (with frequency counts) to populate the sidebar.
 *
 * @remarks Edge cases & deferred work:
 * - **Backlink counts may be stale after a page rename.** The count uses
 *   `links.target` which stores the page title at the time the `[[link]]`
 *   was created. Renaming a page doesn't update existing link targets.
 *   A "migrate to suggested structure" command (plan D1) would fix this.
 * - **Pages with empty titles fall back to filename stem.** The `name` field
 *   is the raw title for navigation queries; `displayName` replaces underscores
 *   with spaces for cosmetic display in the sidebar.
 * - **No filtering or search.** The sidebar shows all pages and tags with
 *   no text filter. Search is planned (D6) but not yet wired to this query.
 */
import { ref, watch } from "vue"
import { createGraphService } from "~/services/graph"
import { useWorkspaceStore } from "~/stores/workspace"

export interface SidebarPage {
  /** Raw title from the index (used for navigation queries). */
  name: string
  /** Human-readable label (cosmetic transformations applied). */
  displayName: string
  backlinkCount: number
}

export interface SidebarTag {
  name: string
  count: number
}

export function useSidebarIndex() {
  const ws = useWorkspaceStore()
  const pages = ref<SidebarPage[]>([])
  const tags = ref<SidebarTag[]>([])

  async function refresh() {
    const db = ws.db
    if (!db) {
      pages.value = []
      tags.value = []
      return
    }
    try {
      // Pages: use GraphService for entity listing
      const graph = createGraphService(db)
      const pageEntities = await graph.getEntities("page")
      const pageEntries = pageEntities.map((e) => {
        const name =
          e.title ?? e.id.split("/").pop()?.replace(/\.md$/, "") ?? e.id
        const displayName = name.replace(/_/g, " ")
        return { name, displayName }
      })

      // Backlink counts: how many links reference each page
      const backlinkRows = await db.select<{ target: string; count: number }[]>(
        "SELECT target, COUNT(*) as count FROM links WHERE link_type = 'page-ref' GROUP BY target",
      )
      const backlinkMap = new Map(backlinkRows.map((r) => [r.target, r.count]))

      pages.value = pageEntries.map(({ name, displayName }) => ({
        name,
        displayName,
        backlinkCount: backlinkMap.get(name) ?? 0,
      }))

      // Tags: count references per tag
      const tagRows = await db.select<{ target: string; count: number }[]>(
        "SELECT target, COUNT(*) as count FROM links WHERE link_type = 'tag' GROUP BY target ORDER BY count DESC",
      )
      tags.value = tagRows.map((r) => ({ name: r.target, count: r.count }))
    } catch (e) {
      console.warn("[useSidebarIndex] failed to query index:", e)
      pages.value = []
      tags.value = []
    }
  }

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

  return { pages, tags, refresh }
}
