import 'dart:io';

import 'package:args/args.dart';

extension StringUtils on String {
  String capitalize() {
    return substring(0, 1).toUpperCase() + substring(1);
  }
}

({bool success, File? file}) getTomlFromArgs(List<String> args) {
  const String templateResumePath = 'assets/resume_template.toml';
  final parser = ArgParser();
  parser.addOption('input', abbr: 'i', defaultsTo: 'examples/resume.toml', help: 'Input file path');
  parser.addFlag('help', abbr: 'h', help: 'Prints help info');
  final parsedResults = parser.parse(args);

  if (parsedResults.flag("help")) {
    stdout.writeln(parser.usage);
    return (success: false, file: null);
  }

  final inputFilePath = parsedResults.option('input');
  if (inputFilePath == null) {
    throw Exception('No valid input provided.');
  }
  final inputFile = File(inputFilePath);
  if (!inputFile.existsSync()) {
    stdout.writeln(
      'Provided `$inputFilePath`, but it does not exist. Would you like to start with the template?\n\t($templateResumePath copied to $inputFilePath)\n(y/n): ',
    );
    final ans = stdin.readLineSync()?.toLowerCase() ?? 'n';
    if (ans == 'y') {
      stdout.writeln('Copying over...');
      File(templateResumePath).copySync(inputFilePath);
      final newFile = File(inputFilePath);
      if (!newFile.existsSync()) {
        return (success: false, file: null);
      }
      return (success: true, file: newFile);
    } else {
      stdout.writeln('Got it. Try again with an actual existing document. You got this 👍');
      return (success: false, file: null);
    }
  } else {
    return (success: true, file: inputFile);
  }
}