import re
import unicodedata
from uuid import UUID
from pathlib import Path
from urllib.parse import unquote, urlparse

from flask import Blueprint, abort, current_app, jsonify, redirect, render_template, request, url_for
from InvestmentWebsite.services.about_helpers import build_about_context
from InvestmentWebsite.services.catalog_helpers import (
    build_catalog_context,
    get_catalog_filters,
)
from InvestmentWebsite.services.catalog_constants import DETAILS_MAP, OFFICES
from InvestmentWebsite.services.http_helpers import cacheable_response
from InvestmentWebsite.services.lead_service import send_investment_lead, send_valuation_lead
from InvestmentWebsite.offers.lead_spam_guard import (
    FORM_TOKEN_FIELD, HONEYPOT_FIELD, check_form_token,
)
from modules.core.extensions import limiter
from InvestmentWebsite.services.franchise_service import (
    book_public_franchise_meeting,
    get_public_franchise_availability,
)
from InvestmentWebsite.services.poland_helpers import build_poland_map
from InvestmentWebsite.offers.record_schema import OFFER_IDX as IDX
from modules.core.offer_analytics import investment_offer_key

from modules.core.error_responses import current_request_id, log_internal_error
from modules.core.agent_queries import (
    get_agents,
    get_branches,
    get_branches_office_data,
)
from InvestmentWebsite.services.catalog import (
    get_agent_card_data,
    get_agent_roles,
    get_estates_count_by_wojewodztwo,
)
from InvestmentWebsite.services.offer_urls import (
    extract_offer_id_from_slug,
)
from InvestmentWebsite.seo import (
    build_breadcrumb_json_ld,
    build_landing_head,
    build_real_estate_agent_json_ld,
)
from InvestmentWebsite.offers.investment_facade import InvestmentFacade

investment_bp = Blueprint("investment", __name__)
investment_facade = InvestmentFacade()

PER_PAGE = 36
FALLBACK_OFFER_DETAILS = [
    ("Typ nieruchomości", IDX.PROPERTY_TYPE),
    ("Typ oferty", IDX.OFFER_TYPE),
    ("Rynek", IDX.MARKET_TYPE),
    ("Miejscowość", IDX.CITY),
    ("Województwo", IDX.REGION),
    ("Powierzchnia", IDX.AREA_M2, "m²"),
]


def _slugify(value: str) -> str:
    normalized = unicodedata.normalize("NFKD", str(value or ""))
    ascii_text = normalized.encode("ascii", "ignore").decode("ascii").lower()
    slug = re.sub(r"[^a-z0-9]+", "-", ascii_text).strip("-")
    return slug or "any"


def _build_investment_slug_maps():
    filters = get_catalog_filters()
    property_types = [item for item in filters.get("typ_nieruchomosci", []) if item]
    offer_types = [item for item in filters.get("typ_oferty", []) if item]

    property_slug_to_value = {}
    property_value_to_slug = {}
    for value in property_types:
        slug = _slugify(value)
        if slug not in property_slug_to_value:
            property_slug_to_value[slug] = value
        property_value_to_slug[value] = slug

    offer_slug_to_value = {}
    offer_value_to_slug = {}
    for value in offer_types:
        slug = _slugify(value)
        if slug not in offer_slug_to_value:
            offer_slug_to_value[slug] = value
        offer_value_to_slug[value] = slug

    return {
        "property_slug_to_value": property_slug_to_value,
        "property_value_to_slug": property_value_to_slug,
        "offer_slug_to_value": offer_slug_to_value,
        "offer_value_to_slug": offer_value_to_slug,
    }

# =========================
# MAIN PAGE
# =========================

@investment_bp.route("/")
def main_page():
    wojewodztwa_stats = get_estates_count_by_wojewodztwo()
    moduvo_agent = get_agent_card_data(103)

    return cacheable_response(
        "strona_glowna.html",
        head=build_landing_head(
            page_title="Investment Nieruchomości - Sprzedaż i Wynajem",
            meta_description="Investment Nieruchomości to Twoja zaufana agencja nieruchomości oferująca sprzedaż i wynajem mieszkań, domów, apartamentów i działek w Polsce, Hiszpanii i Dubaju.",
            canonical_url=request.base_url,
            theme_color="#478ac9",
            image_url=url_for("static", filename="images/main_strona_glowna.webp", _external=True),
            google_site_verification="0yJEd2A5pmkCtu-BimV1HQ_QLTICFVVb-ZRdEnudXCk",
            og_title="Investment Nieruchomości - Oferty Sprzedaży i Wynajmu",
            og_description="Agencja nieruchomości: sprzedaż i wynajem mieszkań, domów, apartamentów i działek w Polsce, Hiszpanii i Dubaju.",
            json_ld=[
                build_real_estate_agent_json_ld(
                    name="Investment Nieruchomości",
                    url=request.url_root.rstrip("/"),
                    logo=url_for("static", filename="images/investment_logo.webp", _external=True),
                    image=url_for("static", filename="images/main_strona_glowna.webp", _external=True),
                    telephone="+48 500 793 294",
                    email="sebastian.szymoniak.investment@gmail.com",
                    street_address="ul. Bema 2H",
                    address_locality="Kędzierzyn-Koźle",
                    address_country="PL",
                )
            ],
        ),
        wojewodztwa_stats=wojewodztwa_stats,
        moduvo_agent=moduvo_agent,
    )

@investment_bp.route("/polityka-prywatnosci", defaults={"language": "pl"})
@investment_bp.route("/privacy-policy", defaults={"language": "en"})
def privacy_policy(language):
    english = language == "en"
    return render_template(
        "privacy_policy.html",
        privacy_language=language,
        head=build_landing_head(
            page_title="Privacy Policy | Investment" if english else "Polityka prywatności | Investment",
            meta_description=(
                "How Investment handles your personal data and how to exercise your rights."
                if english
                else "Jak Investment przetwarza dane osobowe i jak możesz skorzystać ze swoich praw."
            ),
            canonical_url=request.base_url,
        ),
    )


# =========================
# ABOUT
# =========================

def _verified_office_image_url(image_url):
    image_url = (image_url or "").strip()
    if not image_url:
        return ""

    parsed = urlparse(image_url)
    if parsed.scheme in {"http", "https"}:
        return image_url

    image_path = unquote(parsed.path or image_url)
    if image_path.startswith("/static/"):
        relative_path = image_path.removeprefix("/static/")
    elif image_path.startswith("static/"):
        relative_path = image_path.removeprefix("static/")
    else:
        return image_url

    static_root = Path(current_app.static_folder)
    if (static_root / relative_path).is_file():
        return image_url

    return ""


def _sanitize_office_images(offices):
    sanitized = {}
    for key, office in offices.items():
        office_data = dict(office)
        office_data["image"] = _verified_office_image_url(office_data.get("image"))
        sanitized[key] = office_data
    return sanitized

@investment_bp.route("/o-nas", methods=["GET", "POST"])
def about_page():
    agents = get_agents()
    branches = get_branches()
    roles = get_agent_roles()
    offices_from_db = get_branches_office_data()
    selected_region = request.form.get("region_filter", "all")
    context = build_about_context(agents, branches, roles, selected_region)
    offices_merged = dict(OFFICES)
    offices_merged.update(offices_from_db)
    offices_merged = _sanitize_office_images(offices_merged)

    return render_template(
        "o_nas.html",
        head=build_landing_head(
            page_title="O nas - Investment Nieruchomości",
            meta_description="Poznaj nasz zespół i dowiedz się, jak działamy w Polsce i Hiszpanii.",
            canonical_url=request.base_url,
        ),
        offices=offices_merged,
        **context,
    )

# =========================
# CONTACT
# =========================

@investment_bp.route("/franczyza")
def contact_page():
    return cacheable_response(
        "franczyza.html",
        head=build_landing_head(
            page_title="Franczyza - Investment Nieruchomości",
            meta_description="Dołącz do naszej sieci franczyzowej – rozwiń swój biznes z Investment Nieruchomości.",
            canonical_url=request.base_url,
        ),
    )


@investment_bp.route("/dla-biznesu")
def business_solutions_page():
    return cacheable_response(
        "dla_biznesu.html",
        head=build_landing_head(
            page_title="Rozwiązania dla biznesu | Investment Nieruchomości",
            meta_description=(
                "Rozwiązania dla rynku nieruchomości: prezentacja projektów, "
                "technologia, integracje, dystrybucja i wsparcie procesu sprzedaży."
            ),
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/rodzinnyzakatek.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona glowna", f"{request.url_root.rstrip('/')}/"),
                        ("Rozwiązania dla biznesu", request.base_url),
                    ]
                )
            ],
        ),
        business_agent=get_agent_card_data(101),
    )


@investment_bp.route("/franczyza/umow-spotkanie")
def franchise_meeting_page():
    source = (request.args.get("src") or "franczyza").strip().lower()
    franchise_agent = get_agent_card_data(101)
    return cacheable_response(
        "franchise_meeting.html",
        head=build_landing_head(
            page_title="Umów spotkanie franczyzowe | Investment Nieruchomości",
            meta_description="Umów spotkanie dotyczące franczyzy Investment Nieruchomości. Wybierz dogodny termin i zostaw dane kontaktowe.",
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/franczyza.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona główna", f"{request.url_root.rstrip('/')}/"),
                        ("Franczyza", f"{request.url_root.rstrip('/')}/franczyza"),
                        ("Umów spotkanie", request.base_url),
                    ]
                )
            ],
        ),
        booking_source=source,
        franchise_agent=franchise_agent,
    )


@investment_bp.route("/bezplatna-wycena-nieruchomosci")
def valuation_page():
    return cacheable_response(
        "wycena_nieruchomosci.html",
        head=build_landing_head(
            page_title="Bezpłatna wycena nieruchomości | Investment Nieruchomości",
            meta_description="Formularz bezpłatnej wyceny nieruchomości. Zostaw dane mieszkania, domu, działki, lokalu lub obiektu i skontaktujemy się z Tobą.",
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/main_strona_glowna.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona główna", f"{request.url_root.rstrip('/')}/"),
                        ("Bezpłatna wycena nieruchomości", request.base_url),
                    ]
                )
            ],
        ),
    )

# =========================
# POLAND HUB
# =========================

@investment_bp.route("/nieruchomosci/polska")
def polska_hub():
    wojewodztwa_stats = get_estates_count_by_wojewodztwo()
    poland_map = build_poland_map(wojewodztwa_stats)

    return cacheable_response(
        "investment/polska.html",
        head=build_landing_head(
            page_title="Nieruchomości w Polsce | Investment Nieruchomości",
            meta_description="Nieruchomości w Polsce: mieszkania, domy, działki i lokale w kluczowych województwach. Wybierz region i przejdź do ofert.",
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/wojewodztwa/zachodniopomorskie.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona główna", f"{request.url_root.rstrip('/')}/"),
                        ("Nieruchomości w Polsce", request.base_url),
                    ]
                )
            ],
        ),
        wojewodztwa_stats=wojewodztwa_stats,
        poland_map=poland_map,
    )

# =========================
# OFFER CATALOG
# =========================


@investment_bp.route("/nieruchomosci")
@investment_bp.route("/nieruchomosci/strona/<int:page>")
def offer_catalog(page=1):
    selected_filters = investment_facade.catalog_filters_from_args(request.args)
    context = build_catalog_context(request.args, page, PER_PAGE)
    slug_maps = _build_investment_slug_maps()

    return render_template(
        "investment/nieruchomosci.html",
        head=build_landing_head(
            page_title="Katalog nieruchomości | Investment Nieruchomości",
            meta_description="Katalog nieruchomości w Polsce: mieszkania, domy, działki i lokale z aktualnymi ofertami Investment Nieruchomości.",
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/main_strona_glowna.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona główna", f"{request.url_root.rstrip('/')}/"),
                        ("Katalog nieruchomości", request.base_url),
                    ]
                )
            ],
        ),
        filters=get_catalog_filters(),
        investment_filter_slugs=slug_maps,
        typ_nieruchomosci=selected_filters["typ_nieruchomosci"],
        typ_oferty=selected_filters["typ_oferty"],
        typ_rynku=selected_filters["typ_rynku"],
        stan_nieruchomosci=selected_filters["stan_nieruchomosci"],
        cena_min=selected_filters["cena_min"],
        cena_max=selected_filters["cena_max"],
        powierzchnia_min=selected_filters["powierzchnia_min"],
        powierzchnia_max=selected_filters["powierzchnia_max"],
        miejscowosc=selected_filters["miejscowosc"],
        wojewodztwo=selected_filters["wojewodztwo"],
        agent_id=request.args.get("agent_id"),
        q=selected_filters["q"],
        **context
    )


@investment_bp.route(
    "/nieruchomosci/katalog/<property_type_slug>",
    defaults={"offer_type_slug": ""},
)
@investment_bp.route("/nieruchomosci/katalog/<property_type_slug>/<offer_type_slug>")
def offer_catalog_seo(property_type_slug, offer_type_slug):
    slug_maps = _build_investment_slug_maps()
    property_type = slug_maps["property_slug_to_value"].get(property_type_slug)
    offer_type = slug_maps["offer_slug_to_value"].get(offer_type_slug) if offer_type_slug else None

    if not property_type or (offer_type_slug and not offer_type):
        abort(404)

    args = request.args.copy()
    args["typ-nieruchomosci"] = property_type
    if offer_type:
        args["typ-oferty"] = offer_type

    selected_filters = investment_facade.catalog_filters_from_args(args)
    context = build_catalog_context(args, 1, PER_PAGE)
    page_title = (
        f"{property_type} na {offer_type} | Katalog nieruchomosci | Investment"
        if offer_type
        else f"{property_type} | Katalog nieruchomosci | Investment"
    )
    meta_description = (
        f"Oferty typu {property_type.lower()} na {offer_type.lower()}. "
        "Aktualny katalog nieruchomosci Investment."
        if offer_type
        else f"Katalog ofert: {property_type.lower()}. "
        "Aktualne nieruchomosci Investment."
    )

    return render_template(
        "investment/nieruchomosci.html",
        head=build_landing_head(
            page_title=page_title,
            meta_description=meta_description,
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/main_strona_glowna.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona glowna", f"{request.url_root.rstrip('/')}/"),
                        ("Katalog nieruchomosci", f"{request.url_root.rstrip('/')}/nieruchomosci"),
                        (property_type, request.base_url),
                    ]
                )
            ],
        ),
        filters=get_catalog_filters(),
        investment_filter_slugs=slug_maps,
        typ_nieruchomosci=selected_filters["typ_nieruchomosci"],
        typ_oferty=selected_filters["typ_oferty"],
        typ_rynku=selected_filters["typ_rynku"],
        stan_nieruchomosci=selected_filters["stan_nieruchomosci"],
        cena_min=selected_filters["cena_min"],
        cena_max=selected_filters["cena_max"],
        powierzchnia_min=selected_filters["powierzchnia_min"],
        powierzchnia_max=selected_filters["powierzchnia_max"],
        miejscowosc=selected_filters["miejscowosc"],
        wojewodztwo=selected_filters["wojewodztwo"],
        agent_id=request.args.get("agent_id"),
        q=selected_filters["q"],
        **context
    )

@investment_bp.route("/nieruchomosci/ajax-json")
def offer_catalog_ajax_json():
    args = request.args
    page = args.get("page", 1, type=int)
    context = build_catalog_context(args, page, PER_PAGE)

    html = render_template("components/offers_grid_partial.html", **context)
    return jsonify(
        {
            "html": html,
            "pagination": {
                "current_page": context["current_page"],
                "total_pages": context["total_pages"],
            },
            "total_records": context["total_records"],
        }
    )


@investment_bp.route("/agent/<int:agent_id>")
def agent_redirect(agent_id):
    return redirect(
        url_for("investment.offer_catalog", agent_id=agent_id),
        code=302
    )


# =========================
# OFFER PAGE
# =========================

def _render_offer_page(estate_id, *, requested_slug=None, force_redirect=False):
    view_data, error_response = investment_facade.build_offer_page_view(
        request=request,
        estate_id=estate_id,
        details_map=DETAILS_MAP,
        fallback_offer_details=FALLBACK_OFFER_DETAILS,
    )
    if error_response:
        return error_response

    try:
        offer = view_data["offer"]
        video_exists_flag = view_data["video_exists"]
        detail_items = view_data["detail_items"]
        gallery_images = view_data["gallery_images"]
        canonical_slug = view_data["canonical_slug"]
        canonical_path = view_data["canonical_path"]
        canonical_url = view_data["canonical_url"]

        if force_redirect or (requested_slug is not None and requested_slug != canonical_slug):
            return redirect(canonical_path, code=301)

        offer_meta = view_data["offer_meta"]

        return cacheable_response(
            "investment/oferta.html",
            head=build_landing_head(
                page_title=offer_meta["page_title"],
                meta_description=offer_meta["meta_description"],
                canonical_url=canonical_url,
                image_url=offer_meta["og_image"],
                og_type="article",
                json_ld=[offer_meta["breadcrumb_schema"], offer_meta["offer_schema"]],
            ),
            offer=offer,
            video_exists=video_exists_flag,
            detail_items=detail_items,
            gallery_images=gallery_images,
            matomo_offer_key=investment_offer_key(offer["id"]),
        )
    except Exception as e:
        log_internal_error(f"offer_page {estate_id}", e)
        abort(500)                                           # the site's own 500 page; the exception stays in the server log


@investment_bp.route("/nieruchomosc/<offer_slug>")
def offer_page_slug(offer_slug):
    estate_id = extract_offer_id_from_slug(offer_slug)
    if estate_id is None:
        abort(404)
    return _render_offer_page(estate_id, requested_slug=offer_slug)


@investment_bp.route("/nieruchomosc/oferta-id-<int:estate_id>")
def offer_page_legacy(estate_id):
    return _render_offer_page(estate_id, force_redirect=True)

def _public_form_verified(fields):
    token = fields.get(FORM_TOKEN_FIELD)
    return (
        isinstance(token, str) and len(token) <= 512
        and fields.get(HONEYPOT_FIELD, "") == ""
        and not check_form_token(token)
    )


def _public_form_error():
    return {"success": False, "error": "Nie udało się zweryfikować formularza. Odśwież stronę i spróbuj ponownie."}, 400


@investment_bp.route("/send-lead", methods=["POST"])
@limiter.limit("3 per minute")
def send_lead():
    request.max_content_length = 32 * 1024
    fields = request.form
    if not fields.get("offer_id"):
        return {"success": False, "error": "Brak ID oferty"}, 400
    if not _public_form_verified(fields):
        return _public_form_error()
    try:
        submission_id = UUID(fields.get("submission_id", ""))
        if submission_id.version != 4:
            return _public_form_error()
    except ValueError:
        return _public_form_error()
    try:
        payload, status = send_investment_lead(
            phone=fields.get("phone", "").strip(),
            email=fields.get("email", "").strip(),
            message=fields.get("message", "").strip(),
            offer_id=fields.get("offer_id"),
            submission_id=submission_id.hex,
        )
        return payload, status

    except Exception as e:
        current_app.logger.error("send_lead failed [request_id=%s] (%s)", current_request_id(), type(e).__name__)
        return {"success": False, "error": "Server error."}, 500


@investment_bp.route("/api/valuation-lead", methods=["POST"])
@limiter.limit("3 per minute")
def send_valuation_form_lead():
    request.max_content_length = 32 * 1024
    payload = request.get_json(silent=True)
    if not isinstance(payload, dict) or not _public_form_verified(payload):
        return _public_form_error()
    try:
        response_payload, status = send_valuation_lead(payload)
        return jsonify(response_payload), status
    except Exception as exc:
        current_app.logger.error("Valuation lead error [request_id=%s] (%s)", current_request_id(), type(exc).__name__)
        return jsonify({"success": False, "error": "Server error."}), 500


@investment_bp.route("/api/franczyza/availability", methods=["GET"])
def franchise_meeting_availability_api():
    try:
        return jsonify(get_public_franchise_availability())
    except Exception as exc:
        current_app.logger.error("Franchise availability error (%s)", type(exc).__name__)
        return jsonify({"success": False, "error": "Nie udało się pobrać dostępnych terminów."}), 500


@investment_bp.route("/api/franczyza/book-meeting", methods=["POST"])
@limiter.limit("3 per minute")
def franchise_meeting_booking_api():
    request.max_content_length = 32 * 1024
    payload = request.get_json(silent=True)
    if not isinstance(payload, dict) or not _public_form_verified(payload):
        return _public_form_error()
    try:
        response_payload, status = book_public_franchise_meeting(payload)
        return jsonify(response_payload), status
    except Exception as exc:
        current_app.logger.error("Franchise meeting booking error [request_id=%s] (%s)", current_request_id(), type(exc).__name__)
        return jsonify({"success": False, "error": "Nie udało się zapisać spotkania."}), 500
