/**
 * List workleafs across the repo, grouped by parent, with live server info.
 *
 * Output shape:
 *
 *   storyboard workleaf list
 *
 *   main
 *     ● workleaf--quick-fix    :1235   http://localhost:1235/storyboard/   (pid 12345)
 *     ○ workleaf--archive       (no server)
 *
 *   4.3.0
 *     ● workleaf--bench         :1236   http://localhost:1236/storyboard/   (pid 23456)
 *
 * `●` = live server, `○` = no live server.
 */

import * as p from '@clack/prompts'
import { listWorkleafs } from './paths.js'
import { findByWorktree } from '../worktree/serverRegistry.js'
import { dim, bold, green } from '../cli/intro.js'

export function runList() {
  const all = listWorkleafs()

  if (all.length === 0) {
    p.log.info('No workleafs yet.')
    p.log.info(dim('Create one with: npx storyboard workleaf create <name>'))
    return
  }

  // Group by parent, preserving insertion order from listWorkleafs (already
  // grouped by readdir order which is parent-first).
  const byParent = new Map()
  for (const w of all) {
    if (!byParent.has(w.parent)) byParent.set(w.parent, [])
    byParent.get(w.parent).push(w)
  }

  console.log()
  for (const [parent, leaves] of byParent) {
    console.log(`  ${bold(parent)}`)
    for (const w of leaves) {
      const servers = findByWorktree(w.branch)
      if (servers.length > 0) {
        const s = servers[0]
        const url = `http://localhost:${s.port}/storyboard/`
        console.log(`    ${green('●')} workleaf--${w.slug.padEnd(28)} :${String(s.port).padEnd(5)}  ${green(url)}  ${dim(`(pid ${s.pid})`)}`)
      } else {
        console.log(`    ${dim('○')} workleaf--${w.slug.padEnd(28)} ${dim('(no server)')}`)
      }
    }
    console.log()
  }

  p.log.info(dim('Tip: storyboard workleaf merge <name>  squashes & cleans up'))
}
