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

declare(strict_types=1);

if (file_exists(__DIR__.'/../vendor/autoload.php')) {
    require __DIR__.'/../vendor/autoload.php';
} elseif (file_exists(__DIR__.'/../../../autoload.php')) {
    require __DIR__.'/../../../autoload.php';
} else {
    echo 'Run "composer install" in order to install the necessary dependencies.'.PHP_EOL;
    exit(1);
}

ini_set('xdebug.max_nesting_level', '3000');

use Cnimmo\ListDeps\DependencyFinder;

$opts = getopt('p:r:', ['paths:', 'root:', 'input-separator:', 'output-separator:', 'allow-missing', 'ignore:']);

$pathOptionValue = $opts['p'] ?? $opts['paths'] ?? null;
$inputSeparator = $opts['input-separator'] ?? ',';
$outputSeparator = $opts['output-separator'] ?? PHP_EOL;
$rootPath = $opts['r'] ?? $opts['root'] ?? null;
$allowMissing = isset($opts['allow-missing']) ? true : false;
$ignorePaths = isset($opts['ignore']) ? explode(',', $opts['ignore']) : [];

if (!$pathOptionValue) {
    echo 'No paths specified.'.PHP_EOL;
    exit(1);
}

$paths = explode($inputSeparator, $pathOptionValue);
$validatedPaths = array_map('realpath', $paths);

$invalidPathIndex = array_search(false, $validatedPaths, true);

if ($invalidPathIndex !== false) {
    echo 'Encountered non-existent path: ' . $paths[$invalidPathIndex] . PHP_EOL;
    exit(1);
}

$finder = new DependencyFinder($rootPath, $ignorePaths, $validatedPaths, !$allowMissing);

$dependentFilesByPath = $finder->findDependencies();

$flatDependentFiles = [];
array_walk_recursive($dependentFilesByPath, function($a) use (&$flatDependentFiles) { $flatDependentFiles[] = $a; });

echo implode($outputSeparator, $flatDependentFiles);