"""
1 function for rn cuz im lazy
"""
import random
from typing import Literal, Optional
import requests

_US_LAST_NAMES = None
_UK_LAST_NAMES = None
_FIRST_NAMES_CACHE = None

def getname(
    country: Literal["us", "uk"] = "us",
    gender: Optional[Literal["male", "female"]] = None
) -> str:
    """
    args:
        country: us or uk
        gender: male or female

    returns names in First Last format

    raises
    valueerror if none found (should never happen lmao)
    connectionerror if connectionerror idk

    """

    _load_all_data()

    first_names = _filter_first_names(country, gender)

    if not first_names: # raise
        raise ValueError(f"No names found for country={country}, gender={gender}")

    first_name = random.choice(first_names)
    last_name = _get_random_last_name(country)

    return f"{first_name} {last_name}" # yep return ok

def _load_all_data():
    """load from github dude i hate commenting"""
    global _FIRST_NAMES_CACHE, _US_LAST_NAMES, _UK_LAST_NAMES

    if _FIRST_NAMES_CACHE is None:
        _FIRST_NAMES_CACHE = _fetch_first_names()

    if _US_LAST_NAMES is None:
        _US_LAST_NAMES = _fetch_last_names("us")

    if _UK_LAST_NAMES is None:
        _UK_LAST_NAMES = _fetch_last_names("uk")

def _fetch_first_names() -> list:
    """firstnameeee"""
    url = "https://raw.githubusercontent.com/railsmechanic/firstnames-to-gender/master/names.json"

    response = requests.get(url, timeout=10)
    response.raise_for_status()

    return response.json()

def _fetch_last_names(country: str) -> list:
    """last"""
    if country == "us":
        url = "https://raw.githubusercontent.com/SajjadPourali/Surnames/master/withoutStatistics/us.txt"
    else:  # uk
        url = "https://raw.githubusercontent.com/SajjadPourali/Surnames/master/withoutStatistics/uk.txt"

    response = requests.get(url, timeout=10)
    response.raise_for_status()

    last_names = [
        name.strip().title()
        for name in response.text.splitlines()
        if name.strip()
    ]

    return last_names

def _filter_first_names(country: str, gender: Optional[str]) -> list:
    """Filter first names by country and gender."""

    target_country = "us" if country == "us" else "gb"

    filtered = []
    for item in _FIRST_NAMES_CACHE:
        if item.get("country") != target_country:
            continue

        if gender and item.get("gender") != gender:
            continue

        name = item.get("name", "").strip().title()
        if name:
            filtered.append(name)

    return filtered

def _get_random_last_name(country: str) -> str:
    """literally read the function name"""
    if country == "us":
        if not _US_LAST_NAMES:
            raise ValueError("US last names not loaded")
        return random.choice(_US_LAST_NAMES)
    else:  # uk
        if not _UK_LAST_NAMES:
            raise ValueError("UK last names not loaded")
        return random.choice(_UK_LAST_NAMES)