export type PathPromptRequest = {
  title: string
  hint: string
  defaultValue: string
  folderName?: string
}

type PathPromptFn = (req: PathPromptRequest) => Promise<string | null>

let promptFn: PathPromptFn | null = null

export function registerPathPrompt(fn: PathPromptFn | null): void {
  promptFn = fn
}

export async function askDiskPath(req: PathPromptRequest): Promise<string | null> {
  if (promptFn) return promptFn(req)
  const v = window.prompt(`${req.title}\n\n${req.hint}`, req.defaultValue)
  return v?.trim() ? v.trim() : null
}

const ABS_ROOT_KEY = 'myreader-abs-root-map'

export function rememberedAbsRoot(folderName: string): string | undefined {
  try {
    const map = JSON.parse(localStorage.getItem(ABS_ROOT_KEY) || '{}') as Record<string, string>
    return map[folderName]
  } catch {
    return undefined
  }
}

export function rememberAbsRoot(folderName: string, absPath: string): void {
  try {
    const map = JSON.parse(localStorage.getItem(ABS_ROOT_KEY) || '{}') as Record<string, string>
    map[folderName] = absPath
    localStorage.setItem(ABS_ROOT_KEY, JSON.stringify(map))
  } catch {
    /* ignore */
  }
}
