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

import 'package:crypto/crypto.dart';

/// Builds content/manifest.json from the season packs under content/.
/// Usage: dart run tool/make_manifest.dart
void main() {
  final contentDir = Directory('content');
  final seasons = <Map<String, dynamic>>[];

  final dirs = contentDir
      .listSync()
      .whereType<Directory>()
      .where((d) => File('${d.path}/pack.json').existsSync())
      .toList()
    ..sort((a, b) => a.path.compareTo(b.path));

  for (final dir in dirs) {
    final file = File('${dir.path}/pack.json');
    final bytes = file.readAsBytesSync();
    final pack = jsonDecode(utf8.decode(bytes)) as Map<String, dynamic>;
    seasons.add({
      'seasonId': pack['seasonId'],
      'version': pack['version'],
      'packUrl': 'seasons/${pack['seasonId']}/pack.json',
      'sha256': sha256.convert(bytes).toString(),
    });
  }

  final manifest = {
    'schemaVersion': 1,
    'minAppBuild': 1,
    'current': seasons.isEmpty ? '' : seasons.last['seasonId'],
    'seasons': seasons,
  };

  File('content/manifest.json').writeAsStringSync(
      '${const JsonEncoder.withIndent("  ").convert(manifest)}\n');
  stdout.writeln('manifest.json written with ${seasons.length} season(s).');
}
