import type { Stats } from 'node:fs'
import path from 'node:path'

type RuntimeGlobals = typeof globalThis & {
  process?: NodeJS.Process
}

function runtimeGlobals(): RuntimeGlobals {
  return globalThis as RuntimeGlobals
}

export function sanitizeExternalFilePath(rawPath: string): string | null {
  const target = String(rawPath ?? '').trim()
  if (!target) return null
  if (target.includes('\0')) return null
  if (/[\r\n]/.test(target)) return null
  if (/[;&|`]/.test(target)) return null
  return target
}

export async function openPathExternally(rawPath: string): Promise<boolean> {
  const target = sanitizeExternalFilePath(rawPath)
  if (!target) return false

  try {
    const [{ spawn }, { stat }] = await Promise.all([
      import('node:child_process'),
      import('node:fs/promises'),
    ])
    const platform = String(runtimeGlobals().process?.platform ?? '')
    const info: Stats | null = await stat(target).catch(() => null)
    const exists = Boolean(info)
    const isDir = info?.isDirectory() ?? false
    const dir = path.dirname(target)

    if (platform === 'darwin') {
      if (exists && !isDir)
        spawn('open', ['-R', target], {
          shell: false,
          detached: true,
          stdio: 'ignore',
        }).unref()
      else
        spawn('open', [exists ? target : dir], {
          shell: false,
          detached: true,
          stdio: 'ignore',
        }).unref()
      return true
    }

    if (platform === 'win32') {
      if (exists && !isDir)
        spawn('explorer.exe', [`/select,${target}`], {
          shell: false,
          detached: true,
          stdio: 'ignore',
        }).unref()
      else
        spawn('explorer.exe', [exists ? target : dir], {
          shell: false,
          detached: true,
          stdio: 'ignore',
        }).unref()
      return true
    }

    spawn('xdg-open', [exists && isDir ? target : dir], {
      shell: false,
      detached: true,
      stdio: 'ignore',
    }).unref()
    return true
  } catch {
    return false
  }
}

export async function openUrlExternally(rawUrl: string): Promise<boolean> {
  const url = String(rawUrl ?? '').trim()
  if (!/^https?:\/\//i.test(url)) return false
  if (url.includes('\0')) return false
  if (/[\r\n]/.test(url)) return false

  try {
    const { spawn } = await import('node:child_process')
    const platform = String(runtimeGlobals().process?.platform ?? '')
    const cmd =
      platform === 'darwin'
        ? 'open'
        : platform === 'win32'
          ? 'explorer.exe'
          : 'xdg-open'
    spawn(cmd, [url], { shell: false, detached: true, stdio: 'ignore' }).unref()
    return true
  } catch {
    return false
  }
}
