<?php
namespace Core\System\License;

class Fingerprint
{
    /**
     * Generates a stable machine fingerprint (unchanged behavior).
     */
    public static function generate(): string
    {
        $data = [
            php_uname(),
            PHP_VERSION,
            $_SERVER['SERVER_SOFTWARE'] ?? '',
            $_SERVER['DOCUMENT_ROOT'] ?? '',
        ];

        return hash('sha256', implode('|', $data));
    }

    /**
     * Integrity hashing (anti-tamper telemetry).
     *
     * IMPORTANT:
     * - This does NOT affect activation/allow/block by itself.
     * - Returns SHA256 hashes of critical files relative to MTEngine root.
     * - Matches the structure stored in license server table integrity_versions.hashes_json.
     *
     * Return format:
     * [
     *   "core/system/App.php" => "sha256...",
     *   ...
     * ]
     */
    public static function integrity(): array
    {
        $root = self::engineRootPath();

        $targets = [
            'core/system/App.php',
            'core/system/License/LicenseMiddleware.php',
            'core/system/License/LicenseClient.php',
            'core/system/License/LicenseStorage.php',
            'core/system/License/Fingerprint.php',
        ];

        $hashes = [];

        foreach ($targets as $rel) {
            $full = rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $rel);

            if (!is_file($full) || !is_readable($full)) {
                // Mark missing/unreadable explicitly to detect tampering
                $hashes[$rel] = null;
                continue;
            }

            $content = file_get_contents($full);
            if ($content === false) {
                $hashes[$rel] = null;
                continue;
            }

            $hashes[$rel] = hash('sha256', $content);
        }

        return $hashes;
    }

    /**
     * Resolve MTEngine root directory reliably.
     * This file is located at: core/system/License/Fingerprint.php
     * Root = 4 levels up from this file:
     *   License -> system -> core -> (root)
     */
    protected static function engineRootPath(): string
    {
        // __DIR__ => .../core/system/License
        return realpath(__DIR__ . '/../../../..') ?: dirname(__DIR__, 4);
    }
}
