import std/[os, strutils, options]
import nimpak/packages
import nimpak/types
import nimpak/cas

proc runConvertCommand*(args: seq[string]) =
  if args.len < 2:
    echo "Usage: nip convert <grafted_package_dir>"
    quit(1)

  let graftedDir = args[1]

  # Load graft result metadata (simulate loading from graftedDir)
  # In real implementation, this would parse graft metadata files
  # Here, we simulate with placeholders for demonstration

  # TODO: Replace with actual loading/parsing of graft metadata
  let dummyFragment = Fragment(
    id: PackageId(name: "dummy", version: "0.1.0", stream: Stable),
    source: Source(
      url: "https://example.com/dummy-0.1.0.tar.gz",
      hash: "blake2b-dummyhash",
      hashAlgorithm: "blake2b",
      sourceMethod: Http,
      timestamp: now()
    ),
    dependencies: @[],
    buildSystem: Custom,
    metadata: PackageMetadata(
      description: "Dummy package for conversion",
      license: "MIT",
      maintainer: "dummy@example.com",
      tags: @[],
      runtime: RuntimeProfile(
        libc: Musl,
        allocator: System,
        systemdAware: false,
        reproducible: true,
        tags: @[]
      )
    ),
    acul: AculCompliance(required: false, membership: "", attribution: "", buildLog: "")
  )

  let dummyAuditLog = GraftAuditLog(
    timestamp: now(),
    source: Pacman,
    packageName: "dummy",
    version: "0.1.0",
    downloadedFilename: "dummy-0.1.0.tar.gz",
    archiveHash: "blake2b-dummyhash",
    hashAlgorithm: "blake2b",
    sourceOutput: "Simulated graft source output",
    downloadUrl: none(string),
    originalSize: 12345,
    deduplicationStatus: "New"
  )

  let graftResult = GraftResult(
    fragment: dummyFragment,
    extractedPath: graftedDir,
    originalMetadata: %*{},
    auditLog: dummyAuditLog
  )

  let convertResult = convertGraftToNpk(graftResult)
  if convertResult.isErr:
    echo "Conversion failed: ", convertResult.getError().msg
    quit(1)

  let npk = convertResult.get()

  # Create archive path
  let archivePath = graftedDir / (npk.metadata.id.name & "-" & npk.metadata.id.version & ".npk")

  let archiveResult = createNpkArchive(npk, archivePath)
  if archiveResult.isErr:
    echo "Failed to create NPK archive: ", archiveResult.getError().msg
    quit(1)

  echo "Conversion successful. NPK archive created at: ", archivePath

# Entry point for the command
when isMainModule:
  runConvertCommand(commandLineParams())
