## Simple Test for Enhanced Garbage Collection System

import unittest, tables, sets, strutils, os, times
import ../src/nimpak/gc
import ../src/nimpak/cas

suite "Enhanced Garbage Collection Basic Tests":
  setup:
    # Create temporary test environment
    let testDir = getTempDir() / "nip_gc_test_" & $getTime().toUnix()
    createDir(testDir)
    
    # Initialize test CAS manager
    var cas = initCasManager(testDir)

  teardown:
    # Clean up test environment
    if dirExists(testDir):
      removeDir(testDir)

  test "Garbage Collection Module Loads and Initializes":
    ## Verify the garbage collection module can be initialized
    echo "Testing garbage collection initialization..."

    # Create test data as byte sequence
    var testData: seq[byte] = @[84, 101, 115, 116, 32, 100, 97, 116, 97, 32, 102, 111, 114, 32, 71, 67]  # "Test data for GC"
    # let hash = cas.computeHash(testData)

    # Store object
    let storeResult = cas.storeObject(testData)
    check storeResult.isOk

    # Initialize garbage collector
    var gc = initGarbageCollector(addr cas)
    
    # Test threshold checking (should not trigger in test environment)
    check not gc.shouldTriggerGarbageCollection()

    # Test garbage collection with empty garbage
    let gcResult = gc.garbageCollect()
    check gcResult.isOk

    echo "✓ Garbage collection initialization test passed"

  test "Threshold Configuration and Should Trigger Logic":
    ## Test threshold configuration and triggering logic
    echo "Testing threshold configuration..."

    # Test default configuration
    var gc = initGarbageCollector(addr cas)
    
    # Should not trigger with default config
    check not gc.shouldTriggerGarbageCollection()

    # Test with always-trigger configuration
    var triggerConfig = GcTriggerConfig(
      storageThreshold: 0.0,  # Always trigger
      timeIntervalHours: 0,   # Disabled
      minFreeSpace: 0,        # Disabled  
      adaptiveMode: false
    )
    
    var gcConfig = GcConfig(
      priorityStrategy: Balanced,
      batchSize: 100,
      maxWorkers: 1,
      dryRun: false,
      verbose: false,
      adaptiveMode: false
    )
    
    # Store some data to ensure non-zero usage
    discard cas.storeObject(@[1.byte, 2.byte, 3.byte])

    gc = initGarbageCollector(addr cas, gcConfig, triggerConfig)
    check gc.shouldTriggerGarbageCollection()

    echo "✓ Threshold configuration test passed"

  test "Garbage Collection Safety - Referenced Objects Protected":
    ## Test that referenced objects are not deleted
    echo "Testing garbage collection safety..."

    # Create test data
    var testData: seq[byte] = @[83, 97, 102, 101, 32, 116, 101, 115, 116]  # "Safe test"
    let hash = cas.computeHash(testData)

    # Store object and add reference
    discard cas.storeObject(testData)
    discard cas.addReference(hash, NPK, "safe-package")

    # Verify object exists and has references
    check cas.objectExists(hash)
    check cas.getRefCount(hash) >= 1

    # Run garbage collection
    var gc = initGarbageCollector(addr cas)
    let gcResult = gc.garbageCollect()
    check gcResult.isOk

    # Object should still exist (was referenced)
    check cas.objectExists(hash)

    echo "✓ Garbage collection safety test passed"

  test "Format Priority Strategies":
    ## Test different format priority strategies
    echo "Testing format priority strategies..."

    # Create garbage for all formats
    let npkGarbage = @["npk-1", "npk-2"]
    let nipGarbage = @["nip-1", "nip-2"] 
    let nexterGarbage = @["nexter-1", "nexter-2"]

    var formatGarbage = initTable[FormatType, seq[string]]()
    formatGarbage[NPK] = npkGarbage
    formatGarbage[NIP] = nipGarbage
    formatGarbage[NEXTER] = nexterGarbage

    # Test SafetyFirst priority
    let prioritized = prioritizeGarbage(formatGarbage, SafetyFirst)
    check prioritized[0..1] == nipGarbage  # NIP first for safety
    check prioritized[2..3] == nexterGarbage  # NEXTER second
    check prioritized[4..5] == npkGarbage  # NPK last

    # Test Aggressive priority  
    let aggressive = prioritizeGarbage(formatGarbage, Aggressive)
    check aggressive[0..1] == npkGarbage  # NPK first for space
    check aggressive[2..3] == nexterGarbage  # NEXTER second
    check aggressive[4..5] == nipGarbage  # NIP last

    echo "✓ Format priority strategies test passed"

  test "Statistics and Reporting":
    ## Test garbage collection statistics and reporting
    echo "Testing statistics and reporting..."

    var gc = initGarbageCollector(addr cas)
    let gcResult = gc.garbageCollect()
    check gcResult.isOk
    
    if gcResult.isOk:
      let stats = gcResult.get()
      
      # Verify statistics are valid
      check stats.deletedCount >= 0
      check stats.sizeFreed >= 0
      check stats.identificationTime >= 0.0
      check stats.deletionTime >= 0.0
      check stats.formatsProcessed >= 0

      # Test stats accessor
      let gcStats = gc.getGcStats()
      check gcStats.deletedCount == stats.deletedCount

    echo "✓ Statistics and reporting test passed"

echo "Enhanced Garbage Collection Basic Test Suite Complete!"
echo "Validated core functionality:"
echo "✓ Module initialization and configuration"
echo "✓ Threshold-based triggering logic"
echo "✓ Safety guarantees for referenced objects"
echo "✓ Format priority strategies"
echo "✓ Statistics and reporting"