import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { CLAUDE_DIRECTORY, SETTINGS_FILE } from '../claude/paths'
import { configCandidates, globalConfigPath, PROJECT_CONFIG_PATH } from '../config/location'
import { CLI_NAME, PACKAGE_NAME } from '../version/release'
import {
  type CommandContext,
  defaultContext,
  GLOBAL_FLAG,
  globalTargetNote,
  runWithKit,
  usageError,
} from './command-context'
import { collidingNames, DEFAULT_SKILL_PREFIX, type InitResult, runGlobalInit, runInit } from './init'
import type { KitSource } from './kit'
import { nextSteps } from './next-steps'
import { SYNC_EXIT } from './report'
import { GLOBAL_STATUS_LINE_COMMAND, migrateGlobalSettings } from './settings-migration'
import {
  applySettingsOffer,
  readSettingsOffer,
  SESSION_HOOK_COMMAND,
  SESSION_HOOK_OFFER,
  type SettingsOffer,
  type SettingsRead,
  statusLineOffer,
} from './settings-offer'
import type { SetupOutcome } from './setup'
import { chooseSetup } from './setup-questions'

/** The answer to init's questions (prefix, hook, status line), for runs without a terminal. */
const ANSWER_FLAG = { yes: '--yes', no: '--no' } as const

/** Where a project's status line runs from: the copy `sync` writes into its `.claude/`. */
const PROJECT_STATUS_LINE = `${CLAUDE_DIRECTORY}/statusline.sh`

const INIT_USAGE = `Usage: ${CLI_NAME} init [--global] [${ANSWER_FLAG.yes} | ${ANSWER_FLAG.no}]`

/** How the user runs the CLI after each kind of install, for the next steps. */
const GLOBAL_CLI = CLI_NAME
const PROJECT_CLI = `bunx ${PACKAGE_NAME}`

const NO_PREFIX = { skillPrefix: undefined, notes: [] }

/** What a successful init leaves for its next steps: the config's names and the kit's version. */
type FinishedInit = { init: InitResult; version: string }

type InitArgs = { ok: true; global: boolean; answer: boolean | undefined } | { ok: false; message: string }

/** `--yes` → true, `--no` → false, neither → undefined (ask). */
const answerOf = (yes: boolean, no: boolean): boolean | undefined => {
  if (yes) return true
  if (no) return false
  return undefined
}

const parseInitArgs = (args: string[]): InitArgs => {
  const unknown = args.find((arg) => arg !== GLOBAL_FLAG && arg !== ANSWER_FLAG.yes && arg !== ANSWER_FLAG.no)
  if (unknown !== undefined) return { ok: false, message: `Unknown argument: ${unknown}\n${INIT_USAGE}` }
  const [yes, no, global] = [ANSWER_FLAG.yes, ANSWER_FLAG.no, GLOBAL_FLAG].map((flag) => args.includes(flag))
  if (yes && no)
    return { ok: false, message: `${ANSWER_FLAG.yes} and ${ANSWER_FLAG.no} exclude each other\n${INIT_USAGE}` }
  return { ok: true, global, answer: answerOf(yes, no) }
}

const configNote = (configCreated: boolean, path: string): string =>
  configCreated ? `Created ${path}.` : `Found ${path}, kept it as it is.`

/** The lines about the config: created or kept, and for a new one the defaults taken without asking. */
const configNotes = (configCreated: boolean, path: string, setup: SetupOutcome | null): string[] => [
  configNote(configCreated, path),
  ...(configCreated && setup?.note ? [setup.note] : []),
]

const HOOK_QUESTION = `Add a SessionStart hook that runs \`${SESSION_HOOK_COMMAND}\`, so every new session brings the global kit up to date after an update?`

const STATUS_LINE_QUESTION = "Show the kit's status line (model, context fill, session cost)?"

/** One setting `init` offers: what it writes, where, and how it asks. */
type Offer = { offer: SettingsOffer; path: string; shownPath: string; label: string; question: string }

const sessionHookOffer = (home: string): Offer => ({
  offer: SESSION_HOOK_OFFER,
  path: join(home, CLAUDE_DIRECTORY, SETTINGS_FILE),
  shownPath: `~/${CLAUDE_DIRECTORY}/${SETTINGS_FILE}`,
  label: 'the SessionStart hook',
  question: HOOK_QUESTION,
})

const statusLineOfferAt = (root: string, shownRoot: string, command: string): Offer => ({
  offer: statusLineOffer(command),
  path: join(root, CLAUDE_DIRECTORY, SETTINGS_FILE),
  shownPath: `${shownRoot}${CLAUDE_DIRECTORY}/${SETTINGS_FILE}`,
  label: 'the status line',
  question: STATUS_LINE_QUESTION,
})

const notWritten = (offer: Offer, reason: string): string =>
  `Did not add ${offer.label} to ${offer.shownPath} (${reason}). It stays as it was; the README shows the entry to add by hand.`

const notAsked = (offer: Offer): string =>
  `Not asked about ${offer.label} without a terminal: \`${ANSWER_FLAG.yes}\` adds it to ${offer.shownPath}, \`${ANSWER_FLAG.no}\` leaves it out.`

/**
 * A status line of the user's own is replaced only after a yes to the question that names it: `--yes` does not
 * answer it, `--no` does, and without a terminal it is not asked.
 */
const foreignAnswer = async (
  context: CommandContext,
  offer: Offer,
  current: string,
  answer: boolean | undefined,
): Promise<boolean | null> => {
  if (answer === false) return false
  return context.ask(`${offer.shownPath} already runs \`${current}\`. Replace it with ${offer.label} of the kit?`)
}

/** The answer for one offer: from the command line, else from the user, null when nobody can be asked. */
const answerFor = async (context: CommandContext, offer: Offer, read: SettingsRead, answer: boolean | undefined) => {
  if (read.plan.kind === 'foreign') return foreignAnswer(context, offer, read.plan.current, answer)
  return (
    answer ??
    (await context.ask(`${offer.question} It goes into ${offer.shownPath}; everything else there stays as it is.`))
  )
}

/** Asks once per offer unless it is there already or the command line answered; never fails the init. */
const offerSetting = async (context: CommandContext, offer: Offer, answer: boolean | undefined): Promise<void> => {
  const read = await readSettingsOffer(offer.path, offer.offer)
  if (read.plan.kind === 'present') return context.log(`${offer.shownPath} already has ${offer.label}.`)
  if (read.plan.kind === 'unreadable') return context.log(notWritten(offer, read.plan.reason))
  const choice = await answerFor(context, offer, read, answer)
  if (choice === null) return context.log(notAsked(offer))
  if (!choice) {
    const kept = read.plan.kind === 'foreign' ? `, kept \`${read.plan.current}\`` : ''
    return context.log(`Left ${offer.label} out of ${offer.shownPath}${kept}.`)
  }
  const written = await applySettingsOffer(offer.path, read)
  context.log(
    written.kind === 'written' ? `Added ${offer.label} to ${offer.shownPath}.` : notWritten(offer, written.reason),
  )
}

const offerSettings = async (context: CommandContext, offers: Offer[], answer: boolean | undefined) => {
  for (const offer of offers) await offerSetting(context, offer, answer)
}

const prefixQuestion = (names: string[]): string =>
  `This project already has ${names.join(', ')}. Install the kit's skills and agents with the prefix ${DEFAULT_SKILL_PREFIX} (/${DEFAULT_SKILL_PREFIX}implement, …), so yours stay as they are and the kit's skills call each other, not yours?`

const prefixNotAsked = (names: string[]): string =>
  `Not asked about a prefix without a terminal although the project has ${names.join(', ')}: those became conflicts (.kit-new). \`${CLI_NAME} init ${ANSWER_FLAG.yes}\` on a fresh config installs the kit as ${DEFAULT_SKILL_PREFIX}…; or set "skillPrefix" in ${PROJECT_CONFIG_PATH} and run sync.`

/** The prefix for a new config: asked when the project already has skills or agents of kit names. */
const chooseSkillPrefix = async (context: CommandContext, kit: KitSource, answer: boolean | undefined) => {
  const claudeDirectory = join(context.projectRoot, CLAUDE_DIRECTORY)
  const names = collidingNames(kit, (path) => existsSync(join(claudeDirectory, path)))
  if (names.length === 0) return { skillPrefix: undefined, notes: [] }
  const choice = answer ?? (await context.ask(prefixQuestion(names)))
  if (choice === null) return { skillPrefix: undefined, notes: [prefixNotAsked(names)] }
  return { skillPrefix: choice ? DEFAULT_SKILL_PREFIX : undefined, notes: [] }
}

/** Prints what to do next, after everything else init said; tools are detected again, since setup may have installed herdr. */
const printNextSteps = (context: CommandContext, finished: FinishedInit, cli: string): void => {
  const steps = nextSteps({
    skillPrefix: finished.init.skillPrefix,
    adapter: finished.init.terminalAdapter,
    tools: context.detectTools(),
    version: finished.version,
    cli,
  })
  for (const line of steps) context.log(line)
}

/** After the sync: the settings offers, then the next steps; nothing of it when init failed. */
const finishInit = async (
  context: CommandContext,
  exitCode: number,
  finished: FinishedInit | undefined,
  after: { offers: Offer[]; cli: string; answer: boolean | undefined },
): Promise<number> => {
  if (exitCode === SYNC_EXIT.error || !finished) return exitCode
  await offerSettings(context, after.offers, after.answer)
  printNextSteps(context, finished, after.cli)
  return exitCode
}

const initProjectCommand = async (context: CommandContext, answer: boolean | undefined): Promise<number> => {
  const configExists = configCandidates(context.projectRoot).some(existsSync)
  let finished: FinishedInit | undefined
  const exitCode = await runWithKit(context, 'init', async (kit) => {
    const { skillPrefix, notes } = configExists ? NO_PREFIX : await chooseSkillPrefix(context, kit, answer)
    const setup = configExists ? null : await chooseSetup(context, answer)
    const init = await runInit({
      projectRoot: context.projectRoot,
      home: context.home,
      kit,
      skillPrefix,
      setup: setup?.values,
    })
    finished = { init, version: kit.version }
    return {
      notes: [...configNotes(init.configCreated, PROJECT_CONFIG_PATH, setup), ...notes],
      result: init.sync,
    }
  })
  const offers = [statusLineOfferAt(context.projectRoot, '', PROJECT_STATUS_LINE)]
  return finishInit(context, exitCode, finished, { offers, cli: PROJECT_CLI, answer })
}

const initGlobalCommand = async (context: CommandContext, answer: boolean | undefined): Promise<number> => {
  const configExists = configCandidates(context.home).some(existsSync)
  let finished: FinishedInit | undefined
  const exitCode = await runWithKit(context, 'init', async (kit) => {
    const setup = configExists ? null : await chooseSetup(context, answer)
    const init = await runGlobalInit({ home: context.home, kit, setup: setup?.values, configHome: context.configHome })
    finished = { init, version: kit.version }
    const settings = await migrateGlobalSettings(context.home, context.cliOnPath())
    return {
      notes: [
        ...configNotes(init.configCreated, globalConfigPath(context.home), setup),
        globalTargetNote(context.home),
        ...settings,
      ],
      result: init.sync,
    }
  })
  const offers = [sessionHookOffer(context.home), statusLineOfferAt(context.home, '~/', GLOBAL_STATUS_LINE_COMMAND)]
  return finishInit(context, exitCode, finished, { offers, cli: GLOBAL_CLI, answer })
}

export const runInitCommand = async (args: string[], context: CommandContext = defaultContext()): Promise<number> => {
  const parsed = parseInitArgs(args)
  if (!parsed.ok) return usageError(context, parsed.message)
  return parsed.global ? initGlobalCommand(context, parsed.answer) : initProjectCommand(context, parsed.answer)
}

export const run = (args: string[]): Promise<number> => runInitCommand(args)
