// SPDX-FileCopyrightText: 2026 FocusFlow contributors
// SPDX-License-Identifier: AGPL-3.0-only

/// Runs the Export command for the Scheduler Export Json package.
library;

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';

/// Entry point for this executable Dart file.
/// It wires the local command, test, or application behavior needed by this repository without exposing additional public API.
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());
}

/// Top-level helper that performs the `_format` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
String? _format(List<String> arguments) {
  final wantsJson = arguments.contains('--json');
  final wantsCsv = arguments.contains('--csv');
  if (wantsJson == wantsCsv) {
    return null;
  }
  return wantsJson ? 'json' : 'csv';
}

/// Top-level helper that performs the `_option` operation for this file.
/// Keeping the helper private makes the surrounding flow easier to read while preventing unrelated libraries from depending on implementation detail.
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];
}
