<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

/**
 * Artisan 命令输出脱敏（不含 .env 密钥与数据库密码）。
 */
final class HostSystemUpdateArtisanOutputSanitizer
{
    /**
     * @var list<string>
     */
    private const SENSITIVE_PATTERNS = [
        '/APP_KEY\s*=/i',
        '/DB_PASSWORD\s*=/i',
        '/DB_USERNAME\s*=/i',
        '/SUPPORT_CENTER_HOST_TOKEN\s*=/i',
        '/SUPPORT_CENTER_HOST_KEY\s*=/i',
        '/Authorization:\s*.+/i',
        '/download_token\s*[:=]\s*\S+/i',
    ];

    public static function sanitize(string $output): string
    {
        $lines = preg_split("/\r\n|\n|\r/", $output) ?: [];
        $sanitized = [];

        foreach ($lines as $line) {
            $redacted = $line;

            foreach (self::SENSITIVE_PATTERNS as $pattern) {
                if (preg_match($pattern, $redacted) === 1) {
                    $redacted = '[redacted]';
                    break;
                }
            }

            $sanitized[] = $redacted;
        }

        return implode("\n", $sanitized);
    }

    public static function excerpt(string $output, int $maxLength = 500): string
    {
        $sanitized = trim(self::sanitize($output));

        if ($sanitized === '') {
            return '';
        }

        if (strlen($sanitized) <= $maxLength) {
            return $sanitized;
        }

        return substr($sanitized, 0, $maxLength).'…';
    }
}
