<?php
declare(strict_types=1);

use SafeTun\Backend\Config\ConfigValidator;
use SafeTun\Backend\Config\LiteralConfigParser;
use SafeTun\Backend\Exception\ConfigException;

require dirname(__DIR__) . '/src/autoload.php';

$serverArguments = $_SERVER['argv'] ?? null;
if (!is_array($serverArguments)) {
    fwrite(STDERR, "This command must run from a CLI that provides argv.\n");
    exit(2);
}
$arguments = [];
foreach ($serverArguments as $serverArgument) {
    if (!is_string($serverArgument)) {
        fwrite(STDERR, "Invalid CLI argument vector.\n");
        exit(2);
    }
    $arguments[] = $serverArgument;
}
$json = false;
$documentRoot = null;
$configPath = null;
foreach (array_slice($arguments, 1) as $argument) {
    if ($argument === '--json') {
        $json = true;
    } elseif (str_starts_with($argument, '--docroot=')) {
        $documentRoot = substr($argument, strlen('--docroot='));
    } elseif (!str_starts_with($argument, '-') && $configPath === null) {
        $configPath = $argument;
    } else {
        fwrite(STDERR, "Usage: php safetun-config-check.php [--json] [--docroot=PATH] /path/config.php\n");
        exit(2);
    }
}
if ($configPath === null) {
    fwrite(STDERR, "Usage: php safetun-config-check.php [--json] [--docroot=PATH] /path/config.php\n");
    exit(2);
}
if (PHP_VERSION_ID < 80200 || !extension_loaded('sodium') || !extension_loaded('openssl')) {
    fwrite(STDERR, "SafeTun requires PHP 8.2+, Sodium, and OpenSSL.\n");
    exit(2);
}

try {
    $parsed = (new LiteralConfigParser())->parseFile($configPath);
    $validated = (new ConfigValidator())->validate($parsed, $configPath, $documentRoot);
    if ($json) {
        echo json_encode([
            'valid' => true,
            'sha256' => $validated->sha256,
            'warnings' => $validated->warnings,
            'normalized_allowed_iran_cidrs' => $validated->values['authorization']['allowed_iran_cidrs'],
        ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES) . "\n";
    } else {
        echo "OK: literal-only syntax and SafeTun schema are valid.\n";
        echo "SHA-256: {$validated->sha256}\n";
        foreach ($validated->warnings as $warning) {
            echo "WARNING: {$warning}\n";
        }
        echo 'Normalized Iran CIDRs: ' . count($validated->values['authorization']['allowed_iran_cidrs']) . "\n";
    }
    exit(0);
} catch (ConfigException $exception) {
    if ($json) {
        echo json_encode(['valid' => false, 'errors' => $exception->errors()], JSON_UNESCAPED_SLASHES) . "\n";
    } else {
        fwrite(STDERR, "INVALID SafeTun configuration:\n");
        foreach ($exception->errors() as $error) {
            fwrite(STDERR, " - {$error}\n");
        }
    }
    exit(1);
} catch (Throwable $exception) {
    $message = 'Configuration check failed safely: ' . $exception->getMessage();
    if ($json) {
        echo json_encode(['valid' => false, 'errors' => [$message]], JSON_UNESCAPED_SLASHES) . "\n";
    } else {
        fwrite(STDERR, $message . "\n");
    }
    exit(1);
}
