// cell patch <module> - Create a patch for a module

var io = use('io')
var shop = use('shop')

if (args.length < 1) {
  log.console("Usage: cell patch <module>")
  log.console("Example: cell patch jj_mod")
  log.console("")
  log.console("This creates a patch file in .cell/patches/ that will be")
  log.console("applied when building the module.")
  $_.stop()
  return
}

var module_name = args[0]

if (!io.exists('.cell/shop.toml')) {
  log.error("No shop.toml found. Run 'cell init' first.")
  $_.stop()
  return
}

var config = shop.load_config()
if (!config || !config.dependencies || !config.dependencies[module_name]) {
  log.error("Module '" + module_name + "' not found in dependencies")
  $_.stop()
  return
}

// Ensure patches directory exists
if (!io.exists('.cell/patches')) {
  io.mkdir('.cell/patches')
}

var patch_file = '.cell/patches/' + module_name + '-fix.patch'

if (io.exists(patch_file)) {
  log.console("Patch already exists: " + patch_file)
  log.console("Edit it directly or delete it to create a new one.")
  $_.stop()
  return
}

// Create patch template
var patch_template = `# Patch for ${module_name}
# 
# To create a patch:
# 1. Make a copy of the module: cp -r .cell/modules/${module_name}@* /tmp/${module_name}-orig
# 2. Edit files in .cell/modules/${module_name}@*
# 3. Generate patch: diff -ruN /tmp/${module_name}-orig .cell/modules/${module_name}@* > ${patch_file}
# 
# This patch will be automatically applied during 'cell build'
`

io.slurpwrite(patch_file, patch_template)

// Add to shop.toml
if (!config.patches) {
  config.patches = {}
}
config.patches[module_name] = patch_file
shop.save_config(config)

log.console("Created patch skeleton: " + patch_file)
log.console("Follow the instructions in the file to create your patch.")
log.console("The patch will be applied automatically during 'cell build'.")

$_.stop()