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

# Autoload files
foreach ([__DIR__ . '/../../../autoload.php', __DIR__ . '/../vendor/autoload.php'] as $file) {
    if (file_exists($file)) {
        require $file;
        break;
    }
}

function showHelp(int $exit) {
    fwrite(STDOUT, <<<OUTPUT
Usage: response2schema [inputfile] [outputfile]

Response2Schema will accept input in application/json; this is the typical response you may receive from an API.
It will infer the format you want the OpenAPI spec to be generated in from the output file path.

Response2Schema cannot guess beyond basic types; it cannot infer oneOf, enums, minimum/maximum numbers, and so on.
This tool is meant to bootstrap your OpenAPI specification, nothing more. 

Valid formats: yaml, json

Example:
    response2schema response.json openapi.yaml


OUTPUT
    );
    exit($exit);
}

function error(string $message) {
    fwrite(STDERR, "\e[31m" . $message . "\e[0m" . PHP_EOL);
    showHelp(1);
}

function success(string $message) {
    fwrite(STDOUT, "\e[32m" . $message . "\e[0m" . PHP_EOL);
}

$inputPath = null;
$outputPath = null;

if (count($argv) < 3) {
    error("Missing input and output file arguments!");
}

foreach($argv as $k => $arg) {
    if ($k === 0) {
        continue;
    }

    // Input
    if ($k === 1) {
        if (!is_string($arg)) {
            error("Please specify an input file.");
        }
        if ($arg === 'help' || $arg === '--help') {
            showHelp(0);
        }
        $inputPath = $arg;
    }

    // Output
    if ($k === 2) {
        if (!is_string($arg)) {
            error("Please specify an output file.");
        }
        $outputPath = $arg;
    }
}

if ($inputPath === null || $outputPath === null) {
    error("Missing input and output file arguments!");
}

try {
    \DSuurlant\Response2Schema\Response2Schema::generate($inputPath, $outputPath);
    success("Generation successful!");
} catch (DomainException $exception) {
    error($exception->getMessage());
}

exit(0);
