"""Offline fixtures shaped like the real avartenproperties.com WordPress REST
payloads (properties, media) plus a scriptable fake HTTP session.

No test built on these touches the network.
"""
from __future__ import annotations

import copy

import requests

BASE = "https://avartenproperties.com"


def php_serialize(value) -> str:
    """Tiny PHP serializer used only to build realistic ``additional_features``."""
    if isinstance(value, dict):
        body = "".join(php_serialize(key) + php_serialize(item) for key, item in value.items())
        return f"a:{len(value)}:{{{body}}}"
    if isinstance(value, int):
        return f"i:{value};"
    text = str(value)
    return f's:{len(text.encode("utf-8"))}:"{text}";'


def additional_features(*pairs) -> str:
    return php_serialize(
        {
            index: {
                "fave_additional_feature_title": title,
                "fave_additional_feature_value": value,
            }
            for index, (title, value) in enumerate(pairs)
        }
    )


def rest_property(**overrides) -> dict:
    """A REST properties record (list/detail shape, whitelisted meta only)."""
    record = {
        "id": 26161,
        "date_gmt": "2025-04-04T12:34:54",
        "modified": "2025-04-04T14:48:52",
        "modified_gmt": "2025-04-04T14:48:52",
        "slug": "laya-courtyard-at-dubai-studio-city",
        "status": "publish",
        "link": f"{BASE}/property/laya-courtyard-at-dubai-studio-city/",
        "title": {"rendered": "Laya Courtyard at Dubai Studio City"},
        "content": {
            "rendered": (
                "<p>Laya Courtyard at Dubai Studio City by DECA properties is a "
                "remarkable project.</p>\n<p>Second&nbsp;paragraph &#8211; details.</p>"
            ),
            "protected": False,
        },
        "featured_media": 26178,
        "class_list": [
            "post-26161",
            "property",
            "type-property",
            "status-publish",
            "has-post-thumbnail",
            "hentry",
            "property_type-apartments",
            "property_status-primary",
            "property_city-dubai",
        ],
        "property_meta": {
            "fave_property_price": ["699000"],
            "fave_prop-price": ["699,000 AED/-"],
            "fave_property_bedrooms": ["2"],
            "fave_bedroom": ["1", "2"],
            "fave_property_bathrooms": ["2"],
            "fave_property_year": ["Q4 - 2026"],
            "fave_property_address": ["Dubai Studio City"],
            "fave_property_map_address": ["Dubai Studio City"],
            "fave_property_location": ["25.03605241282,55.231962187092,16"],
            "houzez_geolocation_lat": ["25.03605241282"],
            "houzez_geolocation_long": ["55.231962187092"],
            "fave_developers": ["Deca Development"],
            "additional_features": [
                additional_features(
                    ("Down Payment", "10%"),
                    ("During Construction", "40%"),
                    ("On Handover", "20%"),
                    ("Post Handover", "30%"),
                )
            ],
            "fave_property_images": ["26162", "26163", "26169"],
            "fave_featured": ["1"],
        },
    }
    meta_overrides = overrides.pop("meta", None)
    record.update(copy.deepcopy(overrides))
    if meta_overrides:
        record["property_meta"] = {**record["property_meta"], **copy.deepcopy(meta_overrides)}
    return record


def media_record(media_id: int, stem: str, *, with_sizes: bool = True) -> dict:
    base = f"{BASE}/wp-content/uploads/2025/04/{stem}"
    record = {
        "id": media_id,
        "source_url": f"{base}-scaled.jpg",
        "media_type": "image",
        "mime_type": "image/jpeg",
        "media_details": {"width": 2560, "height": 1480, "sizes": {}},
    }
    if with_sizes:
        record["media_details"]["sizes"] = {
            "large": {"source_url": f"{base}-1024x592.jpg", "width": 1024, "height": 592},
            "houzez-gallery": {"source_url": f"{base}-1170x785.jpg", "width": 1170, "height": 785},
            "houzez-item-image-1": {"source_url": f"{base}-592x444.jpg", "width": 592, "height": 444},
            "full": {"source_url": f"{base}-scaled.jpg", "width": 2560, "height": 1480},
        }
    return record


class FakeResponse:
    def __init__(self, payload=None, status_code=200, headers=None, *, invalid_json=False):
        self._payload = payload
        self.status_code = status_code
        self.headers = headers or {}
        self._invalid_json = invalid_json

    def json(self):
        if self._invalid_json:
            raise ValueError("no json")
        return copy.deepcopy(self._payload)


class FakeSession:
    """Routes ``(path, sorted params)`` lookups through a handler; records calls."""

    def __init__(self, handler):
        self._handler = handler
        self.calls: list[tuple[str, dict]] = []

    def get(self, url, params=None, headers=None, timeout=None):
        assert url.startswith(BASE), url
        path = url[len(BASE):]
        params = dict(params or {})
        self.calls.append((path, params))
        result = self._handler(path, params)
        if isinstance(result, Exception):
            raise result
        return result

    def calls_to(self, path: str) -> list[dict]:
        return [params for call_path, params in self.calls if call_path == path]


def connection_error() -> requests.ConnectionError:
    return requests.ConnectionError("boom")
