/**
 * Trim and remove one pair of surrounding ASCII quotes from a Template ID argument.
 * Shells usually strip quotes before argv; this still helps when values are copy-pasted with
 * quotes or come from tools that pass literal quote characters.
 *
 * @param {string | undefined | null} value
 * @returns {string | undefined | null}
 */
function normalizeTemplateIdArg(value) {
  if (value == null) {
    return value
  }
  let s = String(value).trim()
  if (s.length >= 2) {
    const a = s[0]
    const b = s[s.length - 1]
    if ((a === '"' && b === '"') || (a === "'" && b === "'")) {
      s = s.slice(1, -1).trim()
    }
  }
  return s
}

/** @deprecated use normalizeTemplateIdArg */
const normalizeCidArg = normalizeTemplateIdArg

/**
 * Prefer --template-id over positional; hidden --cid is an alias of --template-id.
 *
 * @param {{ templateId?: string, cid?: string }} options
 * @param {string | undefined} positional
 * @returns {string | undefined | null}
 */
function resolveLibraryTemplateId(options, positional) {
  const fromOpt = options.templateId != null && String(options.templateId).trim() !== ''
    ? options.templateId
    : options.cid != null && String(options.cid).trim() !== ''
      ? options.cid
      : null
  const hasPos = positional != null && String(positional).trim() !== ''
  const raw = fromOpt != null ? fromOpt : hasPos ? positional : null
  return raw == null ? raw : normalizeTemplateIdArg(raw)
}

/** @deprecated use resolveLibraryTemplateId */
const resolveLibraryCid = resolveLibraryTemplateId

module.exports = {
  normalizeTemplateIdArg,
  normalizeCidArg,
  resolveLibraryTemplateId,
  resolveLibraryCid,
}
