from datetime import datetime
import re
import unicodedata
from pathlib import Path
from flask import Response, render_template, request, send_from_directory
from modules.classes import DatabaseConnectionManager
from modules.core.config import BASE_DIR
from InvestmentWebsite.services.offer_urls import build_offer_path
from integrations.tripinvest.config import TRIPINVEST_AREAS_GROUPED, TRIPINVEST_FILTERS

HIDDEN_PREFIXES = ("/crm",)
LANZAROTE_CATALOG_CATEGORIES = (
    "flats",
    "apartments",
    "chalets",
    "houses",
    "plots_land",
    "business_premises",
    "offices",
    "buildings",
)

NOINDEX_NOFOLLOW_RULES = (
    lambda p: p.startswith("/api/"),
    lambda p: p.startswith("/nieruchomosci/ajax-json"),
    lambda p: p.startswith("/nieruchomosci/dubaj/catalog"),
    lambda p: p.startswith("/nieruchomosci/dubaj/oferta"),
    lambda p: p.startswith("/nieruchomosci/hiszpania/oferta"),
    lambda p: p.startswith("/nieruchomosci/hiszpania/lanzarote/offer"),
)

SITEMAP_BASE_URL = "https://investment-nieruchomosci.com"

SITEMAP_MAIN_PAGES = (
    "",
    "/o-nas",
    "/franczyza",
    "/dla-biznesu",
    "/franczyza/umow-spotkanie",
    "/nieruchomosci/polska",
    "/nieruchomosci",
    "/nieruchomosci/hiszpania",
    "/nieruchomosci/dubaj",
    "/nieruchomosci/hiszpania/costa-blanca",
    "/nieruchomosci/hiszpania/costa-del-sol",
    "/nieruchomosci/hiszpania/lanzarote",
)

SITEMAP_PAGE_TEMPLATES = {
    "": "strona_glowna.html",
    "/o-nas": "o_nas.html",
    "/franczyza": "franczyza.html",
    "/dla-biznesu": "dla_biznesu.html",
    "/franczyza/umow-spotkanie": "franchise_meeting.html",
    "/nieruchomosci/polska": "investment/polska.html",
    "/nieruchomosci": "investment/nieruchomosci.html",
    "/nieruchomosci/hiszpania": "hiszpania.html",
    "/nieruchomosci/dubaj": "dubaj.html",
    "/nieruchomosci/hiszpania/costa-blanca": "hiszpania_region.html",
    "/nieruchomosci/hiszpania/costa-del-sol": "hiszpania_region.html",
    "/nieruchomosci/hiszpania/lanzarote": "hiszpania_region.html",
}

SITEMAP_EXCLUDED_PREFIXES = (
    "/crm",
    "/nieruchomosci/dubaj/catalog",
    "/nieruchomosci/hiszpania/katalog",
)


def apply_robots_headers(response):
    path = request.path
    is_catalog_path = path == "/nieruchomosci" or path.startswith("/nieruchomosci/strona/")
    is_tripinvest_catalog_path = path == "/nieruchomosci/hiszpania/katalog" or path.startswith(
        "/nieruchomosci/hiszpania/katalog/"
    )
    is_poland_seo_catalog_path = path.startswith("/nieruchomosci/katalog/")
    has_query_params = bool(request.args)

    if any(path.startswith(prefix) for prefix in HIDDEN_PREFIXES):
        response.headers["X-Robots-Tag"] = "noindex, nofollow"
    elif is_catalog_path and has_query_params:
        # Filtered catalog URLs should not be indexed, but links can be followed.
        response.headers["X-Robots-Tag"] = "noindex, follow"
    elif is_tripinvest_catalog_path and has_query_params:
        response.headers["X-Robots-Tag"] = "noindex, follow"
    elif is_poland_seo_catalog_path and has_query_params:
        response.headers["X-Robots-Tag"] = "noindex, follow"
    elif path in {
        "/nieruchomosci/hiszpania/katalog",
        "/nieruchomosci/hiszpania/katalog/lanzarote",
    }:
        response.headers["X-Robots-Tag"] = "noindex, nofollow"
    elif any(rule(path) for rule in NOINDEX_NOFOLLOW_RULES):
        response.headers["X-Robots-Tag"] = "noindex, nofollow"

    return response


def _safe_iso_date(raw_date, fallback):
    if not raw_date:
        return fallback

    normalized = str(raw_date).strip()
    if len(normalized) >= 10:
        candidate = normalized[:10]
        try:
            datetime.strptime(candidate, "%Y-%m-%d")
            return candidate
        except ValueError:
            return fallback

    return fallback


def _template_lastmod(page_path, fallback):
    template_rel_path = SITEMAP_PAGE_TEMPLATES.get(page_path)
    if not template_rel_path:
        return fallback

    template_path = Path(BASE_DIR) / "InvestmentWebsite" / "templates" / template_rel_path
    if not template_path.exists():
        return fallback

    try:
        return datetime.utcfromtimestamp(template_path.stat().st_mtime).date().isoformat()
    except OSError:
        return fallback


def build_offer_sitemap_urls(base_url, fallback_date):
    urls = []

    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT ID, Data_dodania, Typ_nieruchomosci, Typ_oferty, Liczba_pokoi, Miejscowosc
            FROM EstateData
            WHERE Status_oferty = 'aktywna'
            ORDER BY ID DESC
            """
        )
        rows = cursor.fetchall()

    for offer_id, date_added, property_type, offer_type, rooms, city in rows:
        urls.append(
            {
                "loc": f"{base_url}{build_offer_path(offer_id, property_type, offer_type, rooms, city)}",
                "lastmod": _safe_iso_date(date_added, fallback_date),
                "changefreq": "daily",
                "priority": "0.8",
            }
        )

    return urls


def build_sitemap_urls(base_url=SITEMAP_BASE_URL):
    today = datetime.utcnow().date().isoformat()
    urls = []

    for page in SITEMAP_MAIN_PAGES:
        if any(page.startswith(prefix) for prefix in SITEMAP_EXCLUDED_PREFIXES):
            continue
        urls.append(
            {
                "loc": f"{base_url}{page}",
                "lastmod": _template_lastmod(page, today),
                "changefreq": "weekly",
                "priority": "0.9",
            }
        )

    urls.extend(build_offer_sitemap_urls(base_url, today))
    urls.extend(build_tripinvest_catalog_sitemap_urls(base_url, today))
    urls.extend(build_lanzarote_catalog_sitemap_urls(base_url, today))
    urls.extend(build_poland_catalog_sitemap_urls(base_url, today))

    return urls


def build_tripinvest_catalog_sitemap_urls(base_url, fallback_date):
    urls = []
    unique_areas = sorted(
        {
            area_slug
            for group in TRIPINVEST_AREAS_GROUPED.values()
            for area_slug in group.values()
        }
    )
    property_types = sorted(TRIPINVEST_FILTERS.keys())

    for area_slug in unique_areas:
        urls.append(
            {
                "loc": f"{base_url}/nieruchomosci/hiszpania/katalog/{area_slug}",
                "lastmod": fallback_date,
                "changefreq": "daily",
                "priority": "0.8",
            }
        )
        for property_type in property_types:
            urls.append(
                {
                    "loc": f"{base_url}/nieruchomosci/hiszpania/katalog/{area_slug}/{property_type}",
                    "lastmod": fallback_date,
                    "changefreq": "daily",
                    "priority": "0.7",
                }
            )

    return urls


def build_lanzarote_catalog_sitemap_urls(base_url, fallback_date):
    return [
        {
            "loc": f"{base_url}/nieruchomosci/hiszpania/katalog/lanzarote/{category}",
            "lastmod": fallback_date,
            "changefreq": "daily",
            "priority": "0.7",
        }
        for category in LANZAROTE_CATALOG_CATEGORIES
    ]


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_poland_catalog_sitemap_urls(base_url, fallback_date):
    urls = []
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT DISTINCT Typ_nieruchomosci, Typ_oferty
            FROM EstateData
            WHERE Status_oferty = 'aktywna'
              AND Typ_nieruchomosci IS NOT NULL
              AND TRIM(Typ_nieruchomosci) <> ''
            """
        )
        rows = cursor.fetchall()

    seen = set()
    for property_type, offer_type in rows:
        property_value = (property_type or "").strip()
        offer_value = (offer_type or "").strip()
        if not property_value:
            continue
        property_slug = _slugify(property_value)
        if offer_value:
            offer_slug = _slugify(offer_value)
            path = f"/nieruchomosci/katalog/{property_slug}/{offer_slug}"
        else:
            path = f"/nieruchomosci/katalog/{property_slug}"
        if path in seen:
            continue
        seen.add(path)
        urls.append(
            {
                "loc": f"{base_url}{path}",
                "lastmod": fallback_date,
                "changefreq": "daily",
                "priority": "0.7",
            }
        )

    return urls


def build_landing_head(
    *,
    page_title,
    meta_description=None,
    canonical_url=None,
    robots=None,
    theme_color="#478ac9",
    image_url=None,
    og_type="website",
    google_site_verification=None,
    og_title=None,
    og_description=None,
    og_url=None,
    twitter_title=None,
    twitter_description=None,
    twitter_card=None,
    twitter_image=None,
    json_ld=None,
):
    canonical = canonical_url or request.base_url
    resolved_og_title = og_title or page_title
    resolved_og_description = og_description or meta_description
    resolved_og_url = og_url or canonical

    head = {
        "page_title": page_title,
        "meta_description": meta_description,
        "canonical_url": canonical,
        "robots": robots,
        "theme_color": theme_color,
        "google_site_verification": google_site_verification,
        "og_title": resolved_og_title,
        "og_description": resolved_og_description,
        "og_type": og_type,
        "og_url": resolved_og_url,
        "twitter_title": twitter_title or resolved_og_title,
        "twitter_description": twitter_description or resolved_og_description,
    }

    if image_url:
        head["og_image"] = image_url
        head["twitter_card"] = twitter_card or "summary_large_image"
        head["twitter_image"] = twitter_image or image_url
    else:
        head["twitter_card"] = twitter_card or "summary"
        if twitter_image:
            head["twitter_image"] = twitter_image

    if json_ld:
        head["json_ld"] = json_ld

    return head


def build_breadcrumb_json_ld(items):
    return {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        "itemListElement": [
            {
                "@type": "ListItem",
                "position": i,
                "name": name,
                "item": item,
            }
            for i, (name, item) in enumerate(items, start=1)
        ],
    }


def build_real_estate_agent_json_ld(
    *,
    name,
    url,
    logo,
    image,
    telephone,
    email,
    street_address,
    address_locality,
    address_country="PL",
):
    return {
        "@context": "https://schema.org",
        "@type": "RealEstateAgent",
        "name": name,
        "url": url,
        "logo": logo,
        "image": image,
        "telephone": telephone,
        "email": email,
        "address": {
            "@type": "PostalAddress",
            "streetAddress": street_address,
            "addressLocality": address_locality,
            "addressCountry": address_country,
        },
    }


def register_seo(app):
    app.after_request(apply_robots_headers)

    @app.route("/robots.txt")
    def robots_txt():
        return send_from_directory(app.static_folder, "robots.txt")

    @app.route("/sitemap.xml")
    def sitemap():
        xml = render_template("sitemap.xml", urls=build_sitemap_urls())
        return Response(xml, mimetype="application/xml")

    @app.context_processor
    def inject_seo_helpers():
        return {"build_landing_head": build_landing_head}
