import requests
from bs4 import BeautifulSoup
import re
import json
import time
from typing import List, Dict

# =========================
# CONFIG
# =========================
BASE_URL = "https://avartenproperties.com/pl/search-results"
MIN_PRICE = 450_000
MAX_PRICE = 50_000_000
SLEEP_BETWEEN_PAGES = 1.5

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}

# =========================
# URL BUILDER
# =========================
def build_url(page: int, min_price: int, max_price: int) -> str:
    if page == 1:
        return f"{BASE_URL}/?min-price={min_price}&max-price={max_price}"
    return f"{BASE_URL}/page/{page}/?min-price={min_price}&max-price={max_price}"

# =========================
# FETCH HTML
# =========================
def fetch_html(page: int) -> str:
    url = build_url(page, MIN_PRICE, MAX_PRICE)
    print(f"Fetching: {url}")
    response = requests.get(url, headers=HEADERS, timeout=20)
    response.raise_for_status()
    return response.text

# =========================
# PARSE MAX PAGES
# =========================
def get_max_pages(html: str) -> int:
    soup = BeautifulSoup(html, "html.parser")
    pages = []

    for a in soup.select(".pagination a.page-link"):
        try:
            pages.append(int(a.get_text(strip=True)))
        except ValueError:
            continue

    return max(pages) if pages else 1

# =========================
# PARSE LISTINGS
# =========================
def parse_listings(html: str):
    soup = BeautifulSoup(html, "html.parser")
    results = []

    for item in soup.select("div.item-listing-wrap"):
        offer_id = item.get("data-hz-id")

        # LISTING ID (numeric)
        listing_id = None
        email_btn = item.select_one("button[data-model-id]")
        if email_btn:
            listing_id = int(email_btn["data-model-id"].split("-")[-1])

        # TITLE + URL
        title = None
        url = None
        title_link = item.select_one(".item-title a[href]")
        if title_link:
            title = title_link.get_text(strip=True)
            url = title_link["href"]

        # STATUS
        status = None
        status_tag = item.select_one(".label-status")
        if status_tag:
            status = status_tag.get_text(strip=True)

        # FEATURED / LABELS
        labels = []

        featured_tag = item.select_one(".label-featured")
        if featured_tag:
            labels.append(featured_tag.get_text(strip=True))
            
        # PROPERTY TYPE
        property_type = []
        type_tag = item.select_one(".h-type span")
        if type_tag:
            property_type = [t.strip() for t in type_tag.text.split(",")]

        # PRICE
        price_from = None
        currency = None
        price_tag = item.select_one(".item-price")
        if price_tag:
            price_text = price_tag.get_text(" ", strip=True)
            match = re.search(r"([\d,]+)\s*(AED)", price_text)
            if match:
                price_from = int(match.group(1).replace(",", ""))
                currency = match.group(2)

        # BEDS / BATHS (RAW ONLY)
        beds_raw = None
        baths_raw = None

        beds_tag = item.select_one(".h-beds .hz-figure")
        baths_tag = item.select_one(".h-baths .hz-figure")

        if beds_tag:
            beds_raw = beds_tag.get_text(strip=True)

        if baths_tag:
            baths_raw = baths_tag.get_text(strip=True)

        # LOCATION
        location = None
        address_tag = item.select_one(".item-address")
        if address_tag:
            location = address_tag.get_text(strip=True)

        # IMAGES
        images_raw = item.get("data-images")
        try:
            images = json.loads(images_raw) if images_raw else []
        except json.JSONDecodeError:
            images = []

        results.append({
            "offer_id": offer_id,
            "listing_id": listing_id,
            "title": title,
            "url": url,
            "status": status,
            "labels": labels,
            "property_type": property_type,
            "price_from": price_from,
            "currency": currency,
            "beds_raw": beds_raw,
            "baths_raw": baths_raw,
            "location": location,
            "images": images
        })

    return results
