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

declare(strict_types=1);

// A box for testing a hub without an application: it is to the hub what an application's console
// command is. Which hub and which environment it speaks as come from `client` in config.php, or
// from ERRHUB_URL and ERRHUB_KEY.

require dirname(__DIR__) . '/src/bootstrap.php';
require dirname(__DIR__) . '/client/ErrhubClient.php';

const USAGE = <<<TXT
usage: bin/client <command>

  ping                          check the key; tells the hub which commit this box runs
  sample [<message>] [<count>]  send one made-up error (the same message is the same type)
  send <folder>                 sweep a folder of report files (*.json, one report each, as POST /v1/reports takes them)
  types [<stage>]               this project's error types
  show <fingerprint>            one type with its history
  issue <fingerprint>           create its GitHub issue now
  complete <fingerprint> <by>   mark the test complete (test environments only)
  mute <fingerprint> [off]      stop, or resume, lodging and following a type

  ERRHUB_COMMIT sets the commit the box says it runs (default: this checkout's).

TXT;

$args = array_slice($argv, 1);
$command = array_shift($args) ?? '';
if ($command === '' || $command === 'help') {
    echo USAGE;
    exit(0);
}

$line = static function (array $t): string {
    $envs = implode(' ', array_map(static fn ($e) => "$e[name]:$e[count]", $t['environments']));
    return sprintf("%s  %-14s %5d  %-22s %-6s %s", $t['fingerprint'], $t['stage'] . ($t['muted'] ? '*' : ''), $t['total_count'],
        $envs, $t['issue'] ? '#' . $t['issue']['number'] : '-', mb_strimwidth((string)preg_replace('/\s+/', ' ', $t['message']), 0, 70, '…'));
};

try {
    $config = errhub_config()['client'];
    $url = getenv('ERRHUB_URL') ?: ($config['url'] ?? '');
    $key = getenv('ERRHUB_KEY') ?: ($config['key'] ?? '');
    if ($url === '' || $key === '') {
        throw new InvalidArgumentException("Set client.url and client.key in config/config.php (or ERRHUB_URL and ERRHUB_KEY).\nA key comes from: bin/hub env:key <project> <environment>");
    }
    $client = new ErrhubClient($url, $key, getenv('ERRHUB_COMMIT') ?: ErrhubClient::gitCommit(dirname(__DIR__)), 'bin/client');

    switch ($command) {
        case 'ping':
            $p = $client->ping();
            echo "$url: $p[project] / $p[environment], running " . ($p['commit'] ? substr($p['commit'], 0, 8) : 'an unknown commit') . "\n";
            break;

        case 'sample':
            $message = $args[0] ?? 'Undefined variable $sample';
            $file = 'bin/client';
            $sent = $client->send([[
                'client_ref'      => 'sample-' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4)),
                'fingerprint'     => ErrhubClient::fingerprint('php', 'ErrorException', $file, 'sample', $message),
                'occurred_at'     => gmdate('c'),
                'category'        => 'php',
                'exception_class' => 'ErrorException',
                'message'         => $message,
                'file'            => $file,
                'function'        => 'sample',
                'count'           => max(1, (int)($args[1] ?? 1)),
                'report'          => [
                    'error'   => ['trace' => ["#0 $file(1): sample()", '#1 {main}']],
                    'request' => ['method' => 'CLI', 'uri' => 'bin/client sample'],
                    'user'    => ['guest' => true],
                ],
            ]]);
            foreach ($sent['rejected'] as $x) {
                echo "rejected: $x[error]\n";
            }
            foreach ($sent['types'] as $t) {
                echo $line($t) . "\n";
            }
            break;

        case 'send':
            if (count($args) !== 1 || !is_dir($args[0])) {
                throw new InvalidArgumentException(USAGE);
            }
            $r = $client->sweep($args[0], static function (string $path): ?array {
                $report = json_decode((string)file_get_contents($path), true);
                return is_array($report) ? $report : null;
            }, '*.json');
            printf("%d sent: %d stored, %d already there, %d rejected; %d file(s) not reports\n", $r['sent'], $r['stored'], $r['duplicate'], count($r['rejected']), $r['skipped']);
            foreach ($r['rejected'] as $x) {
                echo "  rejected $x[client_ref]: $x[error]\n";
            }
            foreach ($r['types'] as $t) {
                echo $line($t) . "\n";
            }
            break;

        case 'types':
            foreach ($client->types(isset($args[0]) ? ['stage' => $args[0]] : []) as $t) {
                echo $line($t) . "\n";
            }
            break;

        case 'show':
        case 'issue':
        case 'complete':
        case 'mute':
            if (!isset($args[0]) || ($command === 'complete' && !isset($args[1]))) {
                throw new InvalidArgumentException(USAGE);
            }
            $t = match ($command) {
                'show'     => $client->type($args[0]),
                'issue'    => $client->createIssue($args[0]),
                'complete' => $client->completeTest($args[0], $args[1]),
                'mute'     => $client->mute($args[0], ($args[1] ?? '') !== 'off'),
            };
            echo $line($t) . "\n";
            if ($t['issue']) {
                echo "  {$t['issue']['url']} ({$t['issue']['state']})\n";
            }
            foreach (array_reverse($t['events'] ?? []) as $ev) {
                echo "  $ev[created_at]  " . str_pad((string)($ev['environment'] ?? ''), 6) . " $ev[event]" . ($ev['detail'] !== null && $ev['detail'] !== '' ? ": $ev[detail]" : '') . "\n";
            }
            break;

        default:
            echo USAGE;
            exit(1);
    }
} catch (InvalidArgumentException $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
} catch (Throwable $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(2);
}
