<?php
declare(strict_types=1);

function ensure_storage(string $dir): void {
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0775, true) && !is_dir($dir)) {
            throw new RuntimeException("Failed to create storage directory");
        }
    }
}

function random_basename(int $len = 24): string {
    return bin2hex(random_bytes(intval($len/2)));
}

function safe_ext(string $filename): string {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    return preg_replace('/[^a-z0-9]+/','', $ext);
}

function detect_mime(string $tmpFile): string {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    return $finfo->file($tmpFile) ?: 'application/octet-stream';
}
