import re
import requests
from bs4 import BeautifulSoup
from urllib.parse import quote_plus, urljoin, urlsplit

from integrations.tripinvest.config import (
    HEADERS,
    TRIPINVEST_FILTERS,
    TRIPINVEST_SORTING,
    TRIPINVEST_OFFER_FLAGS,
    TRIPINVEST_MARKET,
    TRIPINVEST_SEA_DISTANCE,
    TRIPINVEST_FEATURES,
)

# =====================================================
# HELPERY LISTING
# =====================================================

def get_soup(url: str) -> BeautifulSoup:
    """Pobiera HTML strony i zwraca BeautifulSoup"""
    response = requests.get(url, headers=HEADERS, timeout=15)
    response.raise_for_status()
    return BeautifulSoup(response.text, "html.parser")

def extract_offer_url_from_card(offer, base_url: str) -> str | None:
    """Wyciąga kanoniczny URL oferty z karty"""
    for a in offer.select("a[href]"):
        href = a.get("href")
        if href and "/oferta/" in href:
            return urljoin(base_url, href)
    return None


def build_tripinvest_base_url(
    region: str,
    area: str | None,
    filter_name: str | None = None
) -> str:
    """Buduje URL bazowy TripInvest"""

    base = f"https://tripinvest.pl/{region}"

    if filter_name:
        slug = TRIPINVEST_FILTERS.get(filter_name)
        if not slug:
            raise ValueError(
                f"Nieznany filtr '{filter_name}'. Dostępne: {list(TRIPINVEST_FILTERS)}"
            )
        base += f"/{slug}"

    if area:
        base += f"/{area}"

    return base


def apply_sorting(url: str, sorting: str | None) -> str:
    """Dodaje sorting_mode do URL jeśli podano"""
    if not sorting:
        return url

    sort_value = TRIPINVEST_SORTING.get(sorting)
    if not sort_value:
        raise ValueError(
            f"Nieznany sorting '{sorting}'. Dostępne: {list(TRIPINVEST_SORTING)}"
        )

    separator = "&" if "?" in url else "?"
    return f"{url}{separator}sorting_mode={sort_value}"

def apply_offer_flag(url: str, offer_flags: list[str] | None) -> str:
    if not offer_flags:
        return url

    allowed = set(TRIPINVEST_OFFER_FLAGS.values())

    for flag in offer_flags:
        if flag not in allowed:
            raise ValueError(
                f"Nieznany offer_flag '{flag}'. Dostępne: {list(allowed)}"
            )

    separator = "&" if "?" in url else "?"
    params = "&".join(f"offer_is={flag}" for flag in offer_flags)

    return f"{url}{separator}{params}"

def apply_market(url: str, markets: list[str] | None) -> str:
    if not markets:
        return url

    allowed = set(TRIPINVEST_MARKET.values())

    for m in markets:
        if m not in allowed:
            raise ValueError(
                f"Nieznany market '{m}'. Dostępne: {list(allowed)}"
            )

    separator = "&" if "?" in url else "?"
    params = "&".join(f"market={m}" for m in markets)

    return f"{url}{separator}{params}"


def apply_price_range(url: str, price_min: int | None, price_max: int | None) -> str:
    """Dodaje zakres cenowy do URL jeśli podano"""
    if price_min is None and price_max is None:
        return url

    params = []
    if price_min is not None:
        params.append(f"price.from={price_min}")
    if price_max is not None:
        params.append(f"price.to={price_max}")

    if not params:
        return url

    separator = "&" if "?" in url else "?"
    return f"{url}{separator}{'&'.join(params)}"

def apply_area_range(
    url: str,
    area_min: int | None,
    area_max: int | None
) -> str:
    """Dodaje range powierzchni użytkowej do URL jeśli podano"""
    if area_min is None and area_max is None:
        return url

    params = []
    if area_min is not None:
        params.append(f"area.from={area_min}")
    if area_max is not None:
        params.append(f"area.to={area_max}")

    if not params:
        return url

    separator = "&" if "?" in url else "?"
    return f"{url}{separator}{'&'.join(params)}"

def apply_land_area_range(
    url: str,
    land_min: int | None,
    land_max: int | None
) -> str:
    """Dodaje range powierzchni działki do URL jeśli podano"""
    if land_min is None and land_max is None:
        return url

    params = []
    if land_min is not None:
        params.append(f"land_area.from={land_min}")
    if land_max is not None:
        params.append(f"land_area.to={land_max}")

    if not params:
        return url

    separator = "&" if "?" in url else "?"
    return f"{url}{separator}{'&'.join(params)}"

def apply_search_query(url: str, query: str | None) -> str:
    """Dodaje q=... (full-text search) do URL jeśli podano"""
    if not query:
        return url

    q = quote_plus(query.strip())
    separator = "&" if "?" in url else "?"
    return f"{url}{separator}q={q}"

def apply_bedrooms_range(
    url: str,
    bedrooms_min: int | None,
    bedrooms_max: int | None
) -> str:
    """Dodaje zakresy sypialni do URL jeśli podano"""
    if bedrooms_min is None and bedrooms_max is None:
        return url

    params = []
    if bedrooms_min is not None:
        params.append(f"bedrooms_quantity.from={bedrooms_min}")
    if bedrooms_max is not None:
        params.append(f"bedrooms_quantity.to={bedrooms_max}")

    if not params:
        return url

    separator = "&" if "?" in url else "?"
    return f"{url}{separator}{'&'.join(params)}"

def apply_bathrooms_range(
    url: str,
    bathrooms_min: int | None,
    bathrooms_max: int | None
) -> str:
    """Dodaje zakresy łazienek do URL jeśli podano"""
    if bathrooms_min is None and bathrooms_max is None:
        return url

    params = []
    if bathrooms_min is not None:
        params.append(f"bathrooms_quantity.from={bathrooms_min}")
    if bathrooms_max is not None:
        params.append(f"bathrooms_quantity.to={bathrooms_max}")

    if not params:
        return url

    separator = "&" if "?" in url else "?"
    return f"{url}{separator}{'&'.join(params)}"

def apply_sea_distance(url: str, sea_distances: list[str] | None) -> str:
    if not sea_distances:
        return url

    allowed = set(TRIPINVEST_SEA_DISTANCE.values())

    for d in sea_distances:
        if d not in allowed:
            raise ValueError(
                f"Nieznany sea_distance '{d}'. Dostępne: {list(allowed)}"
            )

    separator = "&" if "?" in url else "?"
    params = "&".join(f"sea_distance={d}" for d in sea_distances)

    return f"{url}{separator}{params}"


def apply_feature(url: str, features: list[str] | None) -> str:
    """Dodaje jedną lub wiele cech do URL (cecha=...)"""
    if not features:
        return url

    values = []
    for f in features:
        value = TRIPINVEST_FEATURES.get(f)
        if not value:
            raise ValueError(
                f"Nieznana cecha '{f}'. Dostępne: {list(TRIPINVEST_FEATURES)}"
            )
        values.append(value)

    separator = "&" if "?" in url else "?"
    params = "&".join(f"cecha={v}" for v in values)

    return f"{url}{separator}{params}"

def extract_pagination(soup: BeautifulSoup) -> tuple[int | None, int | None]:
    """
    Zwraca (current_page, total_pages)
    """
    form = soup.select_one("form.c-pagination-form")
    if not form:
        return None, None

    input_el = form.select_one("input[name='page']")
    span_el = form.select_one("span")

    current_page = int(input_el["value"]) if input_el and input_el.get("value") else None

    total_pages = None
    if span_el:
        # np. "z 556"
        m = re.search(r"z\s+(\d+)", span_el.get_text(strip=True))
        if m:
            total_pages = int(m.group(1))

    return current_page, total_pages









# =====================================================
# HELPERY DETAILS
# =====================================================

TRIPINVEST_OFFER_HOSTS = frozenset({"tripinvest.pl", "www.tripinvest.pl"})
TRIPINVEST_OFFER_PATH_PREFIX = "/oferta/"
MAX_TRIPINVEST_REDIRECTS = 5


class UnsafeTripinvestUrl(ValueError):
    """A URL that is not an https TripInvest address (SSRF guard)."""


def _require_tripinvest_https(url) -> str:
    text = str(url or "").strip()
    try:
        parts = urlsplit(text)
        port = parts.port
    except ValueError:
        raise UnsafeTripinvestUrl("Niepoprawny adres URL.") from None
    if (
        parts.scheme.lower() != "https"
        or parts.hostname not in TRIPINVEST_OFFER_HOSTS
        or parts.username is not None
        or parts.password is not None
        or port not in (None, 443)
    ):
        raise UnsafeTripinvestUrl("Dozwolone są tylko adresy https://tripinvest.pl.")
    return text


def validate_tripinvest_offer_url(url) -> str:
    """The URL when it is https://(www.)tripinvest.pl/oferta/<slug>, else UnsafeTripinvestUrl."""
    text = _require_tripinvest_https(url)
    path = urlsplit(text).path
    if not path.startswith(TRIPINVEST_OFFER_PATH_PREFIX) or len(path) <= len(TRIPINVEST_OFFER_PATH_PREFIX):
        raise UnsafeTripinvestUrl("To nie jest link do oferty TripInvest (/oferta/...).")
    return text


def fetch_html(url: str) -> BeautifulSoup:
    """Fetch a TripInvest offer page. The URL and every redirect target are
    validated before they are requested; redirects are never followed blindly."""
    current = validate_tripinvest_offer_url(url)
    for _ in range(MAX_TRIPINVEST_REDIRECTS + 1):
        response = requests.get(current, headers=HEADERS, timeout=15, allow_redirects=False)
        if response.is_redirect:
            current = _require_tripinvest_https(urljoin(current, response.headers["Location"]))
            continue
        response.raise_for_status()
        return BeautifulSoup(response.text, "html.parser")
    raise UnsafeTripinvestUrl("Zbyt wiele przekierowań.")


def extract_text(el):
    return el.get_text(strip=True) if el else None


def extract_int(text: str | None) -> int | None:
    if not text:
        return None
    m = re.search(r"\d+", text.replace("\xa0", " "))
    return int(m.group()) if m else None


def extract_price(text: str | None) -> int | None:
    """Parsuje pełną cenę, np. '385 000€' -> 385000"""
    if not text:
        return None
    cleaned = (
        text.replace("€", "")
            .replace("\xa0", "")
            .replace(" ", "")
    )
    return int(cleaned) if cleaned.isdigit() else None


def extract_ref_from_url(url: str) -> str | None:
    """Wyciąga ID / REF z końca URL"""
    m = re.search(r"-(\d+)$", url)
    return m.group(1) if m else None


def parse_location_from_title(title: str | None) -> str | None:
    """Fallback lokalizacji z tytułu"""
    if not title:
        return None
    if "," in title:
        return title.split(",", 1)[1].strip()
    return None