////
// Helpers for working with projects in the CLI.

import { join } from "path"
import { readdirSync, type Dirent } from "fs"
import { sessionGet } from "./session"
import { DEFAULT_PROJECT, NOSE_DIR } from "./config"
import { isDir } from "./utils"

export function projectName(): string {
  const state = sessionGet()
  if (!state) throw "no state"

  return state.project || DEFAULT_PROJECT
}

export function projects(): string[] {
  return readdirSync(NOSE_DIR, { withFileTypes: true })
    .filter(file => file.isDirectory())
    .map(dir => dir.name)
    .sort()
}

export function projectDir(name = projectName()): string {
  const root = join(NOSE_DIR, name)
  if (!isDir(root))
    throw `no project found at ${root}`
  return root
}

export function projectBin(name = projectName()): string {
  return join(projectDir(name), "bin")
}

export function projectFiles(name = projectName()): Dirent[] {
  return readdirSync(projectDir(name), { recursive: true, withFileTypes: true })
}