import { readFileSync } from 'fs'
import { basename, join } from 'path'

export function getAppPackage(): { name?: string, scripts?: { toes?: string } } | null {
  try {
    return JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf-8'))
  } catch {
    return null
  }
}

export const getAppName = () => getAppPackage()?.name || basename(process.cwd())

export const isApp = () => !!getAppPackage()?.scripts?.toes

export function resolveAppName(name?: string): string | undefined {
  if (name) return name
  if (isApp()) return getAppName()
  console.error('No app specified and current directory is not a toes app')
  return undefined
}
