﻿from datetime import datetime

from flask import Blueprint, abort, current_app, jsonify, render_template, request, url_for
from flask_mail import Message
from flask_limiter.errors import RateLimitExceeded

from InvestmentWebsite.services.platform_logger import save_platform_log
from modules.core.extensions import mail, limiter
from InvestmentWebsite.offers.platform_content import REGIONS
from InvestmentWebsite.offers.platform_facade import (
    build_email_content,
    build_lead_log_data,
    build_lead_payload,
    build_phone_view_payload,
    get_lead_recipients,
    get_platform_data,
    safe_http_url,
    validate_lead_payload,
)
from InvestmentWebsite.offers.lead_spam_guard import (
    FORM_TOKEN_FIELD,
    HONEYPOT_FIELD,
    check_form_token,
    detect_spam,
    issue_form_token,
    security_log_data,
    validate_lead_limits,
)
from InvestmentWebsite.services.http_helpers import cacheable_response
from InvestmentWebsite.seo import build_landing_head, build_breadcrumb_json_ld
from integrations.tripinvest.config import DUBAI_AREAS_GEO, SPAIN_AREAS_GEO

platform_bp = Blueprint("platform", __name__)


@platform_bp.app_context_processor
def _lead_form_guard_context():
    # Used by templates/components/platform_form.html on every platform page.
    return {
        "lead_form_token": issue_form_token,
        "lead_form_token_field": FORM_TOKEN_FIELD,
        "lead_form_honeypot_field": HONEYPOT_FIELD,
    }


@platform_bp.route("/nieruchomosci/hiszpania")
def hiszpania_hub():
    region_slugs = ["costa-del-sol", "costa-blanca", "lanzarote"]
    region_bg = {
        "costa-del-sol": "/static/images/costa_del_sol.webp",
        "costa-blanca": "/static/images/costa_blanca.webp",
        "lanzarote": "/static/images/lanzarote.webp",
    }
    region_markers = []

    for slug in region_slugs:
        region_data = REGIONS.get(slug)
        geo = SPAIN_AREAS_GEO.get(slug)

        if not region_data or not geo:
            continue

        region_markers.append({
            "slug": slug,
            "label": region_data["title"],
            "lat": geo["lat"],
            "lng": geo["lng"],
            "description": region_data["subtitle"],
            "region_url": url_for("platform.hiszpania_region", region_slug=slug),
            "catalog_url": (
                url_for("lanzarote.lanzarote_catalog")
                if slug == "lanzarote"
                else url_for("tripinvest.tripinvest_area_catalog", area=slug)
            ),
            "bg_image": region_bg.get(slug),
        })

    spain_map = {
        "center": [38.0, -2.5],
        "zoom": 5,
        "region": {
            "label": "Hiszpania",
            "description": (
                "Wybierz region na mapie, aby sprawdzić jego charakter inwestycyjny "
                "i przejść do dedykowanej strony ofert."
            ),
            "region_url": url_for("platform.hiszpania_hub"),
            "catalog_url": url_for("platform.hiszpania_hub"),
            "bg_image": "/static/images/hiszpania_hero_2.webp",
        },
        "regions": region_markers,
    }

    return cacheable_response(
        "hiszpania.html",
        head=build_landing_head(
            page_title="Nieruchomości w Hiszpanii | Investment Nieruchomości",
            meta_description="Nieruchomości inwestycyjne w Hiszpanii: Costa Blanca, Costa del Sol i Lanzarote. Sprawdź regiony i oferty.",
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/hiszpania_hero.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona główna", f"{request.url_root.rstrip('/')}/"),
                        ("Nieruchomości w Hiszpanii", request.base_url),
                    ]
                )
            ],
        ),
        spain_map=spain_map,
    )


@platform_bp.route("/nieruchomosci/dubaj")
def dubaj_hub():
    region_geo = DUBAI_AREAS_GEO.get("dubaj")
    city_markers = []

    for slug, item in DUBAI_AREAS_GEO.items():
        if item.get("type") != "district":
            continue

        city_markers.append({
            "slug": slug,
            "label": item.get("label", slug),
            "lat": item.get("lat"),
            "lng": item.get("lng"),
            "description": (
                f"{item.get('label', slug)} to jedna z najczęściej wybieranych lokalizacji "
                "inwestycyjnych w Dubaju."
            ),
            "offer_url": url_for("avarten.avarten_dubaj_catalog"),
        })

    dubai_map = {
        "center": [region_geo.get("lat"), region_geo.get("lng")] if region_geo else [25.2048, 55.2708],
        "zoom": 10,
        "region": {
            "label": region_geo.get("label", "Dubaj") if region_geo else "Dubaj",
            "lat": region_geo.get("lat", 25.2048) if region_geo else 25.2048,
            "lng": region_geo.get("lng", 55.2708) if region_geo else 55.2708,
            "description": (
                "Dubaj to dynamiczny rynek nieruchomości premium z wysokim popytem "
                "na zakup i wynajem. Kliknij dzielnicę na mapie, aby zobaczyć jej położenie i charakter."
            ),
            "offer_url": url_for("avarten.avarten_dubaj_catalog"),
        },
        "cities": city_markers,
    }

    return cacheable_response(
        "dubaj.html",
        head=build_landing_head(
            page_title="Nieruchomości w Dubaju | Investment Nieruchomości",
            meta_description="Nieruchomości inwestycyjne w Dubaju. Sprawdź lokalizacje i oferty mieszkań oraz apartamentów premium.",
            canonical_url=request.base_url,
            image_url=url_for("static", filename="images/dubai_hero.webp", _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona główna", f"{request.url_root.rstrip('/')}/"),
                        ("Nieruchomości w Dubaju", request.base_url),
                    ]
                )
            ],
        ),
        dubai_map=dubai_map,
    )


@platform_bp.route("/nieruchomosci/hiszpania/<region_slug>")
def hiszpania_region(region_slug):
    region = REGIONS.get(region_slug)
    if not region:
        abort(404)

    region_geo = SPAIN_AREAS_GEO.get(region_slug)
    region_map = None

    if region_geo:
        coast_key = region_geo.get("coast")
        coast_label = (
            "Costa Blanca" if coast_key == "costa-blanca"
            else "Costa del Sol" if coast_key == "costa-del-sol"
            else "Lanzarote"
        )
        city_markers = []

        for slug, item in SPAIN_AREAS_GEO.items():
            if item.get("coast") != coast_key:
                continue
            if item.get("type") != "city":
                continue

            city_markers.append({
                "slug": slug,
                "label": item.get("label", slug),
                "lat": item.get("lat"),
                "lng": item.get("lng"),
                "coast_label": coast_label,
                "description": (
                    f"{item.get('label', slug)} to lokalizacja w regionie {coast_label}, "
                    "popularna wśród osób szukających nieruchomości wakacyjnych i inwestycyjnych."
                ),
                "offer_url": (
                    url_for("lanzarote.lanzarote_catalog")
                    if coast_key == "lanzarote"
                    else url_for("tripinvest.tripinvest_area_catalog", area=slug)
                ),
            })

        region_map = {
            "center": [region_geo.get("lat"), region_geo.get("lng")],
            "zoom": 9 if region_geo.get("type") == "region" else 11,
            "coast_label": coast_label,
            "region": {
                "label": region_geo.get("label", region_slug),
                "lat": region_geo.get("lat"),
                "lng": region_geo.get("lng"),
                "description": (
                    f"{region['title']} to jeden z kluczowych obszarów hiszpańskiego rynku nieruchomości. "
                    "Sprawdź oferty z całego regionu lub kliknij konkretne miasto na mapie."
                ),
                "offer_url": (
                    url_for("lanzarote.lanzarote_catalog")
                    if region_slug == "lanzarote"
                    else url_for("tripinvest.tripinvest_area_catalog", area=region_slug)
                ),
            },
            "cities": city_markers,
        }

    return render_template(
        "hiszpania_region.html",
        head=build_landing_head(
            page_title=f"{region['title']} | Investment Nieruchomości",
            meta_description=f"{region['title']} - nieruchomości inwestycyjne i wakacyjne w Hiszpanii. Sprawdź charakter regionu i oferty.",
            canonical_url=request.base_url,
            image_url=url_for("static", filename=region["hero_webp"], _external=True),
            json_ld=[
                build_breadcrumb_json_ld(
                    [
                        ("Strona główna", f"{request.url_root.rstrip('/')}/"),
                        ("Nieruchomości w Hiszpanii", f"{request.url_root.rstrip('/')}/nieruchomosci/hiszpania"),
                        (region["title"], request.base_url),
                    ]
                )
            ],
        ),
        region_title=region["title"],
        region_subtitle=region["subtitle"],
        region_hero_webp=region["hero_webp"],
        region_hero_webp_2=region["hero_webp_2"],
        region_why=region["why"],
        region_dream_title=region["dream_title"],
        region_dream_text=region["dream_text"],
        region_slug=region_slug,
        region_map=region_map,
    )


# =========================
# SEND LEAD
# =========================
@platform_bp.route("/api/platform_send_lead", methods=["POST"])
@limiter.limit("3 per minute")
def platform_send_lead():
    now = datetime.utcnow()

    try:
        payload = build_lead_payload(request, normalize_urls=False)

        # INV-SEC-002: drop automated submissions before anything is logged or mailed.
        spam_reason = detect_spam(request.form)
        if spam_reason is None:
            token_reason = check_form_token(request.form.get(FORM_TOKEN_FIELD))
            if token_reason == "too_fast":
                spam_reason = token_reason
            elif token_reason:
                save_platform_log(security_log_data(now, payload, token_reason), "security")
                return jsonify({
                    "success": False,
                    "error": "Formularz wygasł. Odśwież stronę i spróbuj ponownie.",
                }), 400
        if spam_reason:
            save_platform_log(security_log_data(now, payload, spam_reason), "security")
            return jsonify({"success": True})

        validation_error_key, validation_error_message = validate_lead_payload(payload)
        if not validation_error_key:
            validation_error_key, validation_error_message = validate_lead_limits(payload)
        if validation_error_key:
            log_data = security_log_data(now, payload, validation_error_key)
            log_data["status"] = "validation_error"
            log_data["error"] = validation_error_key
            save_platform_log(log_data, "validation")
            return jsonify({"success": False, "error": validation_error_message}), 400

        # Validate original URLs before sanitization can turn invalid input into
        # an acceptable empty optional field. Keep normalized storage/mail data.
        for key in ("offer_url", "platform_page_url"):
            payload[key] = safe_http_url(payload[key])
        log_data = build_lead_log_data(now, payload)

        platform_data = get_platform_data(payload["platform"])
        email_content = build_email_content(now, payload, platform_data)
        recipients = get_lead_recipients()

        msg = Message(
            subject=email_content["subject"],
            recipients=recipients,
            body=email_content["text_body"],
            html=email_content["html_body"],
            reply_to=email_content["reply_to"],
        )

        mail.send(msg)


        log_data["status"] = "sent"
        save_platform_log(log_data, "leads")

        return jsonify({"success": True})

    except Exception as e:
        log_data = {
            "timestamp": str(now),
            "ip": request.remote_addr,
            "status": "server_error",
            "error": type(e).__name__
        }

        save_platform_log(log_data, "errors")

        current_app.logger.error("Platform lead error (%s)", type(e).__name__)

        return jsonify({
            "success": False,
            "error": "Server error."
        }), 500

# =========================
# PHONE VIEW
# =========================
@platform_bp.route("/api/platform_phone_view", methods=["POST"])
# Anonymous and written to platform_logs.db: bounded per IP. A visitor reveals
# a number a few times at most, so this never limits real use.
@limiter.limit("20 per minute")
def platform_phone_view():

    now = datetime.utcnow()

    try:
        payload = build_phone_view_payload(request)
        log_data = {
            "timestamp": str(now),
            "ip": payload["ip"],
            "user_agent": payload["user_agent"],
            "platform": payload["platform"],
            "offer_url": payload["offer_url"],
            "platform_page_url": payload["platform_page_url"],
            "event": "phone_view",
        }

        save_platform_log(log_data, "phone_views")

        return jsonify({"success": True})

    except Exception as e:
        current_app.logger.error(f"Phone view error: {e}")
        return jsonify({"success": False}), 500


# =========================
# RATE LIMIT HANDLER
# =========================
@platform_bp.errorhandler(RateLimitExceeded)
def handle_rate_limit(e):

    now = datetime.utcnow()

    save_platform_log({
        "timestamp": str(now),
        "ip": request.remote_addr,
        "status": "rate_limit"
    }, "rate_limit")

    return jsonify({
        "success": False,
        "error": "Too many requests. Please try again later."
    }), 429


