import 'dart:io';

/// 非法文件名字符（路径分隔符等）。
final _invalidNameChars = RegExp(r'[/\\:*?"<>|]');

const _maxBaseNameLength = 120;

/// 清洗小程序复制的文件名基底（不含扩展名）。
String? sanitizeRecordingBaseName(String raw) {
  var name = raw.replaceAll(_invalidNameChars, '_').trim();
  if (name.isEmpty) return null;
  if (name.length > _maxBaseNameLength) {
    name = name.substring(0, _maxBaseNameLength);
  }
  return name;
}

/// 解析录制展示名：优先剪切板 filename，否则 REC_时间戳。
String resolveRecordingDisplayName(String? clipboardFilename) {
  final sanitized = clipboardFilename == null
      ? null
      : sanitizeRecordingBaseName(clipboardFilename);
  if (sanitized != null) return sanitized;
  final now = DateTime.now();
  final stamp =
      '${now.year}'
      '${now.month.toString().padLeft(2, '0')}'
      '${now.day.toString().padLeft(2, '0')}_'
      '${now.hour.toString().padLeft(2, '0')}'
      '${now.minute.toString().padLeft(2, '0')}'
      '${now.second.toString().padLeft(2, '0')}';
  return 'REC_$stamp';
}

/// 为展示名补全视频扩展名（已有 .mp4/.mov 则保留）。
String withVideoExtension(String baseName, {bool? isIOS}) {
  final ios = isIOS ?? Platform.isIOS;
  final ext = ios ? '.mov' : '.mp4';
  final lower = baseName.toLowerCase();
  if (lower.endsWith('.mp4') || lower.endsWith('.mov')) {
    return baseName;
  }
  return '$baseName$ext';
}

/// 传给原生的完整文件名（含扩展名）。
String recordingFileNameForPlatform(
  String? clipboardFilename, {
  bool? isIOS,
}) {
  final base = resolveRecordingDisplayName(clipboardFilename);
  return withVideoExtension(base, isIOS: isIOS);
}
