import 'dart:io';

import 'package:scheduler_core/scheduler_core.dart' as core;
import 'package:scheduler_export/export.dart';
import 'package:scheduler_export_json/export_json.dart';
import 'package:scheduler_persistence_memory/persistence_memory.dart';

Future<void> main(List<String> arguments) async {
  final format = _format(arguments);
  if (format == null) {
    stderr.writeln('Usage: dart run bin/export.dart --json|--csv');
    exitCode = 64;
    return;
  }

  final output = StringBuffer();
  final ownerId =
      core.OwnerId(_option(arguments, '--owner') ?? 'default-owner');
  await ExportController(
    taskRepository: InMemoryTaskRepository(),
    writerRegistry: readableExportWriterRegistry(),
  ).exportTasksToSink(
    context: ExportContext(
      ownerId: ownerId,
      timezone: _option(arguments, '--timezone') ?? 'UTC',
      version: 1,
    ),
    format: format,
    sink: output,
  );
  stdout.write(output.toString());
}

String? _format(List<String> arguments) {
  final wantsJson = arguments.contains('--json');
  final wantsCsv = arguments.contains('--csv');
  if (wantsJson == wantsCsv) {
    return null;
  }
  return wantsJson ? 'json' : 'csv';
}

String? _option(List<String> arguments, String name) {
  final index = arguments.indexOf(name);
  if (index == -1 || index + 1 >= arguments.length) {
    return null;
  }
  return arguments[index + 1];
}
