import requests, re, time, random, json
from bs4 import BeautifulSoup
from common.request_logger import log_request_result

def scrape_olx_real_estate(location="kedzierzyn-kozle", distance=0, private_only=True,
                            save_to_json=True, filename="olx_nieruchomosci.json", max_pages=None):
    """
    Scraper ofert nieruchomości z OLX dla podanej lokalizacji i promienia.

    Args:
        location (str): lokalizacja w URL (np. "kedzierzyn-kozle").
        distance (int): promień wyszukiwania w km (0 = brak ograniczenia).
        private_only (bool): True = tylko oferty prywatne, False = wszystkie.
        save_to_json (bool): czy zapisać dane do pliku JSON.
        filename (str): nazwa pliku JSON do zapisu.
        max_pages (int or None): maksymalna liczba stron do pobrania (None = wszystkie).

    Returns:
        list of dict: Lista ogłoszeń.
    """
    base_url = f"https://www.olx.pl/nieruchomosci/{location}/"
    params = "?search%5Border%5D=created_at:desc"
    if distance > 0:
        params += f"&search%5Bdist%5D={distance}"
    if private_only:
        params += "&search%5Bprivate_business%5D=private"

    headers = {'User-Agent': 'Mozilla/5.0'}
    response = requests.get(base_url + params, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    pagination_links = soup.find_all("a", attrs={"data-testid": re.compile(r"^pagination-link-\d+")})
    page_numbers = [int(link.text.strip()) for link in pagination_links if link.text.strip().isdigit()]
    max_page = max(page_numbers) if page_numbers else 1
    if max_pages:
        max_page = min(max_page, max_pages)

    data = []
    page_times = []

    print("⏳ Rozpoczynam scrapowanie...\n")

    for page in range(1, max_page + 1):
        print(f"📄 Pobieram stronę {page}/{max_page}...")
        start_time = time.time()

        page_url = f"{base_url}?page={page}{params.replace('?', '&')}"
        req_start = time.time()
        response = requests.get(page_url, headers=headers)
        req_elapsed = time.time() - req_start
        log_request_result(page_url, response.status_code, req_elapsed)

        soup = BeautifulSoup(response.text, 'html.parser')
        offers = soup.select('div[data-testid="l-card"]')

        for offer in offers:
            title_tag = offer.select_one('h4')
            title = title_tag.text.strip() if title_tag else None

            price_tag = offer.select_one('[data-testid="ad-price"]')
            price = price_tag.text.strip() if price_tag else None

            location_tag = offer.select_one('[data-testid="location-date"]')
            location_date = location_tag.text.strip() if location_tag else None

            link_tag = offer.select_one('a[href]')
            link = link_tag['href'] if link_tag else None
            if link and link.startswith('/'):
                link = 'https://www.olx.pl' + link

            size = None
            param_container = offer.select_one('.css-odp1qd')
            if param_container:
                for span in param_container.find_all('span'):
                    if 'm²' in span.text:
                        size = span.text.strip()
                        break

            data.append({
                'Tytuł': title,
                'Cena': price,
                'Lokalizacja i data': location_date,
                'Metraż': size,
                'Link': link
            })

        elapsed = time.time() - start_time
        page_times.append(elapsed)
        print(f"⏱️ Czas pobierania strony {page}: {elapsed:.2f} s")

        time.sleep(random.uniform(2.0, 5.0))

    total_time = sum(page_times)
    num_offers = len(data)
    offers_per_sec = num_offers / total_time if total_time > 0 else 0

    print("\n📊 Podsumowanie scrapowania:")
    print(f"🔢 Liczba ofert: {num_offers}")
    print(f"⏲️ Całkowity czas pobierania: {total_time:.2f} s")
    print(f"⚡ Wydajność: {offers_per_sec:.2f} ofert/sekundę")

    if save_to_json:
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    return data
