<?php










function blog_debug_preview(string $s, int $maxLen = 400): string
{
    $s = (string)$s;
    
    $s = preg_replace('/[^\\x20-\\x7E]/', '?', $s) ?? '';
    if (strlen($s) > $maxLen) {
        $s = substr($s, 0, $maxLen) . '...';
    }
    return $s;
}




function blog_debug_log(string $name, array $data): void
{
    if (!defined('BASE_PATH')) {
        return;
    }
    
    if (!defined('APP_DEBUG') || APP_DEBUG !== true) {
        return;
    }
    $dir = BASE_PATH . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'logs';
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);
    }

    
    $name = preg_replace('/[^a-zA-Z0-9._-]+/', '_', (string)$name) ?? 'debug.log';
    if ($name === '' || strpos($name, '..') !== false) {
        $name = 'debug.log';
    }

    $path = $dir . DIRECTORY_SEPARATOR . $name;
    $meta = [
        '_ts'  => time(),
        '_dt'  => date('Y-m-d H:i:s'),
        '_uri' => $_SERVER['REQUEST_URI'] ?? '',
        '_ip'  => $_SERVER['REMOTE_ADDR'] ?? '',
    ];
    $payload = $meta + $data;

    $line = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($line === false) {
        $line = json_encode($meta + ['_encode_error' => true], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '{"_encode_error":true}';
    }

    @file_put_contents($path, $line . PHP_EOL, FILE_APPEND | LOCK_EX);
}
