/**
 * Check for CLI updates on npm registry
 * Runs silently in background, shows notification if update available
 */

import { execSync } from 'child_process'

const NPM_REGISTRY = 'https://registry.npmjs.org'
const PACKAGE_NAME = 'anvil'
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000 // 24 hours

interface UpdateInfo {
  currentVersion: string
  latestVersion: string
  updateAvailable: boolean
}

/**
 * Get the latest version from npm registry
 */
async function getLatestVersion(): Promise<string | null> {
  try {
    const response = await fetch(`${NPM_REGISTRY}/${PACKAGE_NAME}/latest`)
    if (!response.ok) return null
    const data = await response.json()
    return data.version || null
  } catch {
    return null
  }
}

/**
 * Compare semver versions
 * Returns: 1 if a > b, -1 if a < b, 0 if equal
 */
function compareVersions(a: string, b: string): number {
  const partsA = a.split('.').map(Number)
  const partsB = b.split('.').map(Number)
  
  for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
    const numA = partsA[i] || 0
    const numB = partsB[i] || 0
    if (numA > numB) return 1
    if (numA < numB) return -1
  }
  return 0
}

/**
 * Check for updates and return info
 */
export async function checkForUpdates(currentVersion: string): Promise<UpdateInfo> {
  const latestVersion = await getLatestVersion()
  
  if (!latestVersion) {
    return {
      currentVersion,
      latestVersion: currentVersion,
      updateAvailable: false
    }
  }
  
  const updateAvailable = compareVersions(latestVersion, currentVersion) > 0
  
  return {
    currentVersion,
    latestVersion,
    updateAvailable
  }
}

/**
 * Show update notification in terminal
 */
export function showUpdateNotification(info: UpdateInfo): void {
  if (!info.updateAvailable) return
  
  console.log('')
  console.log('\x1b[33m┌─────────────────────────────────────────────────────┐\x1b[0m')
  console.log('\x1b[33m│\x1b[0m  \x1b[1mUpdate available!\x1b[0m                               \x1b[33m│\x1b[0m')
  console.log('\x1b[33m│\x1b[0m                                                     \x1b[33m│\x1b[0m')
  console.log(`\x1b[33m│\x1b[0m  Current: \x1b[31m${info.currentVersion}\x1b[0m                        \x1b[33m│\x1b[0m`)
  console.log(`\x1b[33m│\x1b[0m  Latest:  \x1b[32m${info.latestVersion}\x1b[0m                        \x1b[33m│\x1b[0m`)
  console.log('\x1b[33m│\x1b[0m                                                     \x1b[33m│\x1b[0m')
  console.log('\x1b[33m│\x1b[0m  Run \x1b[1mnpm i -g anvil@latest\x1b[0m to update              \x1b[33m│\x1b[0m')
  console.log('\x1b[33m└─────────────────────────────────────────────────────┘\x1b[0m')
  console.log('')
}

/**
 * Check for updates in background (non-blocking)
 * Call this at CLI startup
 */
export function checkForUpdatesInBackground(currentVersion: string): void {
  // Skip check for dev versions
  if (!currentVersion || currentVersion === 'dev' || currentVersion.includes('-dev')) {
    return
  }
  
  // Run check in background, don't block CLI startup
  checkForUpdates(currentVersion)
    .then(info => {
      if (info.updateAvailable) {
        showUpdateNotification(info)
      }
    })
    .catch(() => {
      // Silently ignore errors - update check is best effort
    })
}
