from . import command, STOP_PROCESSING, reply_fn
from html import escape
import re
import requests
import logging
from telegram import InputMediaPhoto
import random

logger = logging.getLogger('dex')

API_BASE = "https://bulbapedia.bulbagarden.net/w/api.php"

pokemon_names = None

def wiki_get_image_url(title):
    file_params = {"action": "query", "titles": title, "prop": "imageinfo", "iiprop": "url", "format": "json", "formatversion": "2"}

    try:
        resp = requests.get(API_BASE, params=file_params)
    except requests.ConnectionError:
        return None

    try:
        url = resp.json()["query"]["pages"][0]["imageinfo"][0]["url"]
    except KeyError:
        return None
    return url

def get_pokemon_names():
    params = {"action": "parse", "page": "List_of_Pokémon_by_name", "prop": "links", "formatversion": 2, "format": "json"}
    resp = requests.get(API_BASE, params=params)

    names = []

    data = resp.json()
    for elem in data['parse']['links']:
        if elem['title'].endswith('(Pokémon)'):
            names.append(elem['title'].rsplit(' ', 1)[0])

    logger.info(f"Loaded {len(names)} pokémon names.")

    return names

@command('dex.random')
def dex_random(bea, bot, update):
    name = random.choice(pokemon_names)
    do_dex(bea, bot, update, name)

@command('dex (.+)', pass_groups=True)
def dex(bea, bot, update, groups):
    do_dex(bea, bot, update, groups[0])

def do_dex(bea, bot, update, name):
    params = {"action": "parse", "page": name.replace(' ', '_') + "_(Pokémon)", "prop": "wikitext", "formatversion": 2, "format": "json"}

    logger.info('Starting dex lookup...')

    try:
        resp = requests.get(API_BASE, params=params)
        if resp.status_code != 200:
            logger.warning(f"Bulba lookup: status code {resp.status_code}")
    except requests.ConnectionError:
        return bea.reply("Ik kon Bulbapedia niet bereiken, sorry.")

    try:
        data = resp.json()
        wikitext = data["parse"]["wikitext"]
    except KeyError:
        return bea.reply("Die Pokémon kon ik niet vinden, sorry.")

    name = None
    idx = None
    types = []
    past_infobox = False
    dex_entry = ""
    image_override = None

    has_alolan = False
    has_galarian = False

    for line in wikitext.split('\n'):
        if line.startswith("|name="):
            name = line.split("|name=")[1].strip()
        if line.startswith("|ndex="):
            idx = line.split("|ndex=")[1].strip()
        if (m := re.match(r"\|type\d=([A-z]+)", line)) and not past_infobox:
            types.append(m.group(1))
        if (m := re.match(r"^\|image=(.+)$", line)) and not past_infobox:
            image_override = m.group(1)
        if line == "}}":
            past_infobox = True
        if m := re.match(r"^{{Dex/Entry\d.*entry=(.+)}}$", line):
            dex_entry = m.group(1)
        if 'Alola' in line and not past_infobox:
            has_alolan = True
        if 'Galar' in line and not past_infobox:
            has_galarian = True

    logger.info('Getting URLs...')

    if image_override is not None:
        urls = [wiki_get_image_url(f"File:{image_override}")]
    else:
        urls = [wiki_get_image_url(f"File:{idx}{name}.png")]
        if has_alolan: urls.append(wiki_get_image_url(f"File:{idx}{name}-Alola.png"))
        if has_galarian: urls.append(wiki_get_image_url(f"File:{idx}{name}-Galar.png"))

    logger.info(f'Sending photos for urls: {urls}')

    caption = f"{name}\n\n<u>Type</u> <i>{escape(', '.join(types))}</i>\n<u>Dex entry</u>: <i>{escape(dex_entry)}</i>"

    photos = [InputMediaPhoto(u, caption=caption, parse_mode='HTML') if n == 0 else InputMediaPhoto(u) for n, u in enumerate(urls) if u is not None]

    return update.message.reply_media_group(photos)



def init(bea, _config):
    global pokemon_names
    pokemon_names = get_pokemon_names()
    return [dex, dex_random]
