## Enhanced Search Command with CAS Path Demonstration
##
## This module implements the enhanced search command that showcases the
## Content Addressable Storage (CAS) system and variant fingerprint architecture.
## It demonstrates the revolutionary approach where packages are identified by
## cryptographic hashes rather than just names and versions.

import std/[os, strutils, times, json, tables, sequtils, algorithm, strformat, options, sugar]
import ../types_fixed, ../database, ../cas, core
import nimcrypto/blake2
import forensic_integrity, security_integration

type
  VariantFingerprint* = object
    ## Represents a complete variant fingerprint based on build configuration
    packageName*: string
    version*: string
    features*: Table[string, string]  # Feature selections (+http2, ssl=openssl)
    buildFlags*: Table[string, string]  # Build flags (lto=thin, debug=false)
    toolchain*: string  # Compiler toolchain (clang-18, gcc-13)
    target*: string     # Target architecture (x86_64-linux-gnu)
    patches*: seq[string]  # Applied patches
    cid*: string        # Content Identifier (BLAKE3 hash)
    casPath*: string    # CAS filesystem path

  PackageVariant* = object
    ## Enhanced package information with CAS awareness
    name*: string
    version*: string
    description*: string
    stream*: string
    tags*: seq[string]
    variants*: seq[VariantFingerprint]
    installStatus*: InstallStatus
    repository*: string
    size*: int64
    installDate*: Option[DateTime]
    integrityStatus*: IntegrityStatus

  InstallStatus* = enum
    NotInstalled,     # ◻ Available but not installed
    Installed,        # ✅ Installed and verified
    UpdateAvailable,  # ⬆ Update available
    Masked           # ⛔ Masked/blocked

  IntegrityStatus* = enum
    Verified,         # ✅ Cryptographically verified
    UserModified,     # ⚠️ Modified with admin attestation
    Tampered,         # 🔴 Unauthorized modification detected
    Unknown          # ? Status unknown

proc calculateVariantFingerprint*(name: string, version: string,
                                 features: Table[string, string] = initTable[string, string](),
                                 buildFlags: Table[string, string] = initTable[string, string](),
                                 toolchain: string = "gcc-13",
                                 target: string = "x86_64-linux-gnu",
                                 patches: seq[string] = @[]): VariantFingerprint =
  ## Calculate variant fingerprint from complete build configuration
  ## This demonstrates the core concept: packages are identified by their complete build tuple

  # Create deterministic build tuple for hashing
  var buildTuple = ""
  buildTuple.add("name=" & name & "\n")
  buildTuple.add("version=" & version & "\n")
  buildTuple.add("toolchain=" & toolchain & "\n")
  buildTuple.add("target=" & target & "\n")

  # Add features in sorted order for determinism
  let sortedFeatures = toSeq(features.pairs).sortedByIt(it[0])
  for (key, value) in sortedFeatures:
    buildTuple.add("feature." & key & "=" & value & "\n")

  # Add build flags in sorted order
  let sortedFlags = toSeq(buildFlags.pairs).sortedByIt(it[0])
  for (key, value) in sortedFlags:
    buildTuple.add("flag." & key & "=" & value & "\n")

  # Add patches in order
  for patch in patches:
    buildTuple.add("patch=" & patch & "\n")

  # Calculate BLAKE3 hash (using BLAKE2b as placeholder)
  let tupleBytes = buildTuple.toOpenArrayByte(0, buildTuple.len - 1).toSeq()
  let digest = blake2_512.digest(tupleBytes)
  let shortHash = ($digest)[0..11]  # First 12 chars for readability
  let cid = "blake3-" & shortHash

  # Generate CAS path
  let casPath = fmt"/Programs/{name}/{version}-{shortHash}/"

  result = VariantFingerprint(
    packageName: name,
    version: version,
    features: features,
    buildFlags: buildFlags,
    toolchain: toolchain,
    target: target,
    patches: patches,
    cid: cid,
    casPath: casPath
  )

proc generateSampleVariants*(name: string, version: string): seq[VariantFingerprint] =
  ## Generate sample variants to demonstrate the variant fingerprint system
  result = @[]

  case name:
  of "nginx":
    # Default variant
    result.add(calculateVariantFingerprint(name, version))

    # Variant with HTTP/2 and Brotli
    var features1 = initTable[string, string]()
    features1["http2"] = "true"
    features1["brotli"] = "true"
    features1["ssl"] = "openssl"
    result.add(calculateVariantFingerprint(name, version, features1))

    # Hardened variant with different toolchain
    var features2 = initTable[string, string]()
    features2["ssl"] = "boringssl"
    var flags2 = initTable[string, string]()
    flags2["lto"] = "thin"
    flags2["hardening"] = "full"
    result.add(calculateVariantFingerprint(name, version, features2, flags2, "clang-18"))

  of "vim":
    # Default variant
    result.add(calculateVariantFingerprint(name, version))

    # Variant with Lua support
    var features1 = initTable[string, string]()
    features1["lua"] = "true"
    features1["python"] = "false"
    result.add(calculateVariantFingerprint(name, version, features1))

    # Full-featured variant
    var features2 = initTable[string, string]()
    features2["lua"] = "true"
    features2["python"] = "true"
    features2["ruby"] = "true"
    features2["gui"] = "gtk3"
    result.add(calculateVariantFingerprint(name, version, features2))

  of "git":
    # Default variant
    result.add(calculateVariantFingerprint(name, version))

    # Variant with different SSL backend
    var features1 = initTable[string, string]()
    features1["ssl"] = "gnutls"
    features1["curl"] = "system"
    result.add(calculateVariantFingerprint(name, version, features1))

  else:
    # Single default variant for other packages
    result.add(calculateVariantFingerprint(name, version))

proc checkInstallStatus*(variants: seq[VariantFingerprint]): InstallStatus =
  ## Check installation status across all variants
  ## This simulates checking the CAS filesystem for installed variants

  for variant in variants:
    # Simulate checking if CAS path exists
    let casExists = dirExists(expandTilde("~/.nip/cas/objects"))  # Simplified check
    if casExists:
      # Simulate random installation status for demo
      case variant.packageName:
      of "htop", "vim": return Installed
      of "git": return UpdateAvailable
      of "firefox": return Masked
      else: return NotInstalled

  return NotInstalled

proc checkIntegrityStatus*(variant: VariantFingerprint): IntegrityStatus =
  ## Check integrity status of installed variant using forensic system

  if not dirExists(variant.casPath):
    return Unknown

  # Use forensic system to check integrity
  let violations = forensic_integrity.simulateFileModification(variant.casPath)

  if violations.len == 0:
    return Verified
  elif violations.len > 2:
    return Tampered  # Multiple violations = tampering
  else:
    return UserModified  # Few violations = user customization

proc enhancedSearchCommand*(query: string, outputFormat: core.OutputFormat = core.OutputHuman,
                           showVariants: bool = true, showCasPaths: bool = true): CommandResult =
  ## Enhanced search command demonstrating CAS paths and variant fingerprints
  try:
    let db = newPackageDatabase()
    db.initDatabase()

    core.showInfo(fmt"🔍 Searching for packages matching: {query}")
    core.showInfo("📊 Analyzing variant fingerprints and CAS paths...")

    let foundPackages = db.searchPackages(query)
    var enhancedResults: seq[PackageVariant] = @[]

    # Convert to enhanced package variants
    for pkg in foundPackages:
      let variants = generateSampleVariants(pkg.name, pkg.version)
      let installStatus = checkInstallStatus(variants)
      let installDate = if installStatus == Installed: some(now() - 7.days) else: none(DateTime)

      enhancedResults.add(PackageVariant(
        name: pkg.name,
        version: pkg.version,
        description: pkg.description,
        stream: pkg.stream,
        tags: pkg.tags,
        variants: variants,
        installStatus: installStatus,
        repository: "nexusos-" & pkg.stream,
        size: pkg.size,
        installDate: installDate,
        integrityStatus: if installStatus == Installed: checkIntegrityStatus(variants[0]) else: Unknown
      ))

    # Create structured output
    var searchResults = newJArray()
    for pkg in enhancedResults:
      var variantArray = newJArray()
      for variant in pkg.variants:
        variantArray.add(%*{
          "cid": variant.cid,
          "cas_path": variant.casPath,
          "features": variant.features,
          "build_flags": variant.buildFlags,
          "toolchain": variant.toolchain,
          "target": variant.target,
          "integrity_status": $checkIntegrityStatus(variant)
        })

      searchResults.add(%*{
        "name": pkg.name,
        "version": pkg.version,
        "description": pkg.description,
        "stream": pkg.stream,
        "repository": pkg.repository,
        "install_status": $pkg.installStatus,
        "integrity_status": $pkg.integrityStatus,
        "size": pkg.size,
        "install_date": if pkg.installDate.isSome: %($pkg.installDate.get) else: newJNull(),
        "variants": variantArray,
        "tags": pkg.tags
      })

    let result = %*{
      "query": query,
      "results": searchResults,
      "total_found": enhancedResults.len,
      "cas_enabled": true,
      "variant_fingerprints": true
    }

    # Human-readable output
    if outputFormat == core.OutputHuman:
      echo ""
      echo bold("🌟 Enhanced Search Results: " & highlight(query))
      echo bold("═══════════════════════════════════════════════════════════════")
      echo ""

      if enhancedResults.len == 0:
        echo warning("No packages found matching: " & query)
        return successResult("No packages found", result)

      for pkg in enhancedResults:
        # Package header with status indicators
        let statusIcon = case pkg.installStatus:
          of Installed: "✅"
          of UpdateAvailable: "⬆️ "
          of NotInstalled: "◻️ "
          of Masked: "⛔"

        let integrityIcon = case pkg.integrityStatus:
          of Verified: ""
          of UserModified: " ⚠️ "
          of Tampered: " 🔴"
          of Unknown: ""

        echo statusIcon & " " & bold(pkg.name) & " " & highlight(pkg.version) &
             " (" & pkg.repository & ")" & integrityIcon
        echo "    " & pkg.description

        if pkg.tags.len > 0:
          echo "    Tags: " & pkg.tags.join(", ")

        if pkg.installDate.isSome:
          echo "    Installed: " & pkg.installDate.get.format("yyyy-MM-dd") &
               " | Size: " & formatFileSize(pkg.size)

        if showVariants and pkg.variants.len > 1:
          echo ""
          echo "    🧬 " & bold("Available Variants:")
          for i, variant in pkg.variants:
            let integrityStatus = checkIntegrityStatus(variant)
            let integrityIcon = case integrityStatus:
              of Verified: "✅"
              of UserModified: "⚠️ "
              of Tampered: "🔴"
              of Unknown: "❓"

            echo fmt"      [{i+1}] {integrityIcon} CID: {variant.cid}"

            if showCasPaths:
              echo fmt"          📁 CAS Path: {variant.casPath}"

            if variant.features.len > 0:
              let featureStr = toSeq(variant.features.pairs).mapIt(it[0] & "=" & it[1]).join(", ")
              echo fmt"          🔧 Features: {featureStr}"

            if variant.buildFlags.len > 0:
              let flagStr = toSeq(variant.buildFlags.pairs).mapIt(it[0] & "=" & it[1]).join(", ")
              echo fmt"          ⚙️  Flags: {flagStr}"

            if variant.toolchain != "gcc-13":
              echo fmt"          🛠️  Toolchain: {variant.toolchain}"

        elif showCasPaths and pkg.variants.len > 0:
          let mainVariant = pkg.variants[0]
          echo fmt"    📁 CAS Path: {mainVariant.casPath}"
          echo fmt"    🆔 CID: {mainVariant.cid}"

        echo ""

      echo bold("Summary:")
      let totalVariants = enhancedResults.mapIt(it.variants.len).foldl(a + b, 0)
      echo fmt"  📦 Found {enhancedResults.len} packages with {totalVariants} total variants"
      echo fmt"  ✅ {enhancedResults.countIt(it.installStatus == Installed)} installed"
      echo fmt"  ⬆️  {enhancedResults.countIt(it.installStatus == UpdateAvailable)} updates available"
      echo fmt"  🔴 {enhancedResults.countIt(it.integrityStatus == Tampered)} integrity violations"

      echo ""
      echo info("💡 Use 'nip show <package>' to see detailed variant information")
      echo info("💡 Use 'nip install <package> --variant <cid>' to install specific variants")

    else:
      # Machine-readable output
      outputData(result)

    return successResult(fmt"Found {enhancedResults.len} packages", result)

  except Exception as e:
    return errorResult(fmt"Enhanced search failed: {e.msg}")

proc enhancedListCommand*(pattern: string = "", showVariants: bool = true,
                         showTampered: bool = false, outputFormat: core.OutputFormat = core.OutputHuman): CommandResult =
  ## Enhanced list command with CAS awareness and pattern filtering
  try:
    let db = newPackageDatabase()
    db.initDatabase()

    core.showInfo("📋 Listing installed packages with CAS analysis...")

    let installedPackages = db.listInstalled()
    var filteredPackages = installedPackages

    # Apply pattern filtering if specified
    if pattern != "":
      filteredPackages = installedPackages.filterIt(
        pattern.toLower() in it.name.toLower() or
        pattern.toLower() in it.stream.toLower()
      )

    var enhancedResults: seq[PackageVariant] = @[]

    for pkg in filteredPackages:
      let variants = generateSampleVariants(pkg.name, pkg.version)
      let integrityStatus = if variants.len > 0: checkIntegrityStatus(variants[0]) else: Unknown

      # Filter by tampered status if requested
      if showTampered and integrityStatus != Tampered:
        continue

      enhancedResults.add(PackageVariant(
        name: pkg.name,
        version: pkg.version,
        description: "",  # Not stored in installed packages
        stream: pkg.stream,
        tags: @[],
        variants: variants,
        installStatus: Installed,
        repository: "nexusos-" & pkg.stream,
        size: pkg.size,
        installDate: some(pkg.installDate),
        integrityStatus: integrityStatus
      ))

    # Sort by installation date (newest first)
    enhancedResults.sort(proc(a, b: PackageVariant): int =
      if a.installDate.isSome and b.installDate.isSome:
        cmp(b.installDate.get, a.installDate.get)
      else:
        cmp(a.name, b.name)
    )

    # Create structured output
    var listResults = newJArray()
    for pkg in enhancedResults:
      var variantArray = newJArray()
      for variant in pkg.variants:
        variantArray.add(%*{
          "cid": variant.cid,
          "cas_path": variant.casPath,
          "integrity_status": $checkIntegrityStatus(variant)
        })

      listResults.add(%*{
        "name": pkg.name,
        "version": pkg.version,
        "stream": pkg.stream,
        "install_date": $pkg.installDate.get,
        "size": pkg.size,
        "integrity_status": $pkg.integrityStatus,
        "variants": variantArray
      })

    let result = %*{
      "type": "installed",
      "pattern": pattern,
      "show_tampered_only": showTampered,
      "packages": listResults,
      "total": enhancedResults.len,
      "total_size": enhancedResults.mapIt(it.size).foldl(a + b, 0'i64)
    }

    # Human-readable output
    if outputFormat == core.OutputHuman:
      echo ""
      let titleSuffix = if pattern != "": fmt" (filtered by: {pattern})" else: ""
      let tamperedSuffix = if showTampered: " - TAMPERED ONLY" else: ""
      echo bold(fmt"📦 Installed Packages ({enhancedResults.len}){titleSuffix}{tamperedSuffix}")
      echo bold("═══════════════════════════════════════════════════════════════")
      echo ""

      if enhancedResults.len == 0:
        if showTampered:
          echo success("✅ No tampered packages found - system integrity intact!")
        else:
          echo warning("No installed packages found" & (if pattern != "": fmt" matching: {pattern}" else: ""))
        return successResult("No packages found", result)

      for pkg in enhancedResults:
        let integrityIcon = case pkg.integrityStatus:
          of Verified: "✅"
          of UserModified: "⚠️ "
          of Tampered: "🔴"
          of Unknown: "❓"

        echo integrityIcon & " " & bold(pkg.name) & " " & highlight(pkg.version) &
             " (" & pkg.stream & ")"
        let installDateStr = pkg.installDate.get.format("yyyy-MM-dd")
        echo fmt"    Size: {formatFileSize(pkg.size)} | Installed: {installDateStr}"

        if pkg.variants.len > 0:
          let mainVariant = pkg.variants[0]
          echo fmt"    📁 CAS Path: {mainVariant.casPath}"
          echo fmt"    🆔 CID: {mainVariant.cid}"

          if pkg.integrityStatus == Tampered:
            echo "    " & error("⚠️  INTEGRITY VIOLATION DETECTED")
            echo "    " & info("💡 Run 'nip diagnose " & mainVariant.cid & "' for forensic analysis")
          elif pkg.integrityStatus == UserModified:
            echo "    " & warning("⚠️  User-modified (attested)")

        echo ""

      let totalSize = enhancedResults.mapIt(it.size).foldl(a + b, 0'i64)
      echo bold("Summary:")
      echo fmt"  📦 Total packages: {enhancedResults.len}"
      echo fmt"  💾 Total size: {formatFileSize(totalSize)}"
      echo fmt"  ✅ Verified: {enhancedResults.countIt(it.integrityStatus == Verified)}"
      echo fmt"  ⚠️  User-modified: {enhancedResults.countIt(it.integrityStatus == UserModified)}"
      echo fmt"  🔴 Tampered: {enhancedResults.countIt(it.integrityStatus == Tampered)}"

      if enhancedResults.anyIt(it.integrityStatus == Tampered):
        echo ""
        echo error("🚨 SECURITY ALERT: Tampered packages detected!")
        echo info("💡 Run 'nip list --tampered' to see only compromised packages")
        echo info("💡 Run 'nip verify --all' for comprehensive integrity scan")

    else:
      outputData(result)

    return successResult(fmt"Listed {enhancedResults.len} packages", result)

  except Exception as e:
    return errorResult(fmt"Enhanced list failed: {e.msg}")

proc whereCommand*(packageName: string): CommandResult =
  ## Show CAS filesystem paths for a package
  try:
    let db = newPackageDatabase()
    db.initDatabase()

    if packageName notin db.packages:
      return errorResult(fmt"Package '{packageName}' not found")

    let pkg = db.getPackage(packageName)
    let variants = generateSampleVariants(pkg.name, pkg.version)
    let installStatus = checkInstallStatus(variants)

    if installStatus == NotInstalled:
      return errorResult(fmt"Package '{packageName}' is not installed")

    core.showInfo(fmt"📁 CAS filesystem paths for: {packageName}")

    var result = newJObject()
    result["package"] = %packageName
    result["version"] = %pkg.version
    result["installed"] = %true

    var pathsArray = newJArray()

    echo ""
    echo bold(fmt"📦 {packageName} {pkg.version}")
    echo "═".repeat(50)

    for i, variant in variants:
      let integrityStatus = checkIntegrityStatus(variant)
      let integrityIcon = case integrityStatus:
        of Verified: "✅"
        of UserModified: "⚠️ "
        of Tampered: "🔴"
        of Unknown: "❓"

      echo fmt"[{i+1}] {integrityIcon} Variant CID: {variant.cid}"
      echo fmt"    📁 CAS Path: {variant.casPath}"
      echo fmt"    🔗 Symlinks:"
      echo fmt"      /usr/bin/{packageName} → {variant.casPath}bin/{packageName}"
      echo fmt"      /usr/lib/lib{packageName}.so → {variant.casPath}lib/lib{packageName}.so"

      if variant.features.len > 0:
        let featureStr = toSeq(variant.features.pairs).mapIt(it[0] & "=" & it[1]).join(", ")
        echo fmt"    🔧 Features: {featureStr}"

      pathsArray.add(%*{
        "variant_index": i + 1,
        "cid": variant.cid,
        "cas_path": variant.casPath,
        "integrity_status": $integrityStatus,
        "symlinks": [
          {"source": fmt"/usr/bin/{packageName}", "target": fmt"{variant.casPath}bin/{packageName}"},
          {"source": fmt"/usr/lib/lib{packageName}.so", "target": fmt"{variant.casPath}lib/lib{packageName}.so"}
        ],
        "features": variant.features
      })
      echo ""

    result["paths"] = pathsArray

    echo info("💡 Use 'nip files <package>' to see all files owned by this package")

    return successResult(fmt"Showed CAS paths for {packageName}", result)

  except Exception as e:
    return errorResult(fmt"Where command failed: {e.msg}")

proc variantsCommand*(packageName: string): CommandResult =
  ## Show all available variants for a package
  try:
    let db = newPackageDatabase()
    db.initDatabase()

    if packageName notin db.packages:
      return errorResult(fmt"Package '{packageName}' not found")

    let pkg = db.getPackage(packageName)
    let variants = generateSampleVariants(pkg.name, pkg.version)

    core.showInfo(fmt"🧬 Analyzing variants for: {packageName}")

    var result = newJObject()
    result["package"] = %packageName
    result["version"] = %pkg.version
    result["total_variants"] = %variants.len

    var variantsArray = newJArray()

    echo ""
    echo bold(fmt"🧬 Package Variants: {packageName} {pkg.version}")
    echo "═".repeat(60)
    echo ""

    for i, variant in variants:
      let integrityStatus = checkIntegrityStatus(variant)
      let integrityIcon = case integrityStatus:
        of Verified: "✅"
        of UserModified: "⚠️ "
        of Tampered: "🔴"
        of Unknown: "❓"

      let isInstalled = dirExists(expandTilde("~/.nip/cas/objects"))  # Simplified check
      let statusIcon = if isInstalled: "✅ INSTALLED" else: "◻️  AVAILABLE"

      echo bold(fmt"Variant {i+1}: {statusIcon} {integrityIcon}")
      echo fmt"  🆔 CID: {variant.cid}"
      echo fmt"  📁 CAS Path: {variant.casPath}"
      echo fmt"  🛠️  Toolchain: {variant.toolchain}"
      echo fmt"  🎯 Target: {variant.target}"

      if variant.features.len > 0:
        echo "  🔧 Features:"
        for (key, value) in variant.features.pairs:
          echo fmt"    • {key} = {value}"
      else:
        echo "  🔧 Features: (default configuration)"

      if variant.buildFlags.len > 0:
        echo "  ⚙️  Build Flags:"
        for (key, value) in variant.buildFlags.pairs:
          echo fmt"    • {key} = {value}"

      if variant.patches.len > 0:
        echo "  🩹 Patches:"
        for patch in variant.patches:
          echo fmt"    • {patch}"

      variantsArray.add(%*{
        "index": i + 1,
        "cid": variant.cid,
        "cas_path": variant.casPath,
        "toolchain": variant.toolchain,
        "target": variant.target,
        "features": variant.features,
        "build_flags": variant.buildFlags,
        "patches": variant.patches,
        "installed": isInstalled,
        "integrity_status": $integrityStatus
      })

      echo ""

    result["variants"] = variantsArray

    echo bold("Summary:")
    echo fmt"  📊 Total variants: {variants.len}"
    let installedCount = variants.countIt(dirExists(expandTilde("~/.nip/cas/objects")))
    echo fmt"  ✅ Installed: {installedCount}"
    let totalFeatures = variants.mapIt(it.features.len).foldl(a + b, 0)
    echo fmt"  🔧 Feature combinations: {totalFeatures}"
    echo ""
    echo info("💡 Use 'nip install <package> --variant <cid>' to install a specific variant")
    echo info("💡 Use 'nip cid <package> +feature -feature' to calculate variant fingerprints")

    return successResult(fmt"Showed {variants.len} variants for {packageName}", result)

  except Exception as e:
    return errorResult(fmt"Variants command failed: {e.msg}")

proc cidCommand*(args: seq[string]): CommandResult =
  ## Calculate variant CID from package name and feature specifications
  try:
    if args.len == 0:
      return errorResult("Usage: nip cid <package> [+feature] [-feature] [flag=value]")

    let packageName = args[0]
    let db = newPackageDatabase()
    db.initDatabase()

    if packageName notin db.packages:
      return errorResult(fmt"Package '{packageName}' not found")

    let pkg = db.getPackage(packageName)

    # Parse feature specifications from command line
    var features = initTable[string, string]()
    var buildFlags = initTable[string, string]()
    var toolchain = "gcc-13"
    var target = "x86_64-linux-gnu"

    for arg in args[1..^1]:
      if arg.startsWith("+"):
        # Enable feature: +http2
        let feature = arg[1..^1]
        features[feature] = "true"
      elif arg.startsWith("-"):
        # Disable feature: -lua
        let feature = arg[1..^1]
        features[feature] = "false"
      elif "=" in arg:
        let parts = arg.split("=", 1)
        if parts.len == 2:
          let key = parts[0]
          let value = parts[1]

          # Determine if it's a feature or build flag
          if key in ["ssl", "gui", "backend"]:
            features[key] = value
          elif key in ["toolchain"]:
            toolchain = value
          elif key in ["target"]:
            target = value
          else:
            buildFlags[key] = value

    core.showInfo(fmt"🧮 Calculating variant fingerprint for: {packageName}")

    let variant = calculateVariantFingerprint(packageName, pkg.version, features,
                                            buildFlags, toolchain, target)

    var result = newJObject()
    result["package"] = %packageName
    result["version"] = %pkg.version
    result["cid"] = %variant.cid
    result["cas_path"] = %variant.casPath
    result["features"] = %variant.features
    result["build_flags"] = %variant.buildFlags
    result["toolchain"] = %variant.toolchain
    result["target"] = %variant.target

    echo ""
    echo bold("🧮 Variant Fingerprint Calculation")
    echo "═".repeat(50)
    echo ""
    echo bold("Input Configuration:")
    echo fmt"  📦 Package: {packageName} {pkg.version}"
    echo fmt"  🛠️  Toolchain: {toolchain}"
    echo fmt"  🎯 Target: {target}"

    if features.len > 0:
      echo "  🔧 Features:"
      for (key, value) in features.pairs:
        echo fmt"    • {key} = {value}"
    else:
      echo "  🔧 Features: (default configuration)"

    if buildFlags.len > 0:
      echo "  ⚙️  Build Flags:"
      for (key, value) in buildFlags.pairs:
        echo fmt"    • {key} = {value}"

    echo ""
    echo bold("Generated Variant:")
    echo fmt"  🆔 CID: {variant.cid}"
    echo fmt"  📁 CAS Path: {variant.casPath}"

    let integrityStatus = checkIntegrityStatus(variant)
    let integrityIcon = case integrityStatus:
      of Verified: "✅ VERIFIED"
      of UserModified: "⚠️  USER-MODIFIED"
      of Tampered: "🔴 TAMPERED"
      of Unknown: "❓ NOT INSTALLED"

    echo fmt"  🔍 Status: {integrityIcon}"

    echo ""
    echo info("💡 This CID uniquely identifies this exact build configuration")
    echo info("💡 Use 'nip install <package> --variant " & variant.cid & "' to install this variant")

    return successResult(fmt"Calculated CID for {packageName}", result)

  except Exception as e:
    return errorResult(fmt"CID calculation failed: {e.msg}")

# Export all enhanced commands
export enhancedSearchCommand, enhancedListCommand, whereCommand, variantsCommand, cidCommand
# Export forensic commands
export forensic_integrity.verifyCommand, forensic_integrity.diagnoseCommand