﻿import base64
from flask import Blueprint, abort, redirect, request, jsonify, url_for
from modules.core.offer_analytics import tripinvest_offer_key
from InvestmentWebsite.offers.api_errors import json_error
from InvestmentWebsite.offers.source_config import TRIPINVEST_API_CONFIG
from InvestmentWebsite.offers.page_flows import render_template_or_error
from InvestmentWebsite.offers.service import get_offer_service
from InvestmentWebsite.offers.source_facade import SourceApiFacade
from InvestmentWebsite.seo import build_landing_head
from InvestmentWebsite.offers.response_contracts import (
    standard_pagination_from_meta,
)
from integrations.tripinvest.config import (
    TRIPINVEST_FILTERS,
    TRIPINVEST_AREAS,
    TRIPINVEST_AREAS_GROUPED,
    TRIPINVEST_SORTING,
    TRIPINVEST_OFFER_FLAGS,
    TRIPINVEST_MARKET,
    TRIPINVEST_FEATURES,
    TRIPINVEST_SEA_DISTANCE,
)

tripinvest_bp = Blueprint("tripinvest", __name__)
offer_service = get_offer_service()


def _encode_offer_token(raw_url: str) -> str:
    return base64.urlsafe_b64encode(raw_url.encode("utf-8")).decode("ascii").rstrip("=")


def _decode_offer_token(token: str) -> str | None:
    if not token:
        return None
    try:
        padding = "=" * (-len(token) % 4)
        decoded = base64.urlsafe_b64decode((token + padding).encode("ascii")).decode("utf-8")
    except Exception:
        return None
    if decoded.startswith("http://") or decoded.startswith("https://"):
        return decoded
    return None


def _tripinvest_area_label(area_slug: str) -> str:
    if not area_slug:
        return "Hiszpania"
    for group in TRIPINVEST_AREAS_GROUPED.values():
        for label, slug in group.items():
            if slug == area_slug:
                return label
    return area_slug.replace("-", " ").title()


def _tripinvest_filter_label(filter_slug: str) -> str:
    if not filter_slug:
        return ""
    return filter_slug.replace("-", " ").replace("_", " ").title()


def _is_valid_tripinvest_area(area_slug: str) -> bool:
    if not area_slug:
        return True
    return any(area_slug in group.values() for group in TRIPINVEST_AREAS_GROUPED.values())


def _is_valid_tripinvest_filter(filter_slug: str) -> bool:
    if not filter_slug:
        return True
    return filter_slug in TRIPINVEST_FILTERS


def _tripinvest_filters_from_request(req_args):
    return {
        "region": "hiszpania",
        "area": req_args.get("area") or None,
        "filter": req_args.get("filter"),
        "sorting": req_args.get("sorting"),
        "offer_flag": req_args.getlist("offer_flag"),
        "market": req_args.getlist("market"),
        "price_min": req_args.get("price_min", type=int),
        "price_max": req_args.get("price_max", type=int),
        "area_min": req_args.get("area_min", type=int),
        "area_max": req_args.get("area_max", type=int),
        "land_area_min": req_args.get("land_area_min", type=int),
        "land_area_max": req_args.get("land_area_max", type=int),
        "query": req_args.get("query"),
        "bedrooms_min": req_args.get("bedrooms_min", type=int),
        "bedrooms_max": req_args.get("bedrooms_max", type=int),
        "bathrooms_min": req_args.get("bathrooms_min", type=int),
        "bathrooms_max": req_args.get("bathrooms_max", type=int),
        "sea_distance": req_args.getlist("sea_distance"),
        "features": req_args.getlist("features"),
    }


# =========================
# AREA CATALOG PAGE
# =========================
@tripinvest_bp.route(
    "/nieruchomosci/hiszpania/katalog",
    defaults={"area": "", "property_type": ""},
)
@tripinvest_bp.route(
    "/nieruchomosci/hiszpania/katalog/<area>",
    defaults={"property_type": ""},
)
@tripinvest_bp.route("/nieruchomosci/hiszpania/katalog/<area>/<property_type>")
def tripinvest_area_catalog(area, property_type):
    requested_filter = request.args.get("filter", "").strip()
    query_keys = set(request.args.keys())
    if (
        area
        and not property_type
        and requested_filter
        and _is_valid_tripinvest_filter(requested_filter)
        and query_keys.issubset({"area", "filter"})
        and (not request.args.get("area") or request.args.get("area") == area)
    ):
        return redirect(
            url_for(
                "tripinvest.tripinvest_area_catalog",
                area=area,
                property_type=requested_filter,
            ),
            code=301,
        )

    if not _is_valid_tripinvest_area(area) or not _is_valid_tripinvest_filter(property_type):
        abort(404)

    area_label = _tripinvest_area_label(area)
    property_type_label = _tripinvest_filter_label(property_type)
    has_area_slug = bool(area)
    has_seo_slug = bool(area and property_type)

    if has_seo_slug:
        page_title = (
            f"{property_type_label} w {area_label} | Nieruchomosci Hiszpania | "
            "Investment Nieruchomosci"
        )
        meta_description = (
            f"Sprawdz {property_type_label.lower()} w lokalizacji {area_label}. "
            "Aktualne oferty nieruchomosci w Hiszpanii."
        )
    elif has_area_slug:
        page_title = f"Nieruchomosci w Hiszpanii - {area_label} | Investment Nieruchomosci"
        meta_description = (
            f"Katalog ofert nieruchomosci w Hiszpanii dla lokalizacji {area_label}. "
            "Przegladaj dostepne oferty i filtry wyszukiwania."
        )
    else:
        page_title = "Nieruchomosci w Hiszpanii - Katalog | Investment Nieruchomosci"
        meta_description = (
            "Katalog ofert nieruchomosci w Hiszpanii. "
            "Przegladaj dostepne oferty i filtry wyszukiwania."
        )

    return render_template_or_error(
        request=request,
        source=TRIPINVEST_API_CONFIG.source,
        template_name="tripinvest/tripinvest_catalog.html",
        context={
            "head": build_landing_head(
                page_title=page_title,
                meta_description=meta_description,
                canonical_url=request.base_url,
                robots=(None if has_area_slug else "noindex, nofollow"),
                image_url=request.url_root.rstrip("/") + "/static/images/hiszpania_hero.webp",
            ),
            "area": area,
            "property_type": property_type,
            "property_filters": TRIPINVEST_FILTERS,
            "areas": TRIPINVEST_AREAS,
            "areas_grouped": TRIPINVEST_AREAS_GROUPED,
            "sorting_options": TRIPINVEST_SORTING,
            "offer_flags": TRIPINVEST_OFFER_FLAGS,
            "markets": TRIPINVEST_MARKET,
            "features": TRIPINVEST_FEATURES,
            "sea_distances": TRIPINVEST_SEA_DISTANCE,
        },
        render_error_event="catalog_template_render_error",
        render_error_message="Failed to render catalog page.",
        log_context={"area": area, "property_type": property_type},
    )


# =========================
# API - OFFERS LIST
# =========================
@tripinvest_bp.route("/api/tripinvest_offers")
def api_tripinvest_offers():
    facade = SourceApiFacade(request, offer_service, TRIPINVEST_API_CONFIG)
    blocked_response = facade.guard()
    if blocked_response:
        return blocked_response

    page = request.args.get("page", default=1, type=int)
    filters = _tripinvest_filters_from_request(request.args)
    area = filters["area"]

    payload, error_response = facade.build_catalog_payload(
        filters=filters,
        page=page,
        error_event="api_offers_fetch_error",
        error_message="Failed to fetch offers",
        success_context={
            "area": area,
            "page": page,
        },
        pagination_builder=standard_pagination_from_meta,
        extra_payload={
            "region": "hiszpania",
            "area": area,
        },
    )
    if error_response:
        return error_response
    return jsonify(payload)


# =========================
# API - OFFER DETAILS
# =========================
@tripinvest_bp.route("/api/tripinvest_offer_details")
def api_tripinvest_offer_details():
    facade = SourceApiFacade(request, offer_service, TRIPINVEST_API_CONFIG)
    blocked_response = facade.guard()
    if blocked_response:
        return blocked_response

    url = request.args.get("url")

    if not url:
        return json_error("Missing URL", 400)

    details, error_response = facade.build_offer_payload(
        identifier={"url": url},
        error_event="api_offer_details_error",
        not_found_message="No data returned",
        generic_message="Failed to fetch offer details",
        success_context={"offer_url": url},
    )
    if error_response:
        return error_response

    return jsonify({
        "offer": details,
        "url": url,
    })


@tripinvest_bp.route("/nieruchomosci/hiszpania/oferta", defaults={"offer_token": ""})
@tripinvest_bp.route("/nieruchomosci/hiszpania/oferta/<offer_token>")
def tripinvest_offer_page(offer_token):

    url = _decode_offer_token(offer_token) if offer_token else None
    legacy_url = request.args.get("url")

    if not url and legacy_url:
        return redirect(
            url_for(
                "tripinvest.tripinvest_offer_page",
                offer_token=_encode_offer_token(legacy_url),
            ),
            code=301,
        )
    if not url:
        url = legacy_url

    if not url:
        return "Missing URL", 400

    return render_template_or_error(
        request=request,
        source=TRIPINVEST_API_CONFIG.source,
        template_name="tripinvest/tripinvest_offer.html",
        context={
            "head": build_landing_head(
                page_title="Oferta nieruchomosci - Hiszpania | Investment Nieruchomosci",
                meta_description=(
                    "Szczegoly oferty nieruchomosci w Hiszpanii. "
                    "Sprawdz parametry, lokalizacje i formularz kontaktowy."
                ),
                canonical_url=request.base_url,
                robots="noindex, nofollow",
                image_url=request.url_root.rstrip("/") + "/static/images/hiszpania_hero.webp",
                og_type="article",
            ),
            "offer_url": url,
            "platform": "tripinvest",
            "robots": "noindex, follow",
            "matomo_offer_key": tripinvest_offer_key(url),
        },
        render_error_event="offer_template_render_error",
        render_error_message="Failed to render offer page.",
        log_context={"offer_url": url},
    )


