#!/usr/bin/env php
<?php
if (empty($argv[1])) {
    echo 'You must provide a base branch to check this PR against.';
    echo "\n";
    exit(1);
}

// Get a changelist of files from Git for this PR.
$fileList = shell_exec('git diff --name-only --diff-filter=ACMR origin/' . $argv[1] . ' HEAD');
$files = array_filter(explode("\n", $fileList));

foreach ($files as &$file) {
    if (strpos($file, ' ') !== false) {
        $file = str_replace(' ', '\\ ', $file);
    }
}

// Run all changed files through the parallel-linter
$output = shell_exec('printf "%s\n" "' . implode('" "', $files) . '" | parallel-lint --no-colors --no-progress --stdin --json');
$output = json_decode($output, true);

if (!count($output["results"]["filesWithSyntaxError"])) {
    echo "\e[0;32mFound no issues with code quality.\e[0m";
    echo "\n";
    exit(0);
} else {
    $totalNumberOfIssues = count($output["results"]["filesWithSyntaxError"]);

    // Render report
    echo "\e[0;31mFound "
        . (($totalNumberOfIssues === 1)
            ? '1 issue'
            : $totalNumberOfIssues . ' issues')
        . " with code quality.\e[0m";
    echo "\n";

    $errors = $output["results"]["errors"];

    unset($file);
    foreach ($output["results"]["filesWithSyntaxError"] as $file) {
        echo "\n";
        echo "\e[1;37m" . str_replace('"', '', $file) . "\e[0m";
        echo "\n\n";

        $errors_in_file = array_filter($errors, fn ($elem) => $elem["file"] === $file);

        foreach ($errors_in_file as $error) {
            echo "\e[2m" . str_pad('  L' . $error['line'], 7) . " | \e[0m";
            echo "\e[0;31mERR:\e[0m  ";
            echo $error['message'];
            echo "\n";
        }
    }

    exit(1);
}
