import 'dart:typed_data';

// --- The Magic Conditional Import ---
// If dart:io is available, use the real scanner. Otherwise, use the stub.
import 'package:wolf_3d_data_types/wolf_3d_data_types.dart';

import 'io/discovery_stub.dart'
    if (dart.library.io) 'io/discovery_io.dart'
    as platform;
import 'wl_parser.dart';

class WolfensteinLoader {
  /// Scans a directory for Wolfenstein 3D data files and loads all available versions.
  ///
  /// NOTE: This will throw an [UnsupportedError] on Web platforms.
  static Future<Map<GameVersion, WolfensteinData>> discover({
    String? directoryPath,
    bool recursive = false,
  }) {
    return platform.discoverInDirectory(
      directoryPath: directoryPath,
      recursive: recursive,
    );
  }

  /// Parses WolfensteinData from raw ByteData.
  /// Throws an [ArgumentError] if any required file is null.
  static WolfensteinData loadFromBytes({
    required GameVersion version,
    required ByteData? vswap,
    required ByteData? mapHead,
    required ByteData? gameMaps,
    required ByteData? vgaDict,
    required ByteData? vgaHead,
    required ByteData? vgaGraph,
    required ByteData? audioHed,
    required ByteData? audioT,
  }) {
    // 1. Validation Check
    final Map<String, ByteData?> files = {
      'VSWAP': vswap,
      'MAPHEAD': mapHead,
      'GAMEMAPS': gameMaps,
      'VGADICT': vgaDict,
      'VGAHEAD': vgaHead,
      'VGAGRAPH': vgaGraph,
      'AUDIOHED': audioHed,
      'AUDIOT': audioT,
    };

    final missing = files.entries
        .where((e) => e.value == null)
        .map((e) => "${e.key}.${version.fileExtension}")
        .toList();

    if (missing.isNotEmpty) {
      throw ArgumentError(
        'Cannot load ${version.name}: Missing files: ${missing.join(", ")}',
      );
    }

    // 2. Pass-through to parser now that we are guaranteed non-null
    return WLParser.load(
      version: version,
      vswap: vswap!,
      mapHead: mapHead!,
      gameMaps: gameMaps!,
      vgaDict: vgaDict!,
      vgaHead: vgaHead!,
      vgaGraph: vgaGraph!,
      audioHed: audioHed!,
      audioT: audioT!,
    );
  }
}
