<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use Aen\MarkdownLab\Converter;
$input = $argv[1] ?? '';
$output = $argv[2] ?? '';
$profile = $argv[3] ?? 'docs';
if (!is_dir($input) || $output === '') {
    fwrite(STDERR, "Usage: php bin/batch.php INPUT_DIRECTORY OUTPUT_DIRECTORY [profile]\n"); exit(2);
}
if (!in_array($profile, Converter::PROFILES, true)) { fwrite(STDERR, "Unknown profile\n"); exit(2); }
if (!is_dir($output) && !mkdir($output, 0775, true) && !is_dir($output)) { exit(2); }
$files = glob(rtrim($input, '/\\') . DIRECTORY_SEPARATOR . '*.md') ?: [];
sort($files);
$errors = 0;
foreach ($files as $file) {
    try {
        if (is_link($file) || filesize($file) > Converter::MAX_INPUT) { throw new LengthException('File exceeds limit or is a symlink'); }
        $text = file_get_contents($file);
        if ($text === false) { throw new RuntimeException('Cannot read input'); }
        $result = (new Converter())->convert($text, $profile);
        $target = rtrim($output, '/\\') . DIRECTORY_SEPARATOR . pathinfo($file, PATHINFO_FILENAME) . '.html';
        if (file_exists($target)) { throw new RuntimeException('Output exists; choose an empty directory'); }
        if (file_put_contents($target, $result['html'], LOCK_EX) === false) { throw new RuntimeException('Cannot write output'); }
        echo json_encode(['file' => basename($file), 'output' => basename($target), 'bytes' => $result['outputBytes']], JSON_UNESCAPED_UNICODE) . PHP_EOL;
    } catch (Throwable $e) { $errors++; fwrite(STDERR, basename($file) . ': ' . $e->getMessage() . PHP_EOL); }
}
exit($errors > 0 ? 1 : 0);
