import chalk from 'chalk'
import { getGlobalConfig, saveGlobalConfig } from '../../utils/config.js'
import {
  getCompanion,
  petCompanion,
  getEquipmentDisplay,
  levelProgress,
} from '../../forge/companion.js'
import { RARITY_STARS } from '../../forge/types.js'
import type { LocalCommandCall } from '../../types/command.js'

const PERSONALITIES = [
  'gruff but loyal',
  'quietly observant',
  'fiery and passionate',
  'stoic and patient',
  'mischievous and clever',
  'wise and measured',
  'eager and energetic',
  'cunning and sharp',
]

const NAME_PARTS_A = [
  'Ash',
  'Cinder',
  'Coal',
  'Ember',
  'Flint',
  'Forge',
  'Iron',
  'Molten',
  'Scoria',
  'Slag',
  'Soot',
  'Spark',
  'Steel',
  'Temper',
]
const NAME_PARTS_B = [
  'belcher',
  'breaker',
  'cracker',
  'fist',
  'foot',
  'hammer',
  'heart',
  'knuckles',
  'maw',
  'shanks',
  'spark',
  'tooth',
  'tongs',
]

function generateName(): string {
  const a = NAME_PARTS_A[Math.floor(Math.random() * NAME_PARTS_A.length)]!
  const b = NAME_PARTS_B[Math.floor(Math.random() * NAME_PARTS_B.length)]!
  return Math.random() > 0.5 ? `${a}${b}` : `${a} ${b}`
}

function generatePersonality(): string {
  return PERSONALITIES[Math.floor(Math.random() * PERSONALITIES.length)]!
}

function hatchCompanion(): void {
  const name = generateName()
  const personality = generatePersonality()
  saveGlobalConfig((current) => ({
    ...current,
    companion: {
      name,
      personality,
      hatchedAt: Date.now(),
    },
  }))
}

export const call: LocalCommandCall = async (args, _context) => {
  const config = getGlobalConfig()
  const arg = (args ?? '').trim().toLowerCase()

  // /forge off — mute companion and stop all API calls
  if (arg === 'off' || arg === 'disable' || arg === 'mute') {
    saveGlobalConfig((current) => ({ ...current, companionMuted: true }))
    const companion = getCompanion()
    return {
      type: 'text',
      value: companion
        ? `${companion.name} retreats into the shadows. Use /forge to bring them back.`
        : 'The forge goes dark.',
    }
  }

  // Un-mute
  if (config.companionMuted) {
    saveGlobalConfig((current) => ({ ...current, companionMuted: false }))
    const companion = getCompanion()
    return {
      type: 'text',
      value: companion
        ? `${companion.name} stirs back to life at the forge.`
        : 'The forge roars back to life.',
    }
  }

  // Hatch if no companion exists
  const isNew = !config.companion
  if (isNew) {
    hatchCompanion()
  }

  const companion = getCompanion()
  if (!companion) {
    return { type: 'text', value: 'Something went wrong at the forge. Try again.' }
  }

  // Check pet cooldown
  const lastPetAt = config.companion?.lastPetAt ?? 0
  const onCooldown = lastPetAt > 0 && Date.now() - lastPetAt < 10_000
  if (onCooldown) {
    return { type: 'text', value: `${companion.name} is still cooling down. Wait a moment!` }
  }

  // Pet (awards XP, updates lastPetAt)
  petCompanion()

  // Show stats
  if (isNew) {
    return {
      type: 'text',
      value: `A ${companion.rarity} ${companion.species} emerges from the forge! Say hello to ${companion.name}.`,
    }
  }

  const stars = RARITY_STARS[companion.rarity]
  const progress = levelProgress(companion)
  const equipment = getEquipmentDisplay(companion.equipment)

  let output = ''
  output += chalk.bold(`  ${companion.name} ${stars}`) + '\n'
  output +=
    chalk.dim(`  ${companion.species} · ${companion.rarity} · ${companion.personality}`) + '\n'
  output += chalk.dim(`  Level ${companion.level} · ${progress}% to next`) + '\n'

  if (companion.shiny) {
    output += chalk.yellow('  ✦ SHINY ✦') + '\n'
  }

  if (equipment.length > 0) {
    output += chalk.dim(`  Equipment: ${equipment.join(', ')}`) + '\n'
  }

  output += '\n'
  output += chalk.dim(
    `  MIGHT ${companion.stats.MIGHT}  ENDURANCE ${companion.stats.ENDURANCE}  SPARK ${companion.stats.SPARK}  TEMPER ${companion.stats.TEMPER}  GRIT ${companion.stats.GRIT}`,
  )

  return { type: 'text', value: output }
}
