/**
 * Resolve the dev server URL for the current worktree.
 *
 * Simple lookup: prefer the env var (set by terminal/agent sessions),
 * then check the live server registry, finally fall back to the
 * worktree's allocated port.
 */

import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { detectWorktreeName, resolveRunningPort } from '../worktree/port.js'
import { findByWorktree } from '../worktree/serverRegistry.js'

export function getServerUrl() {
  if (process.env.STORYBOARD_SERVER_URL) {
    return process.env.STORYBOARD_SERVER_URL.replace(/\/$/, '')
  }

  const name = detectWorktreeName()

  try {
    const servers = findByWorktree(name)
    if (servers.length > 0) return `http://localhost:${servers[0].port}`
  } catch { /* fall through */ }

  const port = resolveRunningPort(name)
  return `http://localhost:${port}`
}

/**
 * Resolve the Vite base path used to serve the app. Priority:
 *   1. `VITE_BASE_PATH` env var (matches vite.config.js convention)
 *   2. `basePath` key in storyboard.config.json
 *   3. `/` (Vite default)
 *
 * Always returns a path starting and ending with `/`.
 */
export function resolveBasePath(cwd = process.cwd()) {
  let base = process.env.VITE_BASE_PATH || null
  if (!base) {
    try {
      const cfg = JSON.parse(readFileSync(resolve(cwd, 'storyboard.config.json'), 'utf8'))
      if (typeof cfg.basePath === 'string' && cfg.basePath) base = cfg.basePath
    } catch { /* empty */ }
  }
  base = base || '/'
  if (!base.startsWith('/')) base = '/' + base
  if (!base.endsWith('/')) base = base + '/'
  return base
}
