import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

declare const __CLI_VERSION__: string | undefined

export type ResolvedCliVersion = Readonly<{
  version: string
  source: 'injected' | 'package'
}> | null

export function resolveCliVersion(): ResolvedCliVersion {
  const injected
    = typeof __CLI_VERSION__ === 'string' ? __CLI_VERSION__.trim() : ''
  if (injected)
    return { version: injected, source: 'injected' }

  const pkgVersion = readNearestPackageVersion()
  if (pkgVersion)
    return { version: pkgVersion, source: 'package' }

  return null
}

function readNearestPackageVersion(): string | null {
  try {
    let dir = path.dirname(fileURLToPath(import.meta.url))
    for (let i = 0; i < 6; i++) {
      const candidate = path.join(dir, 'package.json')
      if (existsSync(candidate)) {
        const raw = readFileSync(candidate, 'utf8')
        const pkg = JSON.parse(raw)
        const version
          = typeof pkg?.version === 'string' ? pkg.version.trim() : ''
        if (version)
          return version
      }
      const parent = path.dirname(dir)
      if (parent === dir)
        break
      dir = parent
    }
  }
  catch {
    // ignore
  }
  return null
}
