## User Override Management for NexusForge
## Allows users to define local package overrides that take precedence over all repos

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

proc loadUserOverrides*(overrideDir: string): Table[string, Fragment] =
  ## Load user-defined package overrides from a directory
  ## Each .kdl file in the directory defines a package override
  ## 
  ## Example override file (nginx.kdl):
  ## ```kdl
  ## package "nginx" {
  ##     version "1.25.0-custom"
  ##     stream "dev"
  ##     source {
  ##         hash "user-override-hash-abc123"
  ##         url "file:///home/user/nginx-build"
  ##     }
  ## }
  ## ```
  var overrides = initTable[string, Fragment]()
  
  if not dirExists(overrideDir):
    return overrides
  
  for file in walkFiles(overrideDir / "*.kdl"):
    try:
      let doc = parseKdlFile(file)
      
      for node in doc:
        if node.name != "package":
          continue
        
        let packageName = node.getArgString(0)
        var fragment = Fragment()
        
        # Parse package metadata
        for child in node.children:
          case child.name:
            of "version":
              fragment.id.version = child.getArgString(0)
            of "stream":
              let streamStr = child.getArgString(0)
              fragment.id.stream = case streamStr:
                of "stable": Stable
                of "testing": Testing
                of "dev": Dev
                of "lts": LTS
                else: Custom
            of "source":
              for sourceChild in child.children:
                case sourceChild.name:
                  of "hash":
                    fragment.source.hash = sourceChild.getArgString(0)
                  of "url":
                    fragment.source.url = sourceChild.getArgString(0)
                  of "method":
                    let methodStr = sourceChild.getArgString(0)
                    fragment.source.sourceMethod = case methodStr:
                      of "git": Git
                      of "http": Http
                      of "local": Local
                      of "grafted": Grafted
                      else: Local
                  else:
                    discard
            else:
              discard
        
        fragment.id.name = packageName
        overrides[packageName] = fragment
    except:
      # Skip invalid override files
      discard
  
  return overrides

proc getUserOverrideDir*(): string =
  ## Get the standard user override directory
  ## Default: ~/.nip/overrides/
  return getHomeDir() / ".nip" / "overrides"

proc loadStandardUserOverrides*(): Table[string, Fragment] =
  ## Load user overrides from the standard location
  return loadUserOverrides(getUserOverrideDir())
