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

function findAutoload(): string
{
    foreach (['/../../autoload.php', '/../vendor/autoload.php', '/vendor/autoload.php'] as $usableFilePath) {
        $fullUsableFilePath = __DIR__ . $usableFilePath;
        if (file_exists($fullUsableFilePath)) {
            return $fullUsableFilePath;
        }
    }

    fwrite(STDERR, 'You need to use composer to use this binary, learn more on https://getcomposer.org/');
    exit(1);
}

require findAutoload();

use Nati\BuilderGenerator\FileBuilderGenerator;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\SingleCommandApplication;
use Symfony\Component\Console\Style\SymfonyStyle;

$strategies = FileBuilderGenerator::strategies()->shortnames();

$generate = function (InputInterface $input, OutputInterface $output) {
    try {
        FileBuilderGenerator::create(new ConsoleLogger($output))
                            ->generateFrom(
                                $input->getArgument('filepath'),
                                $input->getOption('strategy'),
                                (bool)$input->getOption('faker')
                            );
    } catch (Throwable $e) {
        (new SymfonyStyle($input, $output))
            ->getErrorStyle()
            ->error('Error while generating builder, ' . $e->getMessage());
        exit(1);
    }
};

(new SingleCommandApplication())
    ->setName('generate-builder')
    ->setVersion('2.x')
    ->addArgument('filepath', InputArgument::REQUIRED, 'The filepath to the class you want to generate a builder on')
    ->addOption(
        'strategy',
        null,
        InputOption::VALUE_REQUIRED,
        sprintf(
            'Strategy used to build class among "%s" - will be automatically detected if none',
            implode('", "', $strategies)
        ),
        null,
        $strategies
    )
    ->addOption(
        'faker',
        null,
        InputOption::VALUE_NONE,
        'Use faker to initialize properties with more relevant random data',
        null
    )
    ->setCode($generate)
    ->run();
