from __future__ import annotations

from InvestmentWebsite.services.catalog import (
    get_active_agents,
    get_catalog_area_bounds,
    get_catalog_price_bounds,
    get_unique_filter_values,
    normalize_filter_selection,
    normalize_numeric_range_value,
)
from InvestmentWebsite.services.offer_helpers import (
    build_offer_detail_items,
    build_offer_gallery_images,
    build_offer_meta,
    extract_offer_payload_from_canonical,
)
from InvestmentWebsite.services.offer_urls import build_offer_path, build_offer_slug
from InvestmentWebsite.offers.page_flows import fetch_offer_for_page_or_error
from InvestmentWebsite.offers.service import get_offer_service
from InvestmentWebsite.offers.source_config import INVESTMENT_API_CONFIG
from InvestmentWebsite.services.offer_urls import build_offer_path


class InvestmentFacade:
    def __init__(self, offer_service=None):
        self.offer_service = offer_service or get_offer_service()

    def get_catalog_filters(self):
        return {
            "typ_nieruchomosci": get_unique_filter_values(
                column="Typ_nieruchomosci",
                table="EstateData",
            ),
            "typ_oferty": get_unique_filter_values(
                column="Typ_oferty",
                table="EstateData",
            ),
            "typ_rynku": get_unique_filter_values(
                column="Typ_rynku",
                table="EstateData",
            ),
            "stan_nieruchomosci": get_unique_filter_values(
                column="Stan_nieruchomosci",
                table="EstateData",
            ),
            "miejscowosc": get_unique_filter_values(
                column="Miejscowosc",
                table="Localization",
            ),
            "wojewodztwo": get_unique_filter_values(
                column="Wojewodztwo",
                table="Localization",
            ),
            "agenci": get_active_agents(),
            "price_bounds": get_catalog_price_bounds(),
            "area_bounds": get_catalog_area_bounds(),
        }

    def catalog_filters_from_args(self, args):
        return {
            "typ_nieruchomosci": normalize_filter_selection(
                args.get("typ-nieruchomosci"),
                column="Typ_nieruchomosci",
                table="EstateData",
            ),
            "typ_oferty": normalize_filter_selection(
                args.get("typ-oferty"),
                column="Typ_oferty",
                table="EstateData",
            ),
            "typ_rynku": normalize_filter_selection(
                args.get("typ-rynku"),
                column="Typ_rynku",
                table="EstateData",
            ),
            "stan_nieruchomosci": normalize_filter_selection(
                args.get("stan-nieruchomosci"),
                column="Stan_nieruchomosci",
                table="EstateData",
            ),
            "miejscowosc": normalize_filter_selection(
                args.get("miejscowosc"),
                column="Miejscowosc",
                table="Localization",
            ),
            "wojewodztwo": normalize_filter_selection(
                args.get("wojewodztwo"),
                column="Wojewodztwo",
                table="Localization",
            ),
            "kraj": normalize_filter_selection(
                args.get("kraj"),
                column="Kraj",
                table="EstateData",
            ),
            "cena_min": normalize_numeric_range_value(args.get("cena_min")),
            "cena_max": normalize_numeric_range_value(args.get("cena_max")),
            "powierzchnia_min": normalize_numeric_range_value(args.get("powierzchnia_min")),
            "powierzchnia_max": normalize_numeric_range_value(args.get("powierzchnia_max")),
            "sort": args.get("sort"),
            "agent_id": args.get("agent_id", type=int),
            "container_only": args.get("container_only") in {"1", "true", "True", "yes"},
            "q": args.get("q", "").strip(),
        }

    def build_catalog_context(self, args, page, per_page):
        result = self.offer_service.get_catalog(
            source=INVESTMENT_API_CONFIG.source,
            filters=self.catalog_filters_from_args(args),
            page=page,
            per_page=per_page,
        )

        offers = [self._catalog_card_from_canonical(item) for item in result["items"]]
        meta = result["meta"]

        return {
            "offers": offers,
            "total_records": meta["total_records"],
            "current_page": meta["current_page"],
            "total_pages": meta["total_pages"],
            "sort": self.catalog_filters_from_args(args).get("sort"),
        }

    def build_offer_page_view(self, request, estate_id, details_map, fallback_offer_details):
        canonical, error_response = fetch_offer_for_page_or_error(
            request=request,
            offer_service=self.offer_service,
            source=INVESTMENT_API_CONFIG.source,
            identifier={"id": estate_id},
            not_found_message="Offer not found.",
            generic_message="An error occurred while loading the offer.",
            error_event="offer_fetch_error",
            log_context={"offer_id": estate_id},
        )
        if error_response:
            return None, error_response

        offer, record, video_exists_flag = extract_offer_payload_from_canonical(canonical)
        if not offer or not record:
            return None, ("Offer not found.", 404)

        details_config = details_map.get(offer["property_type"], []) or fallback_offer_details
        detail_items = build_offer_detail_items(record, details_config)
        gallery_images = build_offer_gallery_images(offer["id"], offer["image_count"])
        canonical_path = build_offer_path(
            offer_id=offer["id"],
            property_type=offer.get("property_type"),
            offer_type=offer.get("offer_type"),
            rooms=offer.get("rooms"),
            city=offer.get("city"),
        )
        canonical_url = f"{request.url_root.rstrip('/')}{canonical_path}"
        offer_meta = build_offer_meta(offer, canonical_url=canonical_url)

        return {
            "offer": offer,
            "video_exists": video_exists_flag,
            "detail_items": detail_items,
            "gallery_images": gallery_images,
            "offer_meta": offer_meta,
            "canonical_slug": build_offer_slug(
                offer_id=offer["id"],
                property_type=offer.get("property_type"),
                offer_type=offer.get("offer_type"),
                rooms=offer.get("rooms"),
                city=offer.get("city"),
            ),
            "canonical_path": canonical_path,
            "canonical_url": canonical_url,
        }, None

    @staticmethod
    def _catalog_card_from_canonical(item):
        listing = item.get("listing") or {}
        location = listing.get("location") or {}
        pricing = item.get("pricing") or {}
        metrics = item.get("metrics") or {}
        technical = item.get("technical") or {}
        media = item.get("media") or {}

        country_code = listing.get("country_code")
        country_label = "Polska" if country_code == "PL" else "Hiszpania" if country_code == "ES" else ""

        return {
            "id": int(item["identity"]["offer_id"]),
            "property_type": (listing.get("property_type") or "").strip(),
            "offer_type": (listing.get("offer_type") or "").strip(),
            "market_type": (listing.get("market_type") or "").strip(),
            "country": country_label,
            "city": (location.get("city") or "").strip(),
            "region": (location.get("region") or "").strip(),
            "price": pricing.get("amount") or 0,
            "rooms": metrics.get("rooms"),
            "plot_area_m2": metrics.get("plot_area_m2"),
            "plot_shape": None,
            "plot_terrain": None,
            "area_m2": metrics.get("area_m2"),
            "building_condition": technical.get("building_condition"),
            "property_condition": technical.get("property_condition"),
            "location_label": (location.get("address_label") or listing.get("title") or "").strip(),
            "image_url": media.get("cover_image") or "/static/images/no_image.svg",
            "url": build_offer_path(
                offer_id=int(item["identity"]["offer_id"]),
                property_type=listing.get("property_type"),
                offer_type=listing.get("offer_type"),
                rooms=metrics.get("rooms"),
                city=location.get("city"),
            ),
        }
