<?php
namespace EasyChat\Library\Messenger;

class MaxRuntime {

    public static function requireAutoload(): void {
        static $loaded = false;
        if ($loaded || class_exists('\\PHPMax\\Client')) {
            $loaded = true;
            return;
        }

        spl_autoload_register(static function ($class): void {
            if (strpos($class, 'PHPMax\\') !== 0) {
                return;
            }
            $relative = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen('PHPMax\\')));
            $file = DIR_LIBRARY . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'phpmax' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'PHPMax' . DIRECTORY_SEPARATOR . $relative . '.php';
            if (is_file($file)) {
                require_once $file;
            }
        });

        $loaded = true;
    }

    public static function sessionRoot(): string {
        $base = defined('DIR_STORAGE') ? DIR_STORAGE : (SITE_PATH . DIRECTORY_SEPARATOR . 'storage');
        $dir = rtrim((string)$base, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'phpmax';
        if (!is_dir($dir)) {
            mkdir($dir, 0700, true);
        }
        if (is_dir($dir)) {
            self::bestEffort(static function () use ($dir): void {
                chmod($dir, 0700);
            });
            $deny = $dir . DIRECTORY_SEPARATOR . '.htaccess';
            if (!is_file($deny)) {
                self::bestEffort(static function () use ($deny): void {
                    file_put_contents($deny, "Deny from all\n");
                });
            }
        }
        return $dir;
    }

    public static function channelSessionName(int $channel_id): string {
        return 'max-channel-' . max(0, $channel_id) . '.json';
    }

    public static function safeError(\Throwable $e): string {
        $message = preg_replace('/(token|password|secret|code|phone)=([^\\s&]+)/i', '$1=***', $e->getMessage());
        return substr((string)$message, 0, 180);
    }

    private static function bestEffort(callable $callback): void {
        set_error_handler(static function (): bool {
            return true;
        });
        try {
            $callback();
        } finally {
            restore_error_handler();
        }
    }
}
