## test_variant_manager.nim
## Tests for variant manager orchestration

import std/[unittest, tables, os, times, strutils]
import ../src/nimpak/variant_manager
import ../src/nimpak/variant_types
import ../src/nimpak/variant_profiles
import ../src/nimpak/config

suite "Variant Manager":

  setup:
    # Create temporary test database
    let testDbPath = "/tmp/test_variant_mgr_" & $epochTime().int
    let vm = newVariantManager(testDbPath)

  teardown:
    # Clean up test database
    try:
      removeDir(testDbPath)
    except:
      discard

  test "Create variant with domain flags":
    var domains = initTable[string, seq[string]]()
    domains["init"] = @["dinit"]
    domains["graphics"] = @["wayland"]  # Exclusive domain - only one value
    domains["security"] = @["pie", "relro"]  # Non-exclusive - multiple values OK

    let compilerFlags = CompilerFlags(
      cflags: "-O3",
      ldflags: "-Wl,-O1",
      makeflags: "-j8"
    )

    let result = vm.createVariant(
      "firefox",
      "118.0",
      domains,
      compilerFlags
    )

    if not result.success:
      echo "Error: ", result.error

    check result.success == true
    check result.fingerprint.packageName == "firefox"
    check result.fingerprint.version == "118.0"
    check result.fingerprint.hash.len > 0

  test "Create variant from profile":
    var profile = newVariantProfile("test-profile", "Test profile")
    profile.domains["init"] = @["systemd"]
    profile.domains["graphics"] = @["X"]
    profile.compilerFlags.cflags = "-O2"

    let result = vm.createVariantFromProfile(
      "vim",
      "9.0.2",
      profile
    )

    check result.success == true
    check result.fingerprint.packageName == "vim"

  test "List variants for package":
    var domains = initTable[string, seq[string]]()
    domains["init"] = @["dinit"]

    let compilerFlags = CompilerFlags()

    discard vm.createVariant("htop", "3.2.2", domains, compilerFlags)
    discard vm.createVariant("htop", "3.2.3", domains, compilerFlags)

    let variants = vm.listVariants("htop")

    check variants.len == 2

  test "Calculate variant ID without creating":
    var domains = initTable[string, seq[string]]()
    domains["init"] = @["dinit"]
    domains["graphics"] = @["wayland"]

    let compilerFlags = CompilerFlags(cflags: "-O3")

    let fingerprint = vm.calculateVariantId(
      "git",
      "2.41.0",
      domains,
      compilerFlags
    )

    check fingerprint.len > 0
    check fingerprint.startsWith("blake2b-")

  test "Validate domain flags":
    var validDomains = initTable[string, seq[string]]()
    validDomains["init"] = @["dinit"]
    validDomains["graphics"] = @["wayland"]

    let validation = vm.validateFlags(validDomains)

    check validation.isOk == true

when isMainModule:
  echo "Running variant manager tests..."
