import { app } from 'electron'
import { join } from 'path'
import { mkdirSync } from 'fs'

/**
 * Filesystem path helpers for the main process. Kept separate from settings.ts
 * (the electron-store persistence layer) so path derivation and the settings
 * store don't share a module — they have different concerns and dependencies (L69).
 * All resolve app paths, so callers must run post-`app.ready`.
 */

/** Fixed path for the --download-archive file; not user-configurable. */
export function getDownloadArchivePath(): string {
  return join(app.getPath('userData'), 'download-archive.txt')
}

/**
 * The default per-kind download destination: video → Documents\Video,
 * audio → Documents\Audio. Used when the user hasn't set an explicit output
 * folder (Settings → Download folder), so downloads are sorted by type.
 */
export function getDefaultMediaDir(kind: 'video' | 'audio'): string {
  return join(app.getPath('documents'), kind === 'audio' ? 'Audio' : 'Video')
}

/**
 * Create the Documents\Video and Documents\Audio folders up front (called once
 * at startup) so they exist the moment the app opens, not just after the first
 * download. Best-effort: yt-dlp also creates the output dir at download time, so
 * a failure here (read-only Documents, redirected folder) is non-fatal.
 */
export function ensureMediaDirs(): void {
  for (const kind of ['video', 'audio'] as const) {
    try {
      mkdirSync(getDefaultMediaDir(kind), { recursive: true })
    } catch {
      /* non-fatal — the download path will be created on demand instead */
    }
  }
}
