import logging

import requests
from bs4 import BeautifulSoup

logger = logging.getLogger(__name__)

VIVINO_URL = "https://www.vivino.com/{vivino_id}"


def get_title_from_soup(soup) -> str:
    title = ""
    try:
        title = soup.find("span", class_="winePageHeader__title").get_text(strip=True)
    except AttributeError:
        pass
    return title


def get_description_from_soup(soup) -> str:
    desc = ""
    try:
        desc = soup.find("div", class_="winePageHeader__description").get_text(
            strip=True
        )
    except AttributeError:
        pass
    return desc


def get_wine_type_from_soup(soup) -> str:
    wine_type = ""
    try:
        wine_type = (
            soup.find("span", class_="winePageHeader__wine-type")
            .get_text(strip=True)
            .lower()
        )
    except AttributeError:
        pass
    return wine_type


def get_rating_from_soup(soup) -> float:
    rating = None
    try:
        rating = float(
            soup.find("div", class_="winePageHeader__ratingValue").get_text(strip=True)
        )
    except (AttributeError, ValueError):
        pass
    return rating


def get_grapes_from_soup(soup) -> list[str]:
    grapes = []
    try:
        grape_elements = soup.find_all("a", class_="wineLink")
        grapes = [
            g.get_text(strip=True) for g in grape_elements if g.get_text(strip=True)
        ]
    except AttributeError:
        pass
    return grapes


def get_region_from_soup(soup) -> str:
    region = ""
    try:
        region = soup.find("span", class_="winePageHeader__region").get_text(strip=True)
    except AttributeError:
        pass
    return region


def get_producer_from_soup(soup) -> str:
    producer = ""
    try:
        producer = soup.find("span", class_="winePageHeader__producer").get_text(
            strip=True
        )
    except AttributeError:
        pass
    return producer


def get_vintage_from_soup(soup) -> str:
    vintage = ""
    try:
        vintage = soup.find("span", class_="winePageHeader__vintage").get_text(
            strip=True
        )
    except AttributeError:
        pass
    return vintage


def get_image_url_from_soup(soup) -> str:
    image_url = ""
    try:
        image_url = soup.find("img", class_="winePageHeader__image")["src"]
    except (AttributeError, KeyError, TypeError):
        pass
    return image_url


def get_wine_from_vivino_id(vivino_id: str) -> dict:
    wine_url = VIVINO_URL.format(vivino_id=vivino_id)
    headers = {"User-Agent": "Vrobbler 0.11.12"}
    response = requests.get(wine_url, headers=headers)
    wine_dict = {"vivino_id": vivino_id}

    if response.status_code != 200:
        logger.warning(
            "Bad response from vivino.com",
            extra={"status_code": response.status_code, "vivino_id": vivino_id},
        )
        return wine_dict

    soup = BeautifulSoup(response.text, "html.parser")
    wine_dict["title"] = get_title_from_soup(soup)
    wine_dict["description"] = get_description_from_soup(soup)
    wine_dict["wine_type"] = get_wine_type_from_soup(soup)
    wine_dict["vivino_rating"] = get_rating_from_soup(soup)
    wine_dict["grapes"] = get_grapes_from_soup(soup)
    wine_dict["region"] = get_region_from_soup(soup)
    wine_dict["producer__name"] = get_producer_from_soup(soup)
    wine_dict["vintage"] = get_vintage_from_soup(soup)
    wine_dict["image_url"] = get_image_url_from_soup(soup)

    return wine_dict
