/**
 * `jh update`: installs the newest release with the package manager that holds the kit globally,
 * then syncs `~/.claude` (and the project, when the working directory is inside one with its own install) with
 * the new code. It runs only when the user or a session that asked the user starts it; no hook runs it.
 *
 *   jh update
 */
import { existsSync, realpathSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { hasProjectInstall } from '../config/legacy-names'
import { findProjectRoot } from '../config/location'
import { defaultUpdateCheck, lockedVersion } from '../sync/if-changed'
import { locateKit } from '../sync/kit-source'
import { readInstalledVersion } from '../version/installed-version'
import { REGISTRY_TIMEOUT_MS, registryUrl } from '../version/registry'
import { CLI_NAME } from '../version/release'
import { rewriteConfigShares } from './config-shares'
import { detectPackageManager, legacyPackageRoot, shellHostedGlobalRoot } from './package-manager'
import { VERSION_AVAILABILITY, type VersionAvailability } from './registry-wait'
import { runUpdate, UPDATE_EXIT, type UpdateAdapters } from './update'

const USAGE = `Usage: ${CLI_NAME} update`

/** Runs `argv` without a shell and with the terminal attached, so the manager's own output stays visible. */
const runInherited = async (argv: readonly string[], cwd: string): Promise<number> => {
  try {
    const child = Bun.spawn([...argv], {
      cwd: cwd ?? undefined,
      stdin: 'inherit',
      stdout: 'inherit',
      stderr: 'inherit',
    })
    return await child.exited
  } catch {
    return UPDATE_EXIT.error
  }
}

const NOT_FOUND = 404

/** Asks the registry for one exact version: 404 is `missing`, any other failure `unknown`. */
const registryAvailability = async (version: string): Promise<VersionAvailability> => {
  try {
    const response = await fetch(registryUrl(version), { signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS) })
    if (response.ok) return VERSION_AVAILABILITY.available
    return response.status === NOT_FOUND ? VERSION_AVAILABILITY.missing : VERSION_AVAILABILITY.unknown
  } catch {
    return VERSION_AVAILABILITY.unknown
  }
}

const adaptersFor = async (): Promise<UpdateAdapters> => {
  const { version, packageRoot } = await locateKit()
  const home = homedir()
  const realRoot = realpathSync(packageRoot)
  const targetRoot = shellHostedGlobalRoot(realRoot) ?? realRoot
  return {
    installedVersion: version,
    manager: detectPackageManager(realRoot),
    latestVersion: defaultUpdateCheck().latestVersion,
    versionAvailability: registryAvailability,
    sleep: (ms) => Bun.sleep(ms),
    installedVersionOnDisk: () => readInstalledVersion(targetRoot),
    kitCli: [process.execPath, join(targetRoot, 'src', 'cli.ts')],
    run: runInherited,
    hasGlobalKit: async () => (await lockedVersion(home)) !== null,
    hasLegacyPackage: () => existsSync(legacyPackageRoot(targetRoot)),
    jhOnPath: () => Bun.which(CLI_NAME) !== null,
    home,
    projectRoot: findProjectRoot(process.cwd(), home, existsSync),
    hasProjectKit: (root) => hasProjectInstall(root, existsSync),
    rewriteConfigShares,
    log: (line) => console.log(line),
  }
}

export const run = async (args: string[]): Promise<number> => {
  if (args.length > 0) {
    console.log(USAGE)
    return UPDATE_EXIT.error
  }
  try {
    return await runUpdate(await adaptersFor())
  } catch (error) {
    console.log(`${CLI_NAME} update failed: ${error instanceof Error ? error.message : String(error)}`)
    return UPDATE_EXIT.error
  }
}
