#!/usr/bin/env php
<?php

/**
 * This file is part of matchory/coding-style, a Matchory project.
 *
 * @copyright © 2026 Matchory GmbH
 * @license MIT
 */

declare(strict_types=1);

use Matchory\CodingStyle\Console\Reporter;
use Matchory\CodingStyle\Console\Runner;

/**
 * Thin dispatcher. The logic lives in `php/src/Console/` so that PHPStan analyses it.
 */
$packageRoot = dirname(__DIR__, 2);

foreach ([$packageRoot . '/vendor/autoload.php', $packageRoot . '/../../autoload.php'] as $autoload) {
    if (is_file($autoload)) {
        require $autoload;

        break;
    }
}

$projectRoot = getcwd();

if ($projectRoot === false) {
    fwrite(STDERR, 'Cannot determine the current working directory' . PHP_EOL);

    exit(1);
}

$arguments = array_slice($argv, 1);
$command = $arguments[0] ?? 'help';

$usage = <<<'USAGE'
    matchory-coding-style <command> [options]

      sync [--check]      Write the configuration files that cannot be read out of vendor/.
                          Currently: .editorconfig
                          --check   Exit non-zero if a file is out of date, without writing.

      verify [--strict]   Check that this project is actually wired to the shared configuration:
                          the Pint preset, PHPStan auto-discovery, the complexity thresholds that
                          cannot be shipped from a package, and the Rector preset.
                          --strict  Treat warnings as failures.

    USAGE;

if ($command === 'help' || $command === '--help' || $command === '-h') {
    echo $usage . PHP_EOL;

    exit(0);
}

if ($command !== 'sync' && $command !== 'verify') {
    fwrite(STDERR, sprintf('Unknown command %s' . PHP_EOL . PHP_EOL, var_export($command, true)));
    fwrite(STDERR, $usage . PHP_EOL);

    exit(1);
}

$runner = new Runner($packageRoot, $projectRoot, new Reporter());

exit($command === 'sync'
    ? $runner->sync(in_array('--check', $arguments, true))
    : $runner->verify(in_array('--strict', $arguments, true)));
