import 'dart:io';
import 'package:yaml/yaml.dart';
import 'package:yaml_edit/yaml_edit.dart';
import 'package:args/args.dart';

void main(List<String> arguments) {
  final parser = ArgParser()
    ..addOption('input',
        abbr: 'i', defaultsTo: '.melos', help: 'Input directory for YAML files')
    ..addOption('output',
        abbr: 'o', defaultsTo: 'melos.yaml', help: 'Output file path');

  final results = parser.parse(arguments);
  final inputDir = results['input'];
  final outputFile = results['output'];

  try {
    final baseContent = File('$inputDir/base.yaml').readAsStringSync();

    final scriptFiles = Directory(inputDir)
        .listSync()
        .where((file) =>
            file.path.endsWith('.yaml') && !file.path.endsWith('base.yaml'))
        .map((file) => file.path.split('/').last)
        .toList();

    final combinedScripts = <String, dynamic>{};

    for (final file in scriptFiles) {
      print('Processing $file');
      final content = File('$inputDir/$file').readAsStringSync();
      final yaml = loadYaml(content);
      if (yaml == null ||
          yaml['scripts'] == null ||
          yaml['scripts']['_'] == null) {
        print(
            'Warning: $file does not contain expected script structure. Skipping.');
        continue;
      }
      combinedScripts.addAll(Map<String, dynamic>.from(yaml['scripts']['_']));
    }

    // Format multi-line commands
    combinedScripts.forEach((key, value) {
      if (value is Map<String, dynamic> &&
          value['run'] is String &&
          value['run'].contains('\n')) {
        value['run'] =
            '|\n      ${value['run'].split('\n').map((line) => line.trim()).join('\n      ')}';
      }
    });

    final outputYamlEditor = YamlEditor(baseContent);
    outputYamlEditor.update(['scripts'], combinedScripts);

    // Format the YAML content
    final formattedYaml = outputYamlEditor.toString().split('\n').map((line) {
      if (line.trim().startsWith('- ')) {
        return line;
      }
      return line.trimRight();
    }).join('\n');

    // Add comments at the top of the file
    final outputContent = '''
# This file is part of the Protevus Platform.
#
# (C) Protevus <developers@protevus.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.

# THIS FILE IS AUTOGENERATED BY MELOS. DO NOT EDIT THIS FILE DIRECTLY.
# EDIT THE CORRESPONDING YAML FILES INSTEAD.

$formattedYaml
''';

    File(outputFile).writeAsStringSync(outputContent);
    print('Combined Melos configuration written to $outputFile');
  } catch (e, stackTrace) {
    print('Error: $e');
    print('Stack trace: $stackTrace');
    exit(1);
  }
}