// ignore_for_file: avoid_print

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

const inputPath = 'assets/l10n/en.json';
const outputPath = 'lib/src/generated/i18n.dart';

void main() {
  try {
    generateI18n();
  } catch (e) {
    print('Error generating I18n: $e');
    exit(1);
  }
}

void generateI18n() {
  // Ensure input file exists
  final inputFile = File(inputPath);
  if (!inputFile.existsSync()) {
    throw 'Input file not found: $inputPath';
  }

  // Create output directory if it doesn't exist
  final outputDir = Directory(outputPath.substring(0, outputPath.lastIndexOf('/')));
  if (!outputDir.existsSync()) {
    outputDir.createSync(recursive: true);
  }

  // Read and parse JSON
  final jsonString = inputFile.readAsStringSync();
  final jsonMap = json.decode(jsonString) as Map<String, dynamic>;

  // Generate Dart class
  final buffer = StringBuffer();
  buffer.writeln('// Generated code - do not modify by hand');
  buffer.writeln();
  buffer.writeln('class I18n {');
  buffer.writeln('  const I18n._();');
  buffer.writeln();

  // Process JSON and write parent keys
  final parentKeys = jsonMap.keys.toList()..sort();
  for (final key in parentKeys) {
    final keyName = key[0].toLowerCase() + key.substring(1);

    buffer.writeln("  static const String $keyName = '$key';");
  }

  buffer.writeln('}');

  // Write to output file
  final outputFile = File(outputPath);
  outputFile.writeAsStringSync(buffer.toString());

  print('Successfully generated I18n class at: $outputPath');
}
