# Author: Lộc Vũ Trung
# Endpoint resolver for LVTCenter VPS — XOR-encoded URL
# No plaintext server address in source code

"""
Decodes the VPS server URL at runtime using XOR obfuscation.
The actual URL is never stored as a readable string in the source.
"""

import urllib.request
import ssl
import json


# XOR key = 'LVTField' (8 bytes)
_KEY = [0x4C, 0x56, 0x54, 0x46, 0x69, 0x65, 0x6C, 0x64]

# XOR-encoded URL bytes (encoded from the actual server URL)
# h=0x68 ^ 0x4C=0x24, t=0x74 ^ 0x56=0x22, t=0x74 ^ 0x54=0x20, ...
_ENCODED = [
    0x24, 0x22, 0x20, 0x36, 0x1A, 0x5F, 0x43, 0x4B,  # https://
    0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00,  # lvtfield
    0x62, 0x3A, 0x22, 0x32, 0x0A, 0x00, 0x02, 0x10,  # .lvtcent
    0x29, 0x24, 0x7A, 0x2F, 0x1D, 0x4B, 0x0F, 0x0B,  # er.it.co
    0x21,                                              # m
]


def resolve():
    """Decode and return the VPS server URL."""
    return ''.join(
        chr(b ^ _KEY[i % len(_KEY)]) for i, b in enumerate(_ENCODED)
    )


def display_name():
    """Safe display name for the server (no URL exposed)."""
    return 'LVTField'


def is_available(timeout=5):
    """Check if the VPS server is reachable via health endpoint."""
    try:
        url = resolve() + '/api/health'
        ctx = ssl.create_default_context()
        req = urllib.request.Request(url, method='GET')
        with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:  # nosec B310
            data = json.loads(resp.read())
            return data.get('code', 0) == 200
    except Exception:
        return False
