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

requireAutoloader();
ini_set('display_errors', 'stderr');

$options = array();
$options_raw = getopt('', array(
    'use-asterisk',
    'use-underscore',
    'enable-strong',
    'enable-em',
));

foreach ($options_raw as $option => $value) {
    $options[str_replace('-', '_', $option)] = $value;
}

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

    if (str_starts_with($arg, '-')) {
        switch ($arg) {
            case '-h':
            case '--help':
                echo getHelpText();
                exit(0);
            default:
                $option = explode('=', $arg, 2)[0];
                if (!preg_match('/^--[^-]/', $option)
                    || !array_key_exists(ltrim($option, '-'), $options_raw)) {
                    fail('Unknown option: ' . $arg);
                }
        }
    } else {
        $src = $arg;
    }
}

if (isset($src)) {
    if (!file_exists($src)) {
        fail('File not found: ' . $src);
    }

    $markdown = file_get_contents($src);
} else {
    $stdin = fopen('php://stdin', 'rb');

    if (stream_set_blocking($stdin, false)) {
        $markdown = stream_get_contents($stdin);
    }

    fclose($stdin);
    if (empty($markdown)) {
        fail(getHelpText());
    }
}

$converter = new \Everyday\CommonQuill\QuillConverter($options);
echo json_encode($converter->convertToQuill($markdown));

/**
 * Get help and usage info
 *
 * @return string
 */
function getHelpText(): string
{
    if (stripos(PHP_OS_FAMILY, 'WIN') === 0) {
        return <<<WINDOWSHELP
CommonQuill - Markdown to Quill conversions done right

Usage: commonquill [OPTIONS] [FILE]
    -h, --help    Shows help and usage information
    
    (Reading data from STDIN is not currently supported on Windows)
    
Examples:
    Converting a file named document.md:
        commonquill document.md
        
    Converting a file and saving its output:
        commonquill document.md > output.json
        
Full documentation can be found at https://github.com/Everyday-AS/common-quill
WINDOWSHELP;
    }
    return <<<HELP
CommonQuill - Markdown to Quill conversions done right

Usage: commonquill [OPTIONS] [FILE]

    -h, --help    Shows help and usage information
    
    If no file is given, input will be read from STDIN
    
Examples:

    Converting a file named document.md:
        commonquill document.md
        
    Converting a file and saving its output:
        commonquill document.md > output.json
        
    Converting from STDIN:
        echo -e '# Hello World!' | commonquill
        
    Converting from STDIN and saving the output:
        echo -e '# Hello World!' | commonquill > output.json
        
Full documentation can be found at https://github.com/Everyday-AS/common-quill
HELP;
}

/**
 * @param string $message Error message
 */
function fail($message)
{
    fwrite(STDERR, $message . "\n");

    exit(1);
}

function requireAutoloader()
{
    $autoloadPaths = [
        // Local package usage
        __DIR__ . '/../vendor/autoload.php',
        // Package was included as a library
        __DIR__ . '/../../../autoload.php',
    ];

    foreach ($autoloadPaths as $path) {
        if (file_exists($path)) {
            require_once $path;
            break;
        }
    }
}