## Repository Configuration Parser for NexusForge
## Parses repos.kdl files into RepoConfig objects

import std/[strutils, options, sequtils, os]
import ../kdl_parser
import ../../nip/types

proc parseRepoConfig*(path: string): seq[RepoConfig] =
  ## Parse repository configuration from a KDL file
  ## 
  ## Example KDL format:
  ## ```kdl
  ## repo "nexus-core" {
  ##     type "native"
  ##     url "https://repo.nexusos.io/v1"
  ##     key "ed25519-public-key..."
  ##     priority 100
  ## }
  ## ```
  let doc = parseKdlFile(path)
  result = @[]
  
  for node in doc:
    if node.name != "repo":
      continue
      
    let name = node.getArgString(0)
    
    # Defaults
    var config = RepoConfig(
      name: name,
      kind: Native,
      priority: 50
    )
    
    # Parse child nodes (KDL uses children for properties in this format)
    for child in node.children:
      case child.name:
        of "type":
          case child.getArgString(0):
            of "native": config.kind = Native
            of "git": config.kind = Git
            of "graft": config.kind = Graft
            else: raise newException(ValueError, "Unknown repo type: " & child.getArgString(0))
        of "url":
          config.url = child.getArgString(0)
        of "priority":
          config.priority = child.getArgInt(0).int
        of "key":
          config.key = child.getArgString(0)
        of "branch":
          config.branch = child.getArgString(0)
        of "token":
          config.token = child.getArgString(0)
        of "backend":
          case child.getArgString(0):
            of "nix": config.backend = Nix
            of "portage": config.backend = Portage
            of "pkgsrc": config.backend = Pkgsrc
            of "pacman": config.backend = Pacman
            of "apt": config.backend = Apt
            of "dnf": config.backend = Dnf
            of "mock": config.backend = Mock
            else: raise newException(ValueError, "Unknown graft backend: " & child.getArgString(0))
        else:
          discard # Ignore unknown properties for forward compatibility
          
    result.add(config)

proc loadRepoConfigs*(): seq[RepoConfig] =
  ## Load repository configurations from standard locations
  ## Priority: ~/.nip/repos.kdl > /etc/nip/repos.kdl
  
  var configs: seq[RepoConfig] = @[]
  
  # Try system config
  let systemPath = "/etc/nip/repos.kdl"
  if fileExists(systemPath):
    configs.add(parseRepoConfig(systemPath))
  
  # Try user config (overrides system)
  let userPath = getHomeDir() / ".nip" / "repos.kdl"
  if fileExists(userPath):
    configs.add(parseRepoConfig(userPath))
  
  result = configs
