
import std/[os, strformat, strutils]
import ../config
import core

proc checkPathConfigured*(): bool =
  ## Check if NIP binary path is in PATH
  let config = loadConfig()
  let binPath = config.linksDir / "Executables"
  let pathEnv = getEnv("PATH")
  
  # Normalize paths for comparison (remove trailing slashes, resolve symlinks if possible)
  # Simple string check for now
  return binPath in pathEnv

proc detectShell*(): string =
  ## Detect the user's shell
  let shellPath = getEnv("SHELL")
  if shellPath.len > 0:
    return shellPath.extractFilename()
  return "bash"

proc appendToRcFile(rcFile: string, content: string): bool =
  ## Append content to an RC file if it's not already there
  let home = getHomeDir()
  let path = home / rcFile
  
  try:
    var currentContent = ""
    if fileExists(path):
      currentContent = readFile(path)
    
    if content.strip() in currentContent:
      return true # Already there
      
    let newContent = if currentContent.len > 0 and not currentContent.endsWith("\n"):
                       "\n" & content & "\n"
                     else:
                       content & "\n"
                       
    writeFile(path, currentContent & newContent)
    return true
  except Exception as e:
    echo fmt"❌ Failed to update {rcFile}: {e.msg}"
    return false

proc setupUserCommand*(): CommandResult =
  ## Setup NIP for the current user
  let config = loadConfig()
  let binPath = config.linksDir / "Executables"
  let shell = detectShell()
  
  echo fmt"🌱 Setting up NIP for user (Shell: {shell})..."
  echo fmt"   Binary Path: {binPath}"
  
  var success = false
  
  case shell:
  of "zsh":
    let rcContent = fmt"""
# NIP Package Manager
export PATH="{binPath}:$PATH"
"""
    if appendToRcFile(".zshrc", rcContent):
      echo "✅ Updated .zshrc"
      success = true
      
  of "bash":
    let rcContent = fmt"""
# NIP Package Manager
export PATH="{binPath}:$PATH"
"""
    if appendToRcFile(".bashrc", rcContent):
      echo "✅ Updated .bashrc"
      success = true
      
  of "fish":
    let rcContent = fmt"""
# NIP Package Manager
contains "{binPath}" $fish_user_paths; or set -Ua fish_user_paths "{binPath}"
"""
    # Fish is typically in .config/fish/config.fish
    # Ensure dir exists
    let fishDir = getHomeDir() / ".config" / "fish"
    if not dirExists(fishDir):
      createDir(fishDir)
      
    if appendToRcFile(".config/fish/config.fish", rcContent):
      echo "✅ Updated config.fish"
      success = true
      
  else:
    return errorResult(fmt"Unsupported shell: {shell}. Please manually add {binPath} to your PATH.")
    
  if success:
    echo ""
    echo "✨ Setup complete! Please restart your shell or run:"
    echo fmt"   source ~/.{shell}rc"
    return successResult("NIP setup successfully")
  else:
    return errorResult("Failed to setup NIP")

proc setupSystemCommand*(): CommandResult =
  ## Setup NIP system-wide
  # TODO: Implement system-wide setup (e.g. /etc/profile.d/nip.sh)
  return errorResult("System-wide setup not yet implemented")

proc setupCommand*(args: seq[string]): CommandResult =
  ## Dispatch setup commands
  if args.len == 0:
    return errorResult("Usage: nip setup <user|system>")
    
  case args[0]:
  of "user":
    return setupUserCommand()
  of "system":
    return setupSystemCommand()
  else:
    return errorResult("Unknown setup target. Use 'user' or 'system'.")
