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

declare(strict_types=1);

use Bref\Bref;
use Bref\Console\Command\Local;
use Bref\Context\Context;
use Bref\Runtime\Invoker;
use CliArgs\CliArgs;

require_once(__DIR__ . '/../../cheprasov/php-cli-args/src/autoloader.php');

$args = [
    'sls-config' => [
        'help' => 'Json containing the serverless configuration',
    ],
    'function' => [
        'help' => 'The name of the function to run',
    ],
    'event' => [
        'help' => 'The event data in json format'
    ],
    'app-path' => [
        'help' => 'The path to the application',
    ],
    'marker' => [
        'help' => 'Optional marker to prefix the result when it is emitted'
    ]
];

$argHelper = new CliArgs($args);

$appPath = $argHelper->getArg('app-path');

if (!$appPath) {
    print "No app path provided";
    exit(1);
}

if (file_exists($appPath . '/vendor/autoload.php')) {
    require_once $appPath . '/vendor/autoload.php';
} else {
    print "App path did not contain an autoloader.";
    exit(1);
}

/**
 * Provides a wrapper around Bref's Local invoker class without the opinionated
 * output
 */
class Adapter extends Local
{

    public function invoke(array $slsConfig, ?string $function, ?string $data): string
    {

        $handler = $slsConfig['functions'][$function]['handler'];
        $handler = Bref::getContainer()->get($handler);

        $event = $data ? json_decode($data, true, 512, JSON_THROW_ON_ERROR) : null;

        // Same configuration as the Bref runtime on Lambda
        ini_set('display_errors', '1');
        error_reporting(E_ALL);

        $requestId = '8f507cfc-example-4697-b07a-ac58fc914c95';

        $invoker = new Invoker;
        $result = $invoker->invoke($handler, $event, new Context($requestId, 0, '', ''));
        unset($invoker);
        unset($handler);

        return json_encode($result);
    }

}

$adapter = new Adapter;

$slsConfig = json_decode(base64_decode($argHelper->getArg('sls-config')), true);
if (!empty(json_last_error())) {
    print "error parsing serverless config: " . json_last_error_msg();
    exit(1);
}
$function = $argHelper->getArg('function');
$data = base64_decode($argHelper->getArg('event'));

$result = $adapter->invoke($slsConfig, $function, $data);

file_put_contents($appPath . "/.bref-result", $result);

exit;
