import unittest, os, strutils, base64
import ../src/nimpak/signature
import ../src/nip/types

suite "Signature Management Tests":
  
  var 
    manager: SignatureManager
    testRoot = getTempDir() / "nip_sig_test_" & $getCurrentProcessId()
    keyId = "test-key-1"
    testData = "Hello, Signed World!"

  setup:
    createDir(testRoot)
    manager = initSignatureManager(testRoot)

  teardown:
    removeDir(testRoot)

  test "Initialization":
    check dirExists(manager.keysPath)
    check dirExists(manager.privateKeysPath)
    check dirExists(manager.publicKeysPath)
    check dirExists(manager.trustedKeysPath)

  test "Key Generation":
    let kpInfo = manager.generateKeyPair(keyId)
    check kpInfo.id == keyId
    check kpInfo.publicKey.len > 0
    check kpInfo.privateKey.len > 0
    
    check fileExists(manager.privateKeysPath / keyId & ".key")
    check fileExists(manager.publicKeysPath / keyId & ".pub")

  test "Sign and Verify":
    discard manager.generateKeyPair(keyId)
    manager.trustKey(keyId) # Must trust key to verify
    
    # Reload trusted keys
    var mutManager = manager # Make mutable copy for loading
    mutManager.loadTrustedKeys()
    
    let signature = manager.sign(testData, keyId)
    check signature.len > 0
    
    let isValid = mutManager.verify(testData, signature, keyId)
    check isValid

  test "Verification Failure - Tampered Data":
    discard manager.generateKeyPair(keyId)
    manager.trustKey(keyId)
    var mutManager = manager
    mutManager.loadTrustedKeys()
    
    let signature = manager.sign(testData, keyId)
    let isValid = mutManager.verify(testData & "tampered", signature, keyId)
    check not isValid

  test "Verification Failure - Invalid Signature":
    discard manager.generateKeyPair(keyId)
    manager.trustKey(keyId)
    var mutManager = manager
    mutManager.loadTrustedKeys()
    
    # Create a fake signature (valid base64 but wrong content)
    let fakeSigBytes = newSeq[byte](64)
    let fakeSig = base64.encode(fakeSigBytes)
    
    let isValid = mutManager.verify(testData, fakeSig, keyId)
    check not isValid

  test "Trust Management":
    discard manager.generateKeyPair(keyId)
    
    # Initially not trusted
    check not fileExists(manager.trustedKeysPath / keyId & ".pub")
    
    # Trust
    manager.trustKey(keyId)
    check fileExists(manager.trustedKeysPath / keyId & ".pub")
    
    # Revoke
    manager.revokeKey(keyId)
    check not fileExists(manager.trustedKeysPath / keyId & ".pub")
