"""Pull WoW global function names from Townlong-Yak's wow-ui-source repo at a given tag.

Phase 1 captures only top-level globals (no `Foo.Bar` namespacing). The caller
uses the diff between two tags as the API surface diff.
"""
import re
from bot.lib.http import fetch_text

# https://www.townlong-yak.com/framexml/ — repo on GitHub: Gethe/wow-ui-source
# Raw file URL pattern. Tag examples: "live-11.2.7.59185", "classic_era-1.15.8.59000".
RAW_BASE = "https://raw.githubusercontent.com/Gethe/wow-ui-source/{tag}/{path}"

_FUNC_KEYWORD = re.compile(r"^\s*function\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(", re.MULTILINE)
_FUNC_ASSIGN = re.compile(
    r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*function\s*\(", re.MULTILINE
)


def extract_global_function_names(lua_source: str) -> set[str]:
    names: set[str] = set()
    for m in _FUNC_KEYWORD.finditer(lua_source):
        names.add(m.group(1))
    for m in _FUNC_ASSIGN.finditer(lua_source):
        names.add(m.group(1))
    return names


def fetch_raw_lua(tag: str, path: str) -> str:
    return fetch_text(RAW_BASE.format(tag=tag, path=path))
