import std/[unittest, os, tempfiles, strutils]
import nip/archives
import nip/manifest_parser

suite "NIP Archive Tests":

  setup:
    let tempDir = createTempDir("nip_test_archive_", "")
    let sourceDir = tempDir / "source"
    let outputDir = tempDir / "output"
    let extractDir = tempDir / "extract"
    
    createDir(sourceDir)
    createDir(outputDir)
    createDir(extractDir)

  teardown:
    removeDir(tempDir)

  test "Create and Extract Archive":
    # 1. Create Source Content
    writeFile(sourceDir / "hello.txt", "Hello World")
    createDir(sourceDir / "subdir")
    writeFile(sourceDir / "subdir/config.cfg", "key=value")
    
    # 2. Create Manifest
    let manifest = PackageManifest(
      name: "test-pkg",
      version: parseSemanticVersion("1.0.0"),
      license: "MIT"
    )
    
    # 3. Create Archive
    let archivePath = outputDir / "test.nip"
    createArchive(manifest, sourceDir, archivePath)
    
    check fileExists(archivePath)
    check verifyArchive(archivePath)
    
    # 4. Extract Archive
    extractArchive(archivePath, extractDir)
    
    # 5. Verify Content
    check fileExists(extractDir / "manifest.kdl")
    check fileExists(extractDir / "files/hello.txt")
    check fileExists(extractDir / "files/subdir/config.cfg")
    
    check readFile(extractDir / "files/hello.txt") == "Hello World"
    
    # 6. Verify Manifest Content
    let extractedManifest = parseManifest(readFile(extractDir / "manifest.kdl"), NIP, FormatKDL)
    check extractedManifest.name == "test-pkg"
    check $extractedManifest.version == "1.0.0"
