#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import re
import sys
from collections import deque
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Optional
from urllib.parse import urljoin, urlparse

import requests
from bs4 import BeautifulSoup

USER_AGENT = (
    "Mozilla/5.0 (X11; Linux x86_64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) "
    "Chrome/150 Safari/537.36"
)
TIMEOUT = 25
MAX_JS_FILES = 250

DATA_MARKERS = (
    "netArea",
    "grossArea",
    "availability",
    "installments",
    "floorPlanImage",
    "sitePlanImage",
)

OBJECT_REQUIRED_KEYS = ("id", "title", "netArea", "grossArea")


@dataclass
class UnitType:
    external_id: Optional[str]
    title: Optional[str]
    phase_title: Optional[str]
    description: Optional[str]
    status: Optional[str]
    availability_text: Optional[str]
    available_units: Optional[int]
    net_area_text: Optional[str]
    net_area_m2: Optional[float]
    gross_area_text: Optional[str]
    gross_area_m2: Optional[float]
    features: list[str]
    price_text: Optional[str]
    price: Optional[float]
    currency: Optional[str]
    installments: Optional[str]
    image_src: Optional[str]
    site_plan_image: Optional[str]
    floor_plan_image: Optional[str]
    gallery: list[str]
    # The key of the bundle group the unit type sits in, e.g. "Phase I" in
    # {"Phase I": [{id: ...}, ...], "Phase II": [...]}. It is NOT phase_title (a
    # per-unit display string) and, with external_id, it makes a unit type unique:
    # external_id alone repeats between groups ("type-a" in every phase). None when
    # the unit types are a plain array with no group key; nothing is invented then.
    phase_group_key: Optional[str] = None


def make_session() -> requests.Session:
    s = requests.Session()
    s.headers.update({
        "User-Agent": USER_AGENT,
        "Accept": "*/*",
        "Accept-Language": "pl-PL,pl;q=0.9,en;q=0.8",
        "Cache-Control": "no-cache",
    })
    return s


_TEXT_CACHE: dict[str, str] = {}


def clear_text_cache() -> None:
    """Forget every page/bundle fetched so far (get_text never expires them on its own)."""
    _TEXT_CACHE.clear()


def get_text(s: requests.Session, url: str) -> str:
    cached = _TEXT_CACHE.get(url)
    if cached is not None:
        return cached

    r = s.get(url, timeout=TIMEOUT)
    r.raise_for_status()
    r.encoding = "utf-8"
    text = r.text
    _TEXT_CACHE[url] = text
    return text

def extract_json_ld_listing(html: str) -> Optional[dict]:
    """The project's schema.org RealEstateListing from the prerendered page, or None.

    Carries the clean project name and the address the site publishes for SEO
    (name, address_locality, address_region, address_country; only keys that are
    present). It is the source's own structured data, unlike project.name below,
    which is a heuristic over unit titles or the URL slug.
    """
    soup = BeautifulSoup(html or "", "html.parser")
    for tag in soup.find_all("script", type="application/ld+json"):
        try:
            data = json.loads(tag.string or tag.get_text() or "")
        except ValueError:
            continue
        for item in data if isinstance(data, list) else [data]:
            if not isinstance(item, dict):
                continue
            kinds = item.get("@type")
            if "RealEstateListing" not in (kinds if isinstance(kinds, list) else [kinds]):
                continue
            address = item.get("address") if isinstance(item.get("address"), dict) else {}

            def clean(value):
                return " ".join(value.split()) if isinstance(value, str) and value.strip() else None

            found = {
                "name": clean(item.get("name")),
                "address_locality": clean(address.get("addressLocality")),
                "address_region": clean(address.get("addressRegion")),
                "address_country": clean(address.get("addressCountry")),
            }
            return {key: value for key, value in found.items() if value}
    return None


def project_hint_from_url(page_url: str) -> str:
    slug = Path(urlparse(page_url).path).name
    return re.split(r"[_-]", slug, maxsplit=1)[0].lower()


def find_initial_script_urls(html: str, page_url: str) -> list[str]:
    soup = BeautifulSoup(html, "html.parser")
    result: list[str] = []

    for tag in soup.find_all("script", src=True):
        src = tag.get("src")
        if src:
            full = urljoin(page_url, src)
            if full not in result:
                result.append(full)

    for tag in soup.find_all("link", href=True):
        rel = " ".join(tag.get("rel") or [])
        href = tag.get("href")
        if href and ("modulepreload" in rel or href.endswith(".js")):
            full = urljoin(page_url, href)
            if full not in result:
                result.append(full)

    return result


JS_REF_RE = re.compile(r"""["']([^"'?#\s]+\.js(?:\?[^"']*)?)["']""", re.I)


def find_js_references(js_text: str, current_url: str, origin_host: str) -> list[str]:
    found: list[str] = []
    parsed_current = urlparse(current_url)
    origin = f"{parsed_current.scheme}://{parsed_current.netloc}"

    for raw in JS_REF_RE.findall(js_text):
        raw = raw.strip()

        if raw.startswith(("http://", "https://")):
            full = raw
        elif raw.startswith("/"):
            full = urljoin(origin + "/", raw)
        elif raw.startswith("assets/"):
            # Vite entry itself already lives under /assets/. Resolve this
            # form from the site root, otherwise we'd get /assets/assets/...
            full = urljoin(origin + "/", raw)
        else:
            full = urljoin(current_url, raw)

        parsed = urlparse(full)
        if parsed.scheme not in ("http", "https"):
            continue
        if parsed.netloc != origin_host:
            continue
        if full not in found:
            found.append(full)

    return found

def bundle_score(text: str, url: str, project_hint: str) -> int:
    score = sum(2 for marker in DATA_MARKERS if marker in text)
    name = Path(urlparse(url).path).name.lower()

    if "detailpage" in name:
        score += 8
    if project_hint and project_hint in name:
        score += 8
    if project_hint and project_hint in text.lower():
        score += 2
    if "netArea" in text and "grossArea" in text:
        score += 5
    return score


def discover_project_bundle(
    s: requests.Session,
    project_url: str,
    initial_scripts: list[str],
    debug: bool = False,
) -> tuple[str, str]:
    parsed_project = urlparse(project_url)
    origin_host = parsed_project.netloc
    slug = Path(parsed_project.path).name.lower()
    project_hint = re.split(r"[_&-]", slug, maxsplit=1)[0].lower()

    # Filename aliases used by the site's Vite chunks.
    # Example: route /Hawaii_homes -> DetailPageHawai-*.js.
    hint_aliases = {project_hint}
    if project_hint == "hawaii":
        hint_aliases.add("hawai")

    # FAST PATH:
    # Vite's main entry contains lazy-import references to DetailPage*.js.
    # Find the chunk whose filename matches the requested project and fetch
    # that chunk directly. This avoids walking hundreds of unrelated assets.
    entry_texts: list[tuple[str, str]] = []

    for entry_url in initial_scripts:
        try:
            entry_js = get_text(s, entry_url)
        except requests.RequestException as exc:
            if debug:
                print(f"[CC] Entry fetch failed: {entry_url}: {exc}")
            continue

        entry_texts.append((entry_url, entry_js))
        if debug:
            print(
                f"[CC] entry: {Path(urlparse(entry_url).path).name}"
            )

        refs = find_js_references(entry_js, entry_url, origin_host)
        matching = [
            ref for ref in refs
            if "detailpage" in ref.lower()
            and any(
                hint in Path(urlparse(ref).path).name.lower()
                for hint in hint_aliases
            )
        ]

        if matching:
            # Prefer the strongest filename match.
            matching.sort(
                key=lambda u: (
                    not any(
                        Path(urlparse(u).path).name.lower().startswith(
                            f"detailpage{hint}"
                        )
                        for hint in hint_aliases
                    ),
                    u.lower(),
                )
            )
            candidate_url = matching[0]
            candidate_js = get_text(s, candidate_url)

            if debug:
                print(
                    f"[CC] direct match: "
                    f"{Path(urlparse(candidate_url).path).name}"
                )

            if all(
                marker in candidate_js
                for marker in ("netArea", "grossArea", "availability")
            ):
                return candidate_url, candidate_js

    # FALLBACK:
    # Naming/layout may change in the future. Walk the JS graph, but only
    # then, and prefer project-matching chunks. Use the correctly named
    # bundle_score(text, url, project_hint) helper.
    queue = deque()
    queued: set[str] = set()
    visited: set[str] = set()

    for entry_url, entry_js in entry_texts:
        for ref in find_js_references(entry_js, entry_url, origin_host):
            if ref not in queued:
                queued.add(ref)
                queue.append(ref)

    best_any: Optional[tuple[int, str, str]] = None
    best_matching: Optional[tuple[int, str, str]] = None

    while queue and len(visited) < MAX_JS_FILES:
        current_url = queue.popleft()
        if current_url in visited:
            continue
        visited.add(current_url)

        try:
            js = get_text(s, current_url)
        except requests.RequestException:
            continue

        score = bundle_score(js, current_url, project_hint)

        if debug:
            print(
                f"[CC] fallback JS {len(visited):03d} score={score:02d} "
                f"{Path(urlparse(current_url).path).name}"
            )

        has_data = all(
            marker in js for marker in ("netArea", "grossArea", "availability")
        )
        matches_project = any(hint in current_url.lower() for hint in hint_aliases)

        if has_data:
            candidate = (score, current_url, js)
            if best_any is None or score > best_any[0]:
                best_any = candidate
            if matches_project:
                if best_matching is None or score > best_matching[0]:
                    best_matching = candidate
                if "detailpage" in current_url.lower():
                    return current_url, js

        refs = find_js_references(js, current_url, origin_host)
        refs.sort(
            key=lambda u: (
                not any(hint in u.lower() for hint in hint_aliases),
                "detailpage" not in u.lower(),
                u.lower(),
            )
        )
        for ref in refs:
            if ref not in queued and ref not in visited:
                queued.add(ref)
                queue.append(ref)

    if best_matching is not None:
        return best_matching[1], best_matching[2]
    if best_any is not None:
        return best_any[1], best_any[2]

    raise RuntimeError(
        f"Nie znalazłem bundle projektu po przejrzeniu "
        f"{len(visited)} plików JS w fallback."
    )

def find_object_start(text: str, position: int) -> Optional[int]:
    i = position
    while i >= 0:
        if text[i] == "{":
            return i
        i -= 1
    return None


def _extract_balanced(text: str, start: int, open_ch: str, close_ch: str) -> Optional[str]:
    if start < 0 or start >= len(text) or text[start] != open_ch:
        return None

    depth = 0
    quote: Optional[str] = None
    escaped = False

    for i in range(start, len(text)):
        ch = text[i]

        if quote is not None:
            if escaped:
                escaped = False
            elif ch == "\\":
                escaped = True
            elif ch == quote:
                quote = None
            continue

        if ch in ('"', "'", "`"):
            quote = ch
        elif ch == open_ch:
            depth += 1
        elif ch == close_ch:
            depth -= 1
            if depth == 0:
                return text[start:i + 1]

    return None


def extract_balanced_object(text: str, start: int) -> Optional[str]:
    return _extract_balanced(text, start, "{", "}")


def extract_balanced_array(text: str, start: int) -> Optional[str]:
    return _extract_balanced(text, start, "[", "]")


def js_unescape(value: str) -> str:
    return (
        value.replace(r"\/", "/")
        .replace(r'\"', '"')
        .replace(r"\'", "'")
        .replace(r"\\", "\\")
        .replace(r"\n", "\n")
        .replace(r"\r", "\r")
        .replace(r"\t", "\t")
    )


def string_field(obj: str, key: str) -> Optional[str]:
    pattern = re.compile(
        rf'(?:^|[{{,])\s*{re.escape(key)}\s*:\s*(["\'`])(.*?)\1',
        re.S,
    )
    m = pattern.search(obj)
    return js_unescape(m.group(2)).strip() if m else None


def array_field(obj: str, key: str) -> list[str]:
    m = re.search(
        rf'(?:^|[{{,])\s*{re.escape(key)}\s*:\s*\[(.*?)\]',
        obj,
        re.S,
    )
    if not m:
        return []

    return [
        js_unescape(sm.group(2)).strip()
        for sm in re.finditer(r'(["\'`])(.*?)(?<!\\)\1', m.group(1), re.S)
    ]


def number_from_text(value: Optional[str]) -> Optional[float]:
    if not value:
        return None
    cleaned = (
        value.replace("\xa0", " ")
        .replace(",", "")
        .replace("m²", "")
        .replace("m2", "")
        .strip()
    )
    m = re.search(r"-?\d+(?:\.\d+)?", cleaned)
    if not m:
        return None
    n = float(m.group(0))
    return int(n) if n.is_integer() else n


def available_units(value: Optional[str]) -> Optional[int]:
    if not value:
        return None
    m = re.search(r"\b(\d+)\b", value)
    if m:
        return int(m.group(1))
    low = value.lower()
    if "sold out" in low or "not available" in low:
        return 0
    return None


def parse_price(value: Optional[str]) -> tuple[Optional[float], Optional[str]]:
    if not value or "sold out" in value.lower():
        return None, None

    currency = (
        "GBP" if "£" in value else
        "EUR" if "€" in value else
        "USD" if "$" in value else
        None
    )
    return number_from_text(value), currency


def object_is_unit(obj: str) -> bool:
    return all(re.search(rf"\b{re.escape(k)}\s*:", obj) for k in OBJECT_REQUIRED_KEYS)


# `"Phase I": [{` / `Phase1: [{` : a property key that owns an array whose first element is an object.
_GROUP_OPENER_RE = re.compile(
    r"""(?P<key>"(?:[^"\\\n]|\\.){1,200}"|'(?:[^'\\\n]|\\.){1,200}'|`(?:[^`\\\n]|\\.){1,200}`|[A-Za-z_$][\w$]*)"""
    r"""\s*:\s*\[\s*\{"""
)


def _unquote_key(raw: str) -> str:
    if raw and raw[0] in "\"'`" and raw[-1] == raw[0]:
        return js_unescape(raw[1:-1])
    return raw


def _find_unit_groups(bundle: str) -> list[tuple[int, int, str]]:
    """(array start, array end, key) of every `key: [ {unit}, ... ]` group in the bundle."""
    groups: list[tuple[int, int, str]] = []
    for m in _GROUP_OPENER_RE.finditer(bundle):
        array_start = bundle.index("[", m.end("key"))
        first_object_start = bundle.index("{", array_start)
        first_object = extract_balanced_object(bundle, first_object_start)
        if not first_object or not object_is_unit(first_object):
            continue
        array = extract_balanced_array(bundle, array_start)
        if array:
            groups.append((array_start, array_start + len(array), _unquote_key(m.group("key"))))
    return groups


def extract_unit_records(bundle: str) -> list[tuple[Optional[str], str]]:
    """(phase_group_key, unit object source) in source order.

    The group key is the key of the innermost keyed array holding the object, or
    None for unit types that are a plain array. Byte-identical objects are skipped
    only within the same group (the same text in two groups is two unit types).
    """
    groups = _find_unit_groups(bundle)
    records: list[tuple[Optional[str], str]] = []
    seen: set[tuple[Optional[str], str]] = set()

    for m in re.finditer(r'\bid\s*:\s*(["\'`])', bundle):
        start = find_object_start(bundle, m.start())
        if start is None:
            continue

        obj = extract_balanced_object(bundle, start)
        if not obj or len(obj) > 50_000 or not object_is_unit(obj):
            continue

        holding = [g for g in groups if g[0] < start < g[1]]
        group_key = min(holding, key=lambda g: g[1] - g[0])[2] if holding else None

        if (group_key, obj) not in seen:
            seen.add((group_key, obj))
            records.append((group_key, obj))

    return records


def extract_unit_objects(bundle: str) -> list[str]:
    return [obj for _, obj in extract_unit_records(bundle)]


def parse_unit(obj: str, phase_group_key: Optional[str] = None) -> UnitType:
    price_text = string_field(obj, "price")
    price, currency = parse_price(price_text)
    net_text = string_field(obj, "netArea")
    gross_text = string_field(obj, "grossArea")
    availability_text = string_field(obj, "availability")

    return UnitType(
        external_id=string_field(obj, "id"),
        title=string_field(obj, "title"),
        phase_title=string_field(obj, "phaseTitle"),
        description=string_field(obj, "description"),
        status=string_field(obj, "status"),
        availability_text=availability_text,
        available_units=available_units(availability_text),
        net_area_text=net_text,
        net_area_m2=number_from_text(net_text),
        gross_area_text=gross_text,
        gross_area_m2=number_from_text(gross_text),
        features=array_field(obj, "features"),
        price_text=price_text,
        price=price,
        currency=currency,
        installments=string_field(obj, "installments"),
        image_src=string_field(obj, "imageSrc"),
        site_plan_image=string_field(obj, "sitePlanImage"),
        floor_plan_image=string_field(obj, "floorPlanImage"),
        gallery=array_field(obj, "gallery"),
        phase_group_key=phase_group_key,
    )


def guess_project_name(units: list[UnitType], fallback_url: str) -> str:
    if units and units[0].title:
        m = re.match(
            r"(.+?)\s+Phase\s+[IVXLC0-9]+(?:\s|$)",
            units[0].title,
            re.I,
        )
        if m:
            return m.group(1).strip()

    slug = Path(urlparse(fallback_url).path).name
    return slug.replace("_", " ").strip() or "Unknown project"



GENERIC_ROUTES = {
    "", "all-projects", "blog", "booking", "guest-login", "about-us",
    "properties", "pre-arrival", "wellness-fitness", "facilities", "dining",
    "help-center", "login", "privacy-policy", "north-cyprus-real-estate-guide",
    "property-investment-in-north-cyprus", "how-to-buy-property-in-north-cyprus",
    "title-deed-process-north-cyprus", "residency-by-property-investment-cyprus",
    "rental-income-guide", "taxes-on-property-in-north-cyprus",
    "property-for-sale-kyrenia", "property-for-sale-bahceli",
    "property-for-sale-esentepe", "property-for-sale-famagusta",
    "property-for-sale-edremit", "seafront-property-north-cyprus",
    "luxury-villas-north-cyprus", "apartments-for-sale",
    "off-plan-property", "resale-property",
}

PROJECT_SLUG_RE = re.compile(r"(?:homes?|villas?|resort|island)", re.I)
ROUTE_STRING_RE = re.compile(r"[\"'](/[^\"'?#\s]+)[\"']")


def normalize_project_url(base_url: str, raw_href: str) -> Optional[str]:
    raw = (raw_href or "").strip()
    if not raw:
        return None

    # Ignore obvious asset/file/module strings.
    low = raw.lower()
    if (
        low.startswith(("http://", "https://", "mailto:", "tel:", "#"))
        and urlparse(raw).netloc
        and urlparse(raw).netloc != urlparse(base_url).netloc
    ):
        return None
    if any(
        low.endswith(ext)
        for ext in (
            ".js", ".css", ".json", ".png", ".jpg", ".jpeg", ".webp",
            ".svg", ".woff", ".woff2", ".ttf", ".ico"
        )
    ):
        return None

    # Router definitions often contain bare slugs such as "Aloha_homes"
    # instead of href="/Aloha_homes".
    if not raw.startswith(("/", "http://", "https://")):
        raw = "/" + raw.lstrip("./")

    full = urljoin(base_url, raw)
    parsed = urlparse(full)

    if parsed.netloc != urlparse(base_url).netloc:
        return None

    parts = [p for p in parsed.path.split("/") if p]
    if parts and parts[0] in {"en", "tr", "ar", "pl", "ru", "fa"}:
        parts = parts[1:]

    if len(parts) != 1:
        return None

    slug = parts[0]
    if slug.lower() in GENERIC_ROUTES:
        return None
    if not PROJECT_SLUG_RE.search(slug):
        return None

    base = urlparse(base_url)
    lang_parts = [p for p in base.path.split("/") if p]
    lang = (
        lang_parts[0]
        if lang_parts and lang_parts[0] in {"en", "tr", "ar", "pl", "ru", "fa"}
        else "pl"
    )

    return f"{base.scheme}://{base.netloc}/{lang}/{slug}"

def discover_project_urls(
    s: requests.Session,
    all_projects_url: str,
    debug: bool = False,
) -> list[str]:
    html = get_text(s, all_projects_url)
    urls: set[str] = set()

    soup = BeautifulSoup(html, "html.parser")
    for a in soup.find_all("a", href=True):
        u = normalize_project_url(all_projects_url, a.get("href"))
        if u:
            urls.add(u)

    initial = find_initial_script_urls(html, all_projects_url)

    for entry_url in initial:
        try:
            js = get_text(s, entry_url)
        except requests.RequestException as exc:
            if debug:
                print(f"[CC] Entry fetch failed: {entry_url}: {exc}")
            continue

        # 1) Extract quoted route tokens from the entry bundle. This catches
        # "/Aloha_homes", "Aloha_homes", "/pl/Aloha_homes", etc.
        for raw in ROUTE_STRING_RE.findall(js):
            u = normalize_project_url(all_projects_url, raw)
            if u:
                urls.add(u)

        # 2) The current site exposes all project DetailPage chunks from the
        # entry bundle. If router strings are minified differently, use the
        # chunk names as a fast fallback instead of crawling the whole graph.
        if not urls:
            refs = find_js_references(js, entry_url, urlparse(all_projects_url).netloc)

            exceptional = {
                "pearl": "pearl_island",
                "phuket": "Phuket_H&W_Resort",
                "edremit": "edremit_villas",
                "moonlight": "moonlight_villas",
            }

            for ref in refs:
                filename = Path(urlparse(ref).path).name
                m = re.match(r"DetailPage([A-Za-z0-9]+)-", filename, re.I)
                if not m:
                    continue

                name = m.group(1)
                key = name.lower()
                slug = exceptional.get(key)

                if slug is None:
                    # Most current project routes use *_homes.
                    slug = f"{name}_homes"

                u = normalize_project_url(all_projects_url, slug)
                if u:
                    urls.add(u)

    result = sorted(urls, key=lambda u: Path(urlparse(u).path).name.lower())

    if debug:
        print(f"[CC] Project URLs discovered: {len(result)}")
        for u in result:
            print(f"[CC] project: {u}")

    return result

def quality_warnings(unit: UnitType) -> list[dict]:
    warnings: list[dict] = []
    price_low = (unit.price_text or "").lower()
    installments_low = (unit.installments or "").lower()

    if unit.available_units is not None and unit.available_units > 0 and "sold out" in price_low:
        warnings.append({
            "code": "AVAILABILITY_PRICE_CONFLICT",
            "message": (
                f"Availability says {unit.available_units} unit(s) available, "
                f"but price says {unit.price_text}."
            ),
        })

    if unit.available_units == 0 and unit.status and unit.status.lower() == "available":
        warnings.append({
            "code": "STATUS_AVAILABILITY_CONFLICT",
            "message": "Status says Available, but availability is 0.",
        })

    if unit.available_units == 0 and unit.installments and "sold out" not in installments_low:
        warnings.append({
            "code": "ZERO_AVAILABLE_PAYMENT_PLAN_PRESENT",
            "message": "Availability is 0, but payment-plan text does not say Sold Out.",
        })

    if not unit.external_id:
        warnings.append({
            "code": "MISSING_EXTERNAL_ID",
            "message": "Unit type has no external id.",
        })

    if unit.net_area_m2 is None or unit.gross_area_m2 is None:
        warnings.append({
            "code": "MISSING_AREA",
            "message": "Net or gross area could not be normalized.",
        })

    return warnings



def language_from_url(url: str) -> str:
    parts = [p for p in urlparse(url).path.split("/") if p]
    supported = {"ar", "en", "fa", "pl", "ru", "tr"}
    return parts[0] if parts and parts[0] in supported else "en"


def site_origin(url: str) -> str:
    p = urlparse(url)
    return f"{p.scheme}://{p.netloc}"


def get_json(s: requests.Session, url: str):
    r = s.get(url, timeout=TIMEOUT)
    r.raise_for_status()
    r.encoding = "utf-8"
    return r.json()


def deep_get(data, dotted_key: str):
    cur = data
    for part in dotted_key.split("."):
        if not isinstance(cur, dict) or part not in cur:
            return None
        cur = cur[part]
    return cur


def abs_asset(origin: str, value):
    if not isinstance(value, str) or not value:
        return value
    if value.startswith(("http://", "https://", "data:")):
        return value
    if value.startswith("/"):
        return urljoin(origin + "/", value.lstrip("/"))
    return value


def absolutize_assets(value, origin: str):
    if isinstance(value, list):
        return [absolutize_assets(x, origin) for x in value]

    if isinstance(value, dict):
        result = {}
        for k, v in value.items():
            if (
                isinstance(v, str)
                and (
                    k.lower() in {
                        "image", "imagesrc", "iconsrc", "src",
                        "coverimage", "thumbnail", "previewimage"
                    }
                    or re.search(
                        r"\.(?:png|jpe?g|webp|svg|gif)(?:\?.*)?$",
                        v,
                        re.I,
                    )
                )
            ):
                result[k] = abs_asset(origin, v)
            else:
                result[k] = absolutize_assets(v, origin)
        return result

    return value


def referenced_translation_keys(bundle: str) -> set[str]:
    keys: set[str] = set()

    return_objects_re = re.compile(
        r'''\b[A-Za-z_$][\w$]*\(\s*(["'`])([^"'`]+)\1\s*,\s*\{[^{}]{0,200}returnObjects\s*:\s*!0''',
        re.S,
    )
    direct_re = re.compile(
        r'''\b[A-Za-z_$][\w$]*\(\s*(["'`])([^"'`]+)\1\s*\)'''
    )

    for m in return_objects_re.finditer(bundle):
        keys.add(m.group(2))

    for m in direct_re.finditer(bundle):
        key = m.group(2)
        low = key.lower()
        if any(
            token in low
            for token in (
                "projectoverview",
                "amenities",
                "gallery",
                "location",
                "payment",
                "faq",
            )
        ):
            keys.add(key)

    return keys


def find_project_card(
    translation: dict,
    project_url: str,
    origin: str,
    language: str,
) -> Optional[dict]:
    projects_root = deep_get(translation, "projectsPage.projects")
    if not isinstance(projects_root, dict):
        return None

    target_slug = Path(urlparse(project_url).path).name.lower()

    for status in ("ongoing", "completed"):
        items = projects_root.get(status)
        if not isinstance(items, list):
            continue

        for item in items:
            if not isinstance(item, dict):
                continue

            raw_link = (
                item.get("link")
                or item.get("url")
                or item.get("path")
                or item.get("href")
            )
            if not isinstance(raw_link, str):
                continue

            path = raw_link
            if not path.startswith(("http://", "https://")):
                path = "/" + path.lstrip("/")
                parts = [p for p in path.split("/") if p]
                if not parts or parts[0] not in {"ar", "en", "fa", "pl", "ru", "tr"}:
                    path = f"/{language}{path}"

            full = (
                path
                if path.startswith(("http://", "https://"))
                else urljoin(origin + "/", path.lstrip("/"))
            )

            if Path(urlparse(full).path).name.lower() != target_slug:
                continue

            result = dict(item)
            result["status"] = status
            result["project_url"] = full

            for image_key in ("image", "coverImage", "thumbnail"):
                if image_key in result:
                    result[image_key] = abs_asset(origin, result[image_key])

            return result

    return None


def select_section(
    translation: dict,
    keys: set[str],
    prefixes: tuple[str, ...],
    project_url: Optional[str] = None,
):
    """
    Deterministic selection.

    Only translation keys explicitly referenced by this project's
    DetailPage bundle are eligible. Never search all of translation.json
    as a fallback, because that can leak data from another project
    (e.g. amenitiesAloha into Edremit/Pearl/etc.).
    """
    candidates = []

    for key in sorted(keys):
        top = key.split(".", 1)[0]
        if not any(top.lower().startswith(p.lower()) for p in prefixes):
            continue

        value = translation.get(top)
        if value is not None:
            candidates.append((top, value))

    if not candidates:
        return None, None

    # Prefer a project-specific key when the bundle references both a
    # specific and a generic/shared key. Otherwise keep the generic key:
    # if the bundle explicitly references "gallery" or "faq", that is
    # valid source behavior and should not be "corrected".
    hint = ""
    aliases: set[str] = set()

    if project_url:
        slug = Path(urlparse(project_url).path).name.lower()
        hint = re.split(r"[_&-]", slug, maxsplit=1)[0].lower()
        aliases.add(hint)
        if hint == "hawaii":
            aliases.add("hawai")
        if hint == "pearl":
            aliases.add("pearl")
        if hint == "phuket":
            aliases.add("phuket")

    def rank(item):
        key = item[0].lower()
        specific = bool(aliases) and any(alias in key for alias in aliases)
        return (not specific, len(key), key)

    candidates.sort(key=rank)
    return candidates[0]



def extract_map_coordinates(bundle: str) -> dict[str, float] | None:
    """
    Extract the actual project marker coordinates from a DetailPage bundle.

    Priority:
    1) A coordinate array assigned to a JS variable that is later used as:
         lat:<var>[0], lng:<var>[1]
       This matches pages such as Maldives:
         c=[35.3323,33.9]
         ...
         lat:c[0],lng:c[1]

    2) A direct Leaflet marker:
         marker([35.x,33.x], ...)

    3) A direct project object containing numeric lat/lng.

    Explicitly avoid generic map viewport centers such as:
         setView([35.225,33.57],9)
    """

    num_lat = r"3[45]\.\d{1,8}"
    num_lng = r"3[234]\.\d{1,8}"

    # ------------------------------------------------------------------
    # 1) Variable-backed project coordinate:
    #    c=[35.3323,33.9] ... lat:c[0],lng:c[1]
    # ------------------------------------------------------------------
    assignment_re = re.compile(
        rf'(?P<var>[A-Za-z_$][\w$]*)\s*=\s*'
        rf'\[\s*(?P<lat>{num_lat})\s*,\s*(?P<lng>{num_lng})\s*\]'
    )

    for m in assignment_re.finditer(bundle):
        var = re.escape(m.group("var"))

        # Search forward in a reasonably local region. Minified project
        # components normally use the coordinate variable shortly after assignment.
        tail = bundle[m.end(): m.end() + 5000]

        usage_patterns = (
            rf'\blat\s*:\s*{var}\s*\[\s*0\s*\]\s*,\s*\blng\s*:\s*{var}\s*\[\s*1\s*\]',
            rf'\blng\s*:\s*{var}\s*\[\s*1\s*\]\s*,\s*\blat\s*:\s*{var}\s*\[\s*0\s*\]',
        )

        if any(re.search(p, tail) for p in usage_patterns):
            return {
                "lat": float(m.group("lat")),
                "lng": float(m.group("lng")),
            }

    # ------------------------------------------------------------------
    # 2) Direct Leaflet marker([lat,lng], ...)
    # ------------------------------------------------------------------
    marker_re = re.compile(
        rf'(?:\bmarker|\.marker)\s*\(\s*'
        rf'\[\s*(?P<lat>{num_lat})\s*,\s*(?P<lng>{num_lng})\s*\]'
    )

    m = marker_re.search(bundle)
    if m:
        return {
            "lat": float(m.group("lat")),
            "lng": float(m.group("lng")),
        }

    # ------------------------------------------------------------------
    # 3) Direct object numeric lat/lng.
    #    Keep it narrow to avoid unrelated values.
    # ------------------------------------------------------------------
    object_patterns = (
        re.compile(
            rf'\blat\s*:\s*(?P<lat>{num_lat})\s*,\s*'
            rf'\blng\s*:\s*(?P<lng>{num_lng})'
        ),
        re.compile(
            rf'\blng\s*:\s*(?P<lng>{num_lng})\s*,\s*'
            rf'\blat\s*:\s*(?P<lat>{num_lat})'
        ),
    )

    for rx in object_patterns:
        m = rx.search(bundle)
        if m:
            # Reject candidates that are obviously part of a map viewport.
            ctx = bundle[max(0, m.start() - 180): min(len(bundle), m.end() + 180)].lower()
            if "setview" in ctx:
                continue

            return {
                "lat": float(m.group("lat")),
                "lng": float(m.group("lng")),
            }

    return None


def extract_page_sections(
    s: requests.Session,
    project_url: str,
    bundle: str,
) -> tuple[dict, dict]:
    language = language_from_url(project_url)
    origin = site_origin(project_url)
    translation_url = f"{origin}/locales/{language}/translation.json"
    translation = get_json(s, translation_url)

    keys = referenced_translation_keys(bundle)

    overview_key, overview = select_section(
        translation, keys, ("projectOverview",), project_url
    )
    amenities_key, amenities = select_section(
        translation, keys, ("amenities",), project_url
    )
    gallery_key, gallery = select_section(
        translation, keys, ("gallery",), project_url
    )
    location_key, location = select_section(
        translation, keys, ("location",), project_url
    )
    payment_key, payment = select_section(
        translation, keys, ("paymentPlans", "payment"), project_url
    )
    faq_key, faq = select_section(
        translation, keys, ("faq",), project_url
    )

    location_section = absolutize_assets(location, origin)
    coordinates = extract_map_coordinates(bundle)

    if isinstance(location_section, dict) and coordinates:
        location_section = dict(location_section)
        location_section["coordinates"] = coordinates

    sections = {
        "overview": absolutize_assets(overview, origin),
        "amenities": absolutize_assets(amenities, origin),
        "gallery": absolutize_assets(gallery, origin),
        "location": location_section,
        "payment_plans": absolutize_assets(payment, origin),
        "faq": absolutize_assets(faq, origin),
    }
    sections = {k: v for k, v in sections.items() if v is not None}

    meta = {
        "translation_url": translation_url,
        "translation_keys": {
            "overview": overview_key,
            "amenities": amenities_key,
            "gallery": gallery_key,
            "location": location_key,
            "payment_plans": payment_key,
            "faq": faq_key,
        },
        "referenced_translation_keys": sorted(keys),
        "project_card": find_project_card(
            translation, project_url, origin, language
        ),
    }

    return sections, meta


def absolutize_unit_type_assets(unit_data: dict, project_url: str) -> dict:
    """
    Convert unit-level media paths to absolute URLs.

    Fields:
      - image_src
      - site_plan_image
      - floor_plan_image
      - gallery[]
    """
    parsed = urlparse(project_url)
    origin = f"{parsed.scheme}://{parsed.netloc}"

    def normalize(value):
        if not isinstance(value, str) or not value:
            return value
        if value.startswith(("http://", "https://", "data:")):
            return value
        if value.startswith("//"):
            return f"{parsed.scheme}:{value}"
        if value.startswith("/"):
            return urljoin(origin + "/", value.lstrip("/"))
        return urljoin(origin + "/", value)

    result = dict(unit_data)

    for field in ("image_src", "site_plan_image", "floor_plan_image"):
        result[field] = normalize(result.get(field))

    gallery = result.get("gallery")
    if isinstance(gallery, list):
        result["gallery"] = [normalize(item) for item in gallery]

    return result

def extract_project(
    s: requests.Session,
    project_url: str,
    debug: bool = False,
    save_bundle_dir: Optional[Path] = None,
) -> dict:
    print(f"\n[CC] Fetching project: {project_url}")
    html = get_text(s, project_url)
    scripts = find_initial_script_urls(html, project_url)

    bundle_url, bundle = discover_project_bundle(
        s, project_url, scripts, debug=debug
    )

    units = [parse_unit(obj, group_key) for group_key, obj in extract_unit_records(bundle)]

    # A unit type is (phase_group_key, external_id): external_id alone repeats between
    # groups ("type-a" in every phase). Case matters ("type-a" != "type-A"). A repeat
    # inside the same group is skipped, first one wins, and reported below.
    deduped: list[UnitType] = []
    seen_keys: set[tuple[Optional[str], str]] = set()
    duplicate_ids: list[UnitType] = []
    for unit in units:
        key = (unit.phase_group_key, unit.external_id or json.dumps(asdict(unit), sort_keys=True))
        if key in seen_keys:
            duplicate_ids.append(unit)
            continue
        seen_keys.add(key)
        deduped.append(unit)
    units = deduped

    project_name = guess_project_name(units, project_url) if units else "Projekt na Cyprze"

    page_sections, page_meta = extract_page_sections(
        s,
        project_url,
        bundle,
    )

    if save_bundle_dir:
        save_bundle_dir.mkdir(parents=True, exist_ok=True)
        slug = re.sub(r"[^a-z0-9]+", "-", project_name.lower()).strip("-")
        bundle_path = save_bundle_dir / f"{slug}.bundle.js"
        bundle_path.write_text(bundle, encoding="utf-8")
        if debug:
            print(f"[CC] Bundle saved: {bundle_path.resolve()}")

    warnings: list[dict] = []
    for unit in units:
        for warning in quality_warnings(unit):
            warnings.append({
                "external_id": unit.external_id,
                "title": unit.title,
                **warning,
            })
    for unit in duplicate_ids:
        warnings.append({
            "external_id": unit.external_id,
            "title": unit.title,
            "code": "DUPLICATE_UNIT_TYPE_ID",
            "message": (
                f"Another unit type with id {unit.external_id!r} exists in group "
                f"{unit.phase_group_key!r}; the first one was kept."
            ),
        })

    print(
        f"[CC] {project_name}: {len(units)} unit types, "
        f"{len(warnings)} warning(s)"
    )

    project_data = {
        "name": project_name,
    }

    card = page_meta.get("project_card")
    if isinstance(card, dict):
        project_data["card"] = card

    json_ld = extract_json_ld_listing(html)
    if json_ld:
        project_data["json_ld"] = json_ld

    project_data["sections"] = page_sections

    return {
        "source": {
            "project_url": project_url,
            "bundle_url": bundle_url,
            "translation_url": page_meta.get("translation_url"),
            "translation_keys": page_meta.get("translation_keys"),
            "referenced_translation_keys": page_meta.get(
                "referenced_translation_keys"
            ),
        },
        "project": project_data,
        "warnings": warnings,
        "unit_types": [
            absolutize_unit_type_assets(asdict(unit), project_url)
            for unit in units
        ],
    }


def run_batch(
    all_projects_url: str,
    output: Path,
    debug: bool = False,
    save_bundles: bool = False,
) -> int:
    s = make_session()
    print(f"[CC] Discovering projects from: {all_projects_url}")
    project_urls = discover_project_urls(s, all_projects_url, debug=debug)

    if not project_urls:
        raise RuntimeError("Nie znaleziono żadnych URL-i projektów.")

    bundle_dir = output.parent / "bundles" if save_bundles else None

    projects: list[dict] = []
    failures: list[dict] = []

    for i, url in enumerate(project_urls, 1):
        print(f"\n[CC] [{i}/{len(project_urls)}]")
        try:
            projects.append(
                extract_project(
                    s,
                    url,
                    debug=debug,
                    save_bundle_dir=bundle_dir,
                )
            )
        except Exception as exc:
            print(f"[CC] FAILED: {url}: {exc}")
            failures.append({
                "project_url": url,
                "error": str(exc),
            })

    total_units = sum(len(p["unit_types"]) for p in projects)
    total_warnings = sum(len(p["warnings"]) for p in projects)

    result = {
        "source": {
            "all_projects_url": all_projects_url,
        },
        "summary": {
            "projects_discovered": len(project_urls),
            "projects_imported": len(projects),
            "projects_failed": len(failures),
            "unit_types": total_units,
            "warnings": total_warnings,
        },
        "projects": projects,
        "failures": failures,
    }

    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(
        json.dumps(result, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )

    print("\n[CC] ===== SUMMARY =====")
    print(f"[CC] Discovered: {len(project_urls)}")
    print(f"[CC] Imported:   {len(projects)}")
    print(f"[CC] Failed:     {len(failures)}")
    print(f"[CC] Unit types: {total_units}")
    print(f"[CC] Warnings:   {total_warnings}")
    print(f"[CC] Saved:      {output.resolve()}")

    return 0 if not failures else 2


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Scrape details of one Cyprus Constructions project."
    )
    parser.add_argument(
        "url",
        help="Project URL, e.g. https://www.cyprusconstructions.com/pl/Aloha_homes",
    )
    parser.add_argument("-o", "--output", default="cyprus_project_details.json")
    parser.add_argument("--save-bundle", action="store_true")
    parser.add_argument("--debug", action="store_true")
    args = parser.parse_args()

    parsed = urlparse(args.url)
    if parsed.scheme not in {"http", "https"}:
        parser.error("URL musi używać http/https.")
    if parsed.netloc.lower() not in {
        "www.cyprusconstructions.com",
        "cyprusconstructions.com",
    }:
        parser.error("Dozwolona jest tylko domena cyprusconstructions.com.")

    output = Path(args.output)
    s = make_session()
    project = extract_project(
        s,
        args.url,
        debug=args.debug,
        save_bundle_dir=(output.parent / "bundles" if args.save_bundle else None),
    )

    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(
        json.dumps(project, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    print(f"[CC] Saved: {output.resolve()}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        raise SystemExit(130)
    except Exception as exc:
        print(f"\n[ERROR] {exc}", file=sys.stderr)
        raise SystemExit(1)
