library;

import 'dart:io';
import 'dart:typed_data';

import 'package:wolf_3d_dart/wolf_3d_data_types.dart';
import 'package:wolf_3d_dart/wolf_3d_engine.dart';

/// CLI host adapter for slot-based game save persistence.
///
/// Files are stored under `~/.wolf3d_saves` by default and named
/// `SAVEGAM{slot}.{ext}` where `{ext}` follows the active game version.
class CliSaveGamePersistence implements SaveGamePersistence {
  CliSaveGamePersistence({String? directoryPath})
    : _directoryPath = directoryPath ?? '${_platformConfigDir()}/saves';

  final String _directoryPath;

  @override
  Future<Uint8List?> load({
    required int slot,
    required GameVersion version,
  }) async {
    try {
      final File file = File(_slotPath(slot, version));
      if (!file.existsSync()) {
        return null;
      }
      return await file.readAsBytes();
    } catch (_) {
      return null;
    }
  }

  @override
  Future<bool> exists({
    required int slot,
    required GameVersion version,
  }) async {
    try {
      final File file = File(_slotPath(slot, version));
      return file.existsSync() && file.lengthSync() > 0;
    } catch (_) {
      return false;
    }
  }

  @override
  Future<void> save({
    required int slot,
    required GameVersion version,
    required Uint8List bytes,
  }) async {
    final Directory dir = Directory(_directoryPath);
    if (!dir.existsSync()) {
      await dir.create(recursive: true);
    }

    await File(_slotPath(slot, version)).writeAsBytes(bytes, flush: true);
  }

  String _slotPath(int slot, GameVersion version) {
    final String normalizedSlot = slot.clamp(0, 9).toString();
    return '$_directoryPath/SAVEGAM$normalizedSlot.${version.fileExtension}';
  }
}

String _platformConfigDir() {
  if (Platform.isLinux) {
    final String xdg = Platform.environment['XDG_CONFIG_HOME'] ?? '';
    final String home = Platform.environment['HOME'] ?? '.';
    return xdg.isNotEmpty ? '$xdg/wolf3d' : '$home/.config/wolf3d';
  }
  if (Platform.isMacOS) {
    final String home = Platform.environment['HOME'] ?? '.';
    return '$home/Library/Application Support/wolf3d';
  }
  if (Platform.isWindows) {
    final String appData = Platform.environment['APPDATA'] ?? '.';
    return '$appData/wolf3d';
  }
  final String home = Platform.environment['HOME'] ?? '.';
  return '$home/.config/wolf3d';
}
