## graft_commands_enhanced.nim
## Enhanced graft command with USE flag support

import std/[strformat, strutils, tables, times, json, os, sequtils]
import ../graft_coordinator, ../install_manager, ../simple_db, ../system_integration
import ../config, ../logger, ../platform, ../use_flags

proc graftCommandWithUseFlags*(
  packageSpec: string,
  useFlagsStr: string = "",
  cflagsStr: string = "",
  profileName: string = "",
  verbose: bool = false,
  coordinator: GraftCoordinator
): int =
  ## Enhanced graft command with USE flag support
  ## Usage: nip graft [source:]package [--use="flags"] [--cflags="flags"] [--profile=name]
  ## Examples:
  ##   nip graft firefox --use="+wayland -X +lto"
  ##   nip graft vim --use="+python +lua" --cflags="-O3"
  ##   nip graft nginx --profile=performance

  if verbose:
    coordinator.verbose = true

  echo fmt"🌱 NIP Graft - Universal Package Grafting with USE Flags"
  echo ""

  # Parse package spec
  let (source, packageName) = parsePackageSpec(packageSpec)

  # Load configuration
  let cfg = loadConfig()

  # Parse CLI USE flags if provided
  var cliUseFlags: seq[UseFlag] = @[]
  if useFlagsStr.len > 0:
    try:
      cliUseFlags = parseUseFlagLine(useFlagsStr)
      echo "🔧 CLI USE flags: " & formatUseFlags(cliUseFlags)
      echo ""
    except UseFlagParseError as e:
      echo fmt"❌ Error parsing USE flags: {e.msg}"
      return 1

  # Get effective USE flags (profile -> global -> package -> CLI)
  var effectiveUseFlags = getEffectiveUseFlags(cfg, packageName)
  if cliUseFlags.len > 0:
    effectiveUseFlags = mergeUseFlags(effectiveUseFlags, cliUseFlags)

  # Validate USE flags
  let categories = getStandardCategories()
  let (valid, errors) = validateUseFlags(effectiveUseFlags, categories)
  if not valid:
    echo "❌ USE flag validation errors:"
    for err in errors:
      echo fmt"   {err}"
    return 1

  # Get effective compiler flags
  var effectiveCompilerFlags = getEffectiveCompilerFlags(cfg, packageName)
  if cflagsStr.len > 0:
    effectiveCompilerFlags.cflags = cflagsStr

  # Display effective settings
  if effectiveUseFlags.len > 0:
    displayUseFlags(effectiveUseFlags, "Effective USE Flags")

  if effectiveCompilerFlags.cflags.len > 0 or effectiveCompilerFlags.cxxflags.len > 0:
    displayCompilerFlags(effectiveCompilerFlags, "Compiler Flags")

  # Generate variant hash
  let variantHash = useFlagsToHash(effectiveUseFlags)

  echo fmt"📦 Package: {packageName}"
  if source != Auto:
    echo fmt"📍 Source: {source}"
  else:
    echo fmt"🔍 Source: Auto-detect"

  if variantHash != "default":
    echo fmt"🏷️  Variant: {variantHash}"
  echo ""

  logOperation("graft", fmt"package={packageName} source={source} variant={variantHash}")

  # Check if already installed
  # TODO: Check for specific variant once variant management is implemented
  if coordinator.isInstalled(packageName):
    echo fmt"⚠️  Package '{packageName}' is already installed"
    if variantHash != "default":
      echo fmt"   Note: Installing different variants will be supported soon"
    echo fmt"   Use 'nip remove {packageName}' first to reinstall"
    logWarning(fmt"Attempted to install already installed package: {packageName}")
    return 1

  # Perform graft
  # TODO: Pass USE flags and compiler flags to coordinator
  # For now, we just log them and use the standard graft
  if effectiveUseFlags.len > 0:
    logInfo(fmt"USE flags for {packageName}: {formatUseFlags(effectiveUseFlags)}")
  if effectiveCompilerFlags.cflags.len > 0:
    logInfo(fmt"Compiler flags for {packageName}: CFLAGS={effectiveCompilerFlags.cflags}")

  let result = coordinator.graft(packageName, source)

  if result.success:
    echo ""
    echo "✅ Graft successful!"
    echo fmt"📍 Installed to: {result.installPath}"
    if variantHash != "default":
      echo fmt"🏷️  Variant: {variantHash}"
      echo fmt"   (Variant tracking will be added to database in next update)"
    echo fmt"🔗 Symlinks created in /System/Links/"
    echo ""

    # Display what USE flags were used
    if effectiveUseFlags.len > 0:
      echo "📋 Package built with USE flags:"
      let enabled = getEnabledFlags(effectiveUseFlags)
      if enabled.len > 0:
        echo "   Enabled: " & enabled.map(proc(s: string): string = "+" & s).join(" ")
      let disabled = getDisabledFlags(effectiveUseFlags)
      if disabled.len > 0:
        echo "   Disabled: " & disabled.map(proc(s: string): string = "-" & s).join(" ")
      echo ""

    echo fmt"You can now run: {packageName}"
    logSuccess("graft", fmt"{packageName} installed to {result.installPath} with variant {variantHash}")
    return 0
  else:
    echo ""
    echo "❌ Graft failed!"
    for error in result.errors:
      echo fmt"   Error: {error}"
      logError(fmt"Graft error: {error}")
    for warning in result.warnings:
      echo fmt"   Warning: {warning}"
      logWarning(fmt"Graft warning: {warning}")
    logFailure("graft", fmt"Failed to install {packageName}")
    return 1
