import std/[unittest, options]
import nip/manifest_parser

suite "NIP Desktop Integration Tests":

  test "Parse JSON with Desktop Config":
    let jsonContent = """
    {
      "name": "browser",
      "version": "1.0.0",
      "license": "MIT",
      "desktop": {
        "display_name": "My Browser",
        "icon": "browser-icon",
        "terminal": false,
        "categories": ["Network", "WebBrowser"],
        "mime_types": ["text/html", "application/xhtml+xml"]
      }
    }
    """
    
    let manifest = parseManifest(jsonContent, NIP, FormatJSON)
    check manifest.desktop.isSome
    let dt = manifest.desktop.get()
    
    check dt.displayName == "My Browser"
    check dt.icon == some("browser-icon")
    check dt.terminal == false
    check dt.categories == @["Network", "WebBrowser"]
    check dt.mimeTypes.len == 2

  test "Parse KDL with Desktop Config":
    let kdlContent = """
    package "browser" {
      version "1.0.0"
      license "MIT"
      
      desktop display_name="My Browser" icon="browser-icon" terminal=false {
        categories "Network" "WebBrowser"
        mime_types "text/html" "application/xhtml+xml"
      }
    }
    """
    
    let manifest = parseManifest(kdlContent, NIP, FormatKDL)
    check manifest.desktop.isSome
    let dt = manifest.desktop.get()
    
    check dt.displayName == "My Browser"
    check dt.icon == some("browser-icon")
    check dt.categories == @["Network", "WebBrowser"]

  test "Serialization Roundtrip":
    var manifest = PackageManifest(
      format: NIP,
      name: "app",
      version: parseSemanticVersion("1.0.0"),
      license: "MIT"
    )
    
    manifest.desktop = some(DesktopIntegration(
      displayName: "My App",
      icon: some("app-icon"),
      categories: @["Utility"],
      terminal: true
    ))
    
    # JSON
    let jsonStr = serializeManifestToJSON(manifest)
    let jsonManifest = parseManifest(jsonStr, NIP, FormatJSON)
    check jsonManifest.desktop.get().displayName == "My App"
    check jsonManifest.desktop.get().terminal == true
    
    # KDL
    let kdlStr = serializeManifestToKDL(manifest)
    let kdlManifest = parseManifest(kdlStr, NIP, FormatKDL)
    check kdlManifest.desktop.get().displayName == "My App"
    check kdlManifest.desktop.get().categories == @["Utility"]

  test "Hash Determinism":
    var m1 = PackageManifest(name: "app", version: parseSemanticVersion("1.0.0"), license: "MIT")
    m1.desktop = some(DesktopIntegration(
      displayName: "App",
      categories: @["B", "A"] # Unsorted
    ))
    
    var m2 = PackageManifest(name: "app", version: parseSemanticVersion("1.0.0"), license: "MIT")
    m2.desktop = some(DesktopIntegration(
      displayName: "App",
      categories: @["A", "B"] # Sorted
    ))
    
    check calculateManifestHash(m1) == calculateManifestHash(m2)
