#!/usr/bin/env php
<?php
declare(strict_types=1);

namespace App;

use Bigwhoop\PhpClassComponentsExtractor\Extractor;
use Bigwhoop\PhpClassComponentsExtractor\File;
use Bigwhoop\PhpClassComponentsExtractor\Formatting\Formatter;
use Bigwhoop\PhpClassComponentsExtractor\Formatting\GraphvizFormatter;
use Bigwhoop\PhpClassComponentsExtractor\Formatting\JsonFormatter;
use Bigwhoop\PhpClassComponentsExtractor\Formatting\TextFormatter;
use Bigwhoop\PhpClassComponentsExtractor\Source;
use Bigwhoop\PhpClassComponentsExtractor\StdInput;

$autoloadFilePaths = [
    __DIR__ . '/../vendor/autoload.php',
    __DIR__ . '/../../../autoload.php',
];

$autoloadFilePath = false;
foreach ($autoloadFilePaths as $path) {
    if (file_exists($path)) {
        $autoloadFilePath = $path;
        break;
    }
}

if (!$autoloadFilePath) {
    echo "Failed to locate composer's autoload.php.\n";
    exit(1);
}

require $autoloadFilePath;

$help = <<<HELP
Usage: ./class-components-extractor [options] input

Arguments:
  input                 Path to a PHP file or - to use STDIN

Options:
  -h --help             Shows this help
  -f --format <format>  Output format to use. One of the followwing:
                          json      JSON (default)
                          text      Human-readable representation
                          graphviz  Graphviz's graph description language

Examples:
  ./class-components-extractor file.php
  ./class-components-extractor file.php > components.json
  ./class-components-extractor --format text file.php
  ./class-components-extractor --format graphviz file.php | dot -Tpng -o diagram.png
  cat file.php | ./class-components-extractor --graphviz - | dot -Tpng -o diagram.png


HELP;

$restIndex = null;
$options = getopt('hf:', ['help', 'format:'], $restIndex);
$arguments = array_slice($argv, $restIndex);

if (!isset($arguments[0]) || isset($options['h']) || isset($options['help'])) {
    exit($help);
}

/** @var Formatter $formatter */
$formatter = match ($options['format'] ?? $options['f'] ?? 'json') {
    'text' => new TextFormatter(),
    'graphviz' => new GraphVizformatter(),
    default => new JsonFormatter(),
};

/** @var Source $source */
$source = $arguments[0] === '-' ? new StdInput() : new File($arguments[0]);

$extractor = new Extractor();
$graph = $extractor->extract($source);
$output = $formatter->format($graph);

echo $output;
