<?php

declare(strict_types=1);

namespace App\Support\Filesystem;

use Illuminate\Filesystem\Filesystem;
use RuntimeException;

class WindowsSafeFilesystem extends Filesystem
{
    /**
     * @param  int|null  $mode
     */
    public function replace($path, $content, $mode = null): void
    {
        clearstatcache(true, $path);

        $path = realpath($path) ?: $path;
        $directory = dirname($path);

        if (! $this->isDirectory($directory)) {
            $this->makeDirectory($directory, 0777, true, true);
        }

        $tempPath = tempnam($directory, basename($path));

        if ($tempPath === false) {
            throw new RuntimeException(sprintf('Unable to create a temporary file for [%s].', $path));
        }

        if (! is_null($mode)) {
            @chmod($tempPath, $mode);
        } else {
            @chmod($tempPath, 0777 - umask());
        }

        file_put_contents($tempPath, $content);

        if ($this->attemptRenameWithRetry($tempPath, $path)) {
            return;
        }

        if ($this->isWindows()) {
            // Windows 下 rename 覆盖已存在文件可能被占用而失败，改为安全回退写入。
            if (is_file($path)) {
                @unlink($path);
            }

            if (@rename($tempPath, $path)) {
                return;
            }

            if (@file_put_contents($path, $content, LOCK_EX) !== false) {
                @unlink($tempPath);

                if (! is_null($mode)) {
                    @chmod($path, $mode);
                }

                return;
            }
        }

        @unlink($tempPath);

        throw new RuntimeException(sprintf('Unable to replace file [%s].', $path));
    }

    private function attemptRenameWithRetry(string $tempPath, string $path): bool
    {
        for ($attempt = 0; $attempt < 5; $attempt++) {
            if (@rename($tempPath, $path)) {
                return true;
            }

            clearstatcache(true, $path);
            usleep(50000 * ($attempt + 1));
        }

        return false;
    }

    private function isWindows(): bool
    {
        return PHP_OS_FAMILY === 'Windows';
    }
}