from urllib.request import urlopen, Request
import urllib.error
import json
import time
import sys
import random

supabase_url = "https://uokovsjridlmlafrsrtf.supabase.co/rest/v1/update_version"
supabase_api_key = "sb_publishable_jUWDrMjKOpHOYVtm75rLSA_NmvKwOlg"


__version__ = "0.1.6"
# Backward compatibility for existing callers.
orbiLib = __version__

def fetch_latest_version(project, timeout=5):
    query_url = f"{supabase_url}?project=eq.{project.lower()}&select=version&limit=1"
    req = Request(
        query_url,
        headers={
            "Accept": "application/json",
            "Connection": "keep-alive",
            "apikey": supabase_api_key,
        },
    )

    with urlopen(req, timeout=timeout) as response:
        payload = response.read().decode("utf-8").strip()
        data = json.loads(payload)

    if not data:
        raise ValueError(f"No version row found for project '{project}'.")

    latest_version = data[0].get("version")
    if latest_version is None:
        raise ValueError("Supabase response is missing the 'version' field.")

    return str(latest_version)


def _normalize_version(value):
    return str(value).strip().lower().removeprefix("v")


def updateCheck(current_version, project, timeout=5):
    try:
        latest_version = fetch_latest_version(project, timeout=timeout)

        if _normalize_version(latest_version) == _normalize_version(current_version):
            print(f"Project {project} is up to date! (version {current_version})")
            return True

        print(
            f"Out of date. Your version: {current_version}. "
            f"Latest version: {latest_version}."
        )
        return False

    except urllib.error.HTTPError as e:
        print(
            f"Update check unavailable for {project}: HTTP {e.code}. "
            "Please try again later."
        )
        return None
    except urllib.error.URLError as e:
        print(f"Update check unavailable for {project}: {e}")
        return None
    except (ValueError, json.JSONDecodeError) as e:
        print(f"Unexpected response while checking updates for {project}: {e}")
        return None

def type_message(message, delay=0.05):
    """
    Prints a message one character at a time with a delay between each character.
    
    Args:
        message (str): The message to type out
        delay (float): Delay in seconds between each character (default 0.05)
    """
    for char in message:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(delay)
    print()

tombGreetings = ['Privacy is not for sale, and human rights should not be compromised out of fear or greed. - Pavel Durov', 'Why use a premade tool when I can make a crappy tool myself? - Orbernator']
cortexGreetings = ['The quiz game for that one person with some Buzz Controllers. And that browses GitHub. So just me. - Orbernator']

def greetingMessage(project):
    if project == 'Cortex':
        print(cortexGreetings[random.randint(0,0)])
    elif project == 'Tomb':
        print(tombGreetings[random.randint(0,1)])


def libUpdate():
    return updateCheck(__version__, 'orbilib')
