import requests
from bs4 import BeautifulSoup
import time
import logging

# U góry pliku na starcie ustaw loggera (jeśli jeszcze nie masz):
logging.basicConfig(level=logging.INFO)
# Keep the existing log category across the module relocation (and file execution).
logger = logging.getLogger(__name__ if __name__ == "__main__" else "modules.homelanzarote.homelanzarote_scraper")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (InvestmentIntegrator/1.0)"
}

category_urls = {
    "flats": "https://www.homelanzarote.es/en/flats",
    "apartments": "https://www.homelanzarote.es/en/apartments",
    "chalets": "https://www.homelanzarote.es/en/chalets",
    "houses": "https://www.homelanzarote.es/en/houses",
    "plots_land": "https://www.homelanzarote.es/en/plots_land",
    "business_premises": "https://www.homelanzarote.es/en/business_premises",
    "offices": "https://www.homelanzarote.es/en/offices",
    "buildings": "https://www.homelanzarote.es/en/buildings"
}

def parse_features(offer):
    feature_map = {
        "size": "size",
        "superficie": "size",

        "bedroom": "bedrooms",
        "dormitorio": "bedrooms",

        "bath": "bathrooms",
        "baño": "bathrooms",

        "garage": "garage",
        "garaje": "garage",

        "terrace": "terrace",
        "terraza": "terrace",

        "lift": "lift",
        "ascensor": "lift",

        "swimming pool": "pool",
        "piscina": "pool",

        "energy certification": "energy_cert",
        "certificación energética": "energy_cert"
    }

    features = {}
    icon_spans = offer.select("span.iconos_carac span.icinfo")

    for span in icon_spans:
        img = span.find("img")
        if img:
            title = img.get("title", "").strip().lower()
            text = span.get_text(strip=True)
            for key, label in feature_map.items():
                if key in title:
                    features[label] = text
                    break
    return features

def scrape_offers(base_url, all_pages=True):
    results = []
    next_url = base_url
    page = 1

    while next_url:
        logger.info(f"Scraping page {page} → {next_url}")
        r = requests.get(
            next_url,
            headers=HEADERS,
            timeout=15
        )

        logger.info(f"HTTP status: {r.status_code}")

        if r.status_code != 200:
            logger.warning(f"Problem z pobraniem strony (status code {r.status_code}): {next_url}")
            break  # przerywamy pętlę jeśli strona się nie pobrała


        soup = BeautifulSoup(r.content, "html.parser")

        offers = soup.find_all("div", class_="bx_resumen_prop_grid")
        for offer in offers:
            try:
                title = offer.select_one("div.prop_tipo")
                title = title.get_text(strip=True) if title else None

                location_tags = offer.select("h3.prop_localiz span")
                location = ", ".join([tag.get_text(strip=True) for tag in location_tags]) if location_tags else None

                price_tag = offer.select_one("div.info_precio span.importe")
                price = price_tag.get_text(strip=True) if price_tag else None

                url_tag = offer.select_one("a.enlace_imagen_propiedad")
                url_offer = url_tag["href"] if url_tag else None

                img_tag = offer.select_one("a.enlace_imagen_propiedad img")
                img = "https://www.homelanzarote.es" + img_tag["src"] if img_tag else None

                ref_tag = offer.select_one("div.referencia a")
                ref = ref_tag.get_text(strip=True) if ref_tag else None

                tag_span = offer.select_one("span.ctlto")
                tag_label = tag_span.get_text(strip=True) if tag_span else None

                features = parse_features(offer)

                results.append({
                    "title": title,
                    "location": location,
                    "price": price,
                    "url": url_offer,
                    "image": img,
                    "ref": ref,
                    "label": tag_label,
                    **features
                })
            except Exception as e:
                logger.info("Blad parsowania:", e)

        if not all_pages:
            break  # tylko pierwsza strona

        # Dokładna detekcja "next"
        next_button = None
        pagination = soup.find("p", id="paginacion_form_busc_av")
        if pagination:
            for a in pagination.find_all("a", class_="bot_pagin"):
                if "next" in a.get_text(strip=True).lower():
                    next_button = a
                    break

        if next_button and "href" in next_button.attrs:
            next_url = next_button["href"]
            if not next_url.startswith("http"):
                next_url = "https://www.homelanzarote.es" + next_url
            page += 1
            time.sleep(1)
        else:
            next_url = None

    return results


def scrape_category(category_name: str, all_pages=True, lang="en"):
    """
    Scrapuje oferty tylko dla jednej kategorii.
    Domyślnie scrapuje wszystkie strony.
    """
    if category_name not in category_urls:
        raise ValueError(f"Nieprawidlowa kategoria: {category_name}")

    url = category_urls[category_name]
    url = url.replace("/en/", f"/{lang}/")  # <== tu zmiana języka
    logger.info(f"Scrapuje kategorie: {category_name} ({lang})")
    offers = scrape_offers(url, all_pages=all_pages)
    return offers

def scrape_offer_details(url: str, lang="en"):

    if "/en/" in url or "/es/" in url:
        url = url.replace("/en/", f"/{lang}/").replace("/es/", f"/{lang}/")

    logger.info(f"Scraping details from: {url}")

    try:
        r = requests.get(url, headers=HEADERS, timeout=15)
    except Exception as e:
        logger.error(f"Request error: {e}")
        raise Exception(f"Request failed: {e}")

    logger.info(f"HTTP status: {r.status_code}")

    if r.status_code != 200:
        raise Exception(f"Bad status code: {r.status_code}")

    soup = BeautifulSoup(r.content, "html.parser")

    data = {
        "url": url,
        "title": None,
        "price": None,
        "location": None,
        "ref": None,
        "label": None,
        "image": None,
        "features": {},
        "details": {}
    }

    # Title
    title_tag = soup.select_one("h3")
    if title_tag:
        data["title"] = title_tag.get_text(strip=True)

    # Price
    price_tag = soup.select_one("div.info_precio span.importe")
    if price_tag:
        data["price"] = price_tag.get_text(strip=True)

    # Reference
    ref_tag = soup.select_one("div.referencia a.codigo-tag-referencia")
    if ref_tag:
        data["ref"] = ref_tag.get_text(strip=True)

    # Label
    label_tag = soup.select_one("span.ctlto")
    if label_tag:
        data["label"] = label_tag.get_text(strip=True)

    # Location
    location_parts = soup.select("div.localizacion span")
    if location_parts:
        location = ", ".join([el.get_text(strip=True) for el in location_parts])
        data["location"] = location

    # Image
    main_image = soup.select_one("div.foton img")
    if main_image and "src" in main_image.attrs:
        img_src = main_image["src"]
        if not img_src.startswith("http"):
            img_src = "https://www.homelanzarote.es" + img_src
        data["image"] = img_src

    # Short title (from description breve)
    short_title_tag = soup.select_one("div.descripcion span.breve a")
    if short_title_tag:
        data["short_title"] = short_title_tag.get_text(strip=True)

    # Description
    desc_div = soup.select_one("div.descripcion span.larga")
    if desc_div:
        data["description"] = desc_div.get_text(separator="\n", strip=True)

    # Features (ikonki górne)
    feature_map = {
        "size": "size",
        "superficie": "size",

        "bedroom": "bedrooms",
        "dormitorio": "bedrooms",

        "bath": "bathrooms",
        "baño": "bathrooms",

        "garage": "garage",
        "garaje": "garage",

        "terrace": "terrace",
        "terraza": "terrace",

        "lift": "lift",
        "ascensor": "lift",

        "swimming pool": "pool",
        "piscina": "pool",

        "energy certification": "energy_cert",
        "certificación energética": "energy_cert"
    }

    features = {}
    for span in soup.select("span.iconos_carac span.icinfo"):
        img = span.find("img")
        if img:
            title = img.get("title", "").lower()
            text = span.get_text(strip=True)
            for key, label in feature_map.items():
                if key in title:
                    features[label] = text
                    break
    data["features"] = features

    # Szczegółowe informacje
    details = {}
    for div in soup.select("div.caracteristicas div.car"):
        key_el = div.select_one(".car_cap")
        val_el = div.select_one(".car_val")
        if key_el and val_el:
            key = key_el.get_text(strip=True).rstrip(":")
            val = val_el.get_text(strip=True)
            details[key] = val
    data["details"] = details

    return data
