<?php

declare(strict_types=1);

function security_store_file(): string
{
    return __DIR__ . '/app_security.json';
}

function security_store_default_token(): string
{
    return 'THEFULL_APP_V3_' . hash('sha256', __DIR__ . php_uname() . '::thefull');
}

function security_store_clean_token(?string $token): string
{
    $token = trim((string)$token);
    $token = preg_replace('/[^A-Za-z0-9_\-\.\:]/', '', $token) ?: '';
    if (strlen($token) < 24) {
        return '';
    }
    if (strlen($token) > 160) {
        return substr($token, 0, 160);
    }
    return $token;
}

function security_store_load(): array
{
    $file = security_store_file();
    if (!is_file($file)) {
        return [];
    }
    $raw = @file_get_contents($file);
    if (!is_string($raw) || trim($raw) === '') {
        return [];
    }
    $json = json_decode($raw, true);
    return is_array($json) ? $json : [];
}

function security_store_token(): string
{
    $json = security_store_load();
    $token = security_store_clean_token($json['app_token'] ?? '');
    return $token !== '' ? $token : security_store_default_token();
}

function security_store_save_token(string $token): bool
{
    $token = security_store_clean_token($token);
    if ($token === '') {
        return false;
    }
    $payload = [
        'ok' => true,
        'app_token' => $token,
        'updated_at' => (int) round(microtime(true) * 1000),
        'token_header' => 'X-TF-Bridge',
        'token_query' => 'app_token',
        'min_protocol' => 3,
        'require_signature' => true,
        'security_revision' => 'panel-app-v3'
    ];
    $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    if (!is_string($json)) {
        return false;
    }
    $file = security_store_file();
    $tmp = $file . '.tmp';
    if (@file_put_contents($tmp, $json, LOCK_EX) === false) {
        return false;
    }
    return @rename($tmp, $file);
}

function security_store_generate_token(): string
{
    try {
        return 'THEFULL_APP_' . rtrim(strtr(base64_encode(random_bytes(32)), '+/', '_-'), '=');
    } catch (Throwable $e) {
        return 'THEFULL_APP_' . sha1(uniqid('', true) . microtime(true));
    }
}


function security_store_min_protocol(): int
{
    $json = security_store_load();
    return max(1, (int)($json['min_protocol'] ?? 3));
}

function security_store_require_signature(): bool
{
    $json = security_store_load();
    return array_key_exists('require_signature', $json) ? !empty($json['require_signature']) : true;
}
