import 'dart:convert';
import 'dart:io';

final _cacheKeyUnsafeChars = RegExp(r'[^a-zA-Z0-9]');


String sanitizeCacheKeyComponent(String value) =>
    value.replaceAll(_cacheKeyUnsafeChars, '_');


Future<T?> readJsonCacheFile<T>(
  File file,
  T Function(Map<String, dynamic>) fromJson,
) async {
  try {
    if (!await file.exists()) return null;
    final raw = await file.readAsString();
    if (raw.trim().isEmpty) return null;
    return fromJson(jsonDecode(raw) as Map<String, dynamic>);
  } catch (_) {
    return null;
  }
}

Future<void> writeJsonCacheFile(File file, Map<String, dynamic> json) async {
  if (!await file.parent.exists()) {
    await file.parent.create(recursive: true);
  }
  await file.writeAsString(
    const JsonEncoder.withIndent('  ').convert(json),
    flush: true,
  );
}
