#!/usr/bin/env php
<?php
namespace Misuzu;

use Index\Http\{HttpRequest,HttpUri};
use Index\Http\Streams\NullStream;

require_once __DIR__ . '/../misuzu.php';

$hostName = null;
$tplArgs = [];
$pathIndex = 1;

// really bad getopt replacement that supports args with the same name
$nextIs = null;
for($i = 1; $i < $argc; ++$i) {
    $arg = $argv[$i];

handleValue:
    if($nextIs !== null) {
        if($nextIs === 'host') {
            if($hostName !== null)
                die(sprintf('Failed to parse arguments: a hostname was already specified.%s', PHP_EOL));

            $hostName = $arg;
            $nextIs = null;
            continue;
        }

        if($nextIs === 'var') {
            $equals = strpos($arg, '=');
            if($equals === false || $equals < 1)
                die(sprintf('Failed to parse arguments: variables must have names, name=value.%s', PHP_EOL));

            [$name, $value] = explode('=', $arg);
            $tplArgs[$name] = $value;
            $nextIs = null;
            continue;
        }

        die(sprintf('Failed to parse arguments: unexpected value type encountered.%s', PHP_EOL));
        break;
    }

    if($arg === '-h' || $arg === '--host') {
        $nextIs = 'host';
        continue;
    }

    if($arg === '-v' || $arg === '--var') {
        $nextIs = 'var';
        continue;
    }

    if(str_starts_with($arg, '--host=')) {
        if($nextIs !== null)
            die(sprintf('Failed to parse arguments: expected value, got flag.%s', PHP_EOL));

        $nextIs = 'host';
        $arg = substr($arg, 7);
        goto handleValue;
    }

    if(str_starts_with($arg, '--var=')) {
        if($nextIs !== null)
            die(sprintf('Failed to parse arguments: expected value, got flag.%s', PHP_EOL));

        $nextIs = 'var';
        $arg = substr($arg, 6);
        goto handleValue;
    }

    $pathIndex = $i;
    break;
}

$hostName ??= 'localhost';

// this should really not be necessary, mostly done to make sure the url registry is available
$msz->registerRequestRoutes(
    new HttpRequest('1.1', ['Host' => [$hostName]], NullStream::instance(), [], 'GET', HttpUri::createUri('/'), [], [])
);

$ctx = $msz->tplCtx->loadTemplate(implode(' ', array_slice($argv, $pathIndex)));

foreach($tplArgs as $name => $value)
    $ctx->setVar($name, $value);

echo $ctx->render();