import os
import time
import markdown
from collections import defaultdict
from functools import lru_cache, wraps

from flask import url_for

from modules.classes import DatabaseConnectionManager
from modules.core import storage_paths
from InvestmentWebsite.offers.record_schema import AGENT_WITH_BRANCH_IDX as ABIDX
from InvestmentWebsite.offers.record_schema import OFFER_IDX as IDX

# ======================================================
# CONSTANTS
# ======================================================

ALLOWED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
AGENT_AVATAR_EXTENSIONS = (".jpg", ".jpeg", ".png", ".webp")


def ttl_cache(ttl_seconds=120, maxsize=128):
    """
    Lightweight TTL wrapper on top of lru_cache.
    Cache is cleared for the whole function when TTL expires.
    """
    def decorator(func):
        cached_func = lru_cache(maxsize=maxsize)(func)
        expires_at = 0.0

        @wraps(func)
        def wrapper(*args, **kwargs):
            nonlocal expires_at
            now = time.monotonic()
            if now >= expires_at:
                cached_func.cache_clear()
                expires_at = now + ttl_seconds
            return cached_func(*args, **kwargs)

        wrapper.cache_clear = cached_func.cache_clear
        wrapper.cache_info = cached_func.cache_info
        return wrapper

    return decorator


# Offer-specific caches that can go stale after a CRM offer/media/description
# mutation. Names are resolved at call time so definition order does not
# matter. Agent caches (get_agents/get_branches/...) and OfferService's
# foreign-source cache are deliberately excluded -- they are owned/cleared
# elsewhere. The facet/count caches keep their 120s cross-worker TTL; clearing
# them here only makes the writing worker immediately fresh.
def invalidate_offer_caches():
    """Clear every offer-specific cache after a successful CRM offer mutation.

    Same worker: immediately fresh. Other Passenger workers: offer caches
    self-heal within <=30s, facet/count caches within <=120s (their TTL).
    """
    for func in (
        count_images,
        get_estate_description,
        video_exists,
        get_image_path,
        list_offer_image_filenames,
        get_normalized_filter_options,
        get_unique_filter_values,
        get_catalog_price_bounds,
        get_catalog_area_bounds,
        get_active_agents,
        get_estates_count_by_wojewodztwo,
    ):
        func.cache_clear()

# ======================================================
# PAGINATION UTILS
# ======================================================

def get_offset(page, per_page):
    return max(page - 1, 0) * per_page

# ======================================================
# MEDIA / FILESYSTEM
# ======================================================

@ttl_cache(ttl_seconds=30, maxsize=1024)
def count_images(estate_id):
    return len(list_offer_image_filenames(estate_id))

@ttl_cache(ttl_seconds=30, maxsize=1024)
def get_estate_description(estate_id):
    path = storage_paths.offer_dir(estate_id) / f"description_{estate_id}.md"

    if not os.path.exists(path):
        return ""

    with open(path, encoding="utf-8") as f:
        return markdown.markdown(f.read())

@ttl_cache(ttl_seconds=30, maxsize=1024)
def video_exists(estate_id):
    estate_id = str(estate_id)
    base = storage_paths.offer_dir(estate_id)

    for ext in (".mp4", ".webm"):
        if os.path.exists(os.path.join(base, f"video_{estate_id}{ext}")):
            return True

    return False

@ttl_cache(ttl_seconds=30, maxsize=4096)
def get_image_path(record_id):
    image_filenames = list_offer_image_filenames(record_id)
    if image_filenames:
        return url_for("static", filename=f"images/{record_id}/{image_filenames[0]}")

    return url_for("static", filename="images/no_image.svg")


def _extract_offer_image_index(filename):
    try:
        token = str(filename).split("_url_")[-1].split(".")[0]
        return int(token)
    except Exception:
        return 10**9


@ttl_cache(ttl_seconds=30, maxsize=4096)
def list_offer_image_filenames(record_id):
    record_id = str(record_id)
    photos_dir = storage_paths.offer_dir(record_id)

    if not os.path.isdir(photos_dir):
        return []

    files = []
    prefix = f"image_{record_id}_url_"
    for name in os.listdir(photos_dir):
        lower_name = name.lower()
        if not lower_name.startswith(prefix):
            continue
        if os.path.splitext(lower_name)[1] not in ALLOWED_IMAGE_EXTENSIONS:
            continue
        files.append(name)

    files.sort(key=lambda item: (_extract_offer_image_index(item), item.lower()))
    return files


def get_agent_avatar_url(agent_id):
    if not agent_id:
        return ""

    base_dir = storage_paths.agent_avatar_dir()
    for ext in AGENT_AVATAR_EXTENSIONS:
        filename = f"agent_{agent_id}{ext}"
        if (base_dir / filename).is_file():
            return url_for("static", filename=f"images/{filename}")

    return ""

# ======================================================
# AGENTS / BRANCHES
# ======================================================






@lru_cache(maxsize=128)
def get_agent_roles():
    with DatabaseConnectionManager("agents") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT ar.agent_id, GROUP_CONCAT(r.name, ', ')
            FROM agent_roles_v2 ar
            JOIN roles_v2 r ON r.id = ar.role_id
            GROUP BY ar.agent_id
        """)
        return cursor.fetchall()


@lru_cache(maxsize=128)
def get_agent_card_data(agent_id):
    if not agent_id:
        return None

    with DatabaseConnectionManager("agents") as conn:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT
                a.id,
                a.first_name,
                a.last_name,
                a.email,
                a.phone,
                a.license,
                (
                    SELECT GROUP_CONCAT(b.name, ', ')
                    FROM agent_branches_v2 ab
                    JOIN branches_v2 b ON b.id = ab.branch_id
                    WHERE ab.agent_id = a.id
                      AND b.is_active = 1
                ) AS branches_csv,
                (
                    SELECT GROUP_CONCAT(r.name, ', ')
                    FROM agent_roles_v2 ar
                    JOIN roles_v2 r ON r.id = ar.role_id
                    WHERE ar.agent_id = a.id
                ) AS roles_csv
            FROM agents_v2 a
            WHERE a.id = ?
              AND a.is_active = 1
            """,
            (agent_id,),
        )
        row = cursor.fetchone()

    if not row:
        return None

    return {
        "agent_id": row[0],
        "name": row[1],
        "surname": row[2],
        "email": row[3],
        "phone": row[4],
        "license": row[5],
        "branch": row[6],
        "roles": row[7],
        "avatar_url": get_agent_avatar_url(row[0]),
    }

# ======================================================
# ESTATES – CATALOG
# ======================================================

CATALOG_SELECT_SQL = """
    SELECT
        e.ID,
        e.Typ_nieruchomosci,
        e.Typ_oferty,
        e.Typ_rynku,
        e.Kraj,
        e.Miejscowosc,
        e.Lokalizacja,
        e.Cena,
        e.Powierzchnia_dzialki,
        e.Uksztaltowanie_dzialki,
        e.Ksztalt_dzialki,
        e.Powierzchnia,
        e.Liczba_pokoi,
        e.Stan_budynku,
        e.Stan_nieruchomosci,
        e.Tytul
"""

def build_catalog_query_parts(
    typ_nieruchomosci=None,
    typ_oferty=None,
    typ_rynku=None,
    stan_nieruchomosci=None,
    miejscowosc=None,
    wojewodztwo=None,
    kraj=None,
    cena_min=None,
    cena_max=None,
    powierzchnia_min=None,
    powierzchnia_max=None,
    agent_id=None,
    container_only=False,
    q=None,
):
    filters = ["e.Status_oferty = 'aktywna'"]
    values = []
    join_localization = False
    area_expression = """
        CASE
            WHEN CAST(e.Powierzchnia AS REAL) > 0 THEN CAST(e.Powierzchnia AS REAL)
            WHEN CAST(e.Powierzchnia_dzialki AS REAL) > 0 THEN CAST(e.Powierzchnia_dzialki AS REAL)
            ELSE NULL
        END
    """

    def add_exact_match_filter(column_sql, selected_value, table="EstateData"):
        variants = resolve_filter_value_variants(
            selected_value=selected_value,
            column=column_sql.split(".")[-1],
            table=table,
        )
        if not variants:
            return

        placeholders = ",".join("?" for _ in variants)
        filters.append(f"TRIM({column_sql}) IN ({placeholders})")
        values.extend(variants)

    if typ_nieruchomosci:
        add_exact_match_filter("e.Typ_nieruchomosci", typ_nieruchomosci)

    if typ_oferty:
        add_exact_match_filter("e.Typ_oferty", typ_oferty)

    if typ_rynku:
        add_exact_match_filter("e.Typ_rynku", typ_rynku)

    if stan_nieruchomosci:
        add_exact_match_filter("e.Stan_nieruchomosci", stan_nieruchomosci)

    if miejscowosc:
        join_localization = True
        add_exact_match_filter("l.Miejscowosc", miejscowosc, table="Localization")

    if wojewodztwo:
        join_localization = True
        add_exact_match_filter("l.Wojewodztwo", wojewodztwo, table="Localization")

    if kraj:
        add_exact_match_filter("e.Kraj", kraj)

    if cena_min is not None:
        filters.append("CAST(e.Cena AS REAL) >= ?")
        values.append(cena_min)

    if cena_max is not None:
        filters.append("CAST(e.Cena AS REAL) <= ?")
        values.append(cena_max)

    if powierzchnia_min is not None:
        filters.append(f"({area_expression}) >= ?")
        values.append(powierzchnia_min)

    if powierzchnia_max is not None:
        filters.append(f"({area_expression}) <= ?")
        values.append(powierzchnia_max)

    if agent_id:
        filters.append("e.ID_agenta = ?")
        values.append(agent_id)

    if container_only:
        filters.append("LOWER(COALESCE(e.Tytul, '')) LIKE ?")
        values.append("%kontener%")

    if q:
        q_clean = q.strip()
        if q_clean.isdigit():
            # Fast path for ID search.
            filters.append("e.ID = ?")
            values.append(int(q_clean))
        else:
            q_like = f"%{q_clean.lower()}%"
            query_values = [q_like] * 7
            filters.append("""
                (
                    LOWER(e.Typ_nieruchomosci) LIKE ?
                    OR LOWER(e.Typ_oferty) LIKE ?
                    OR LOWER(e.Typ_rynku) LIKE ?
                    OR LOWER(e.Kraj) LIKE ?
                    OR LOWER(e.Miejscowosc) LIKE ?
                    OR LOWER(e.Lokalizacja) LIKE ?
                    OR CAST(e.ID_agenta AS TEXT) LIKE ?
                )
            """)
            values.extend(query_values)

    where_clause = " AND ".join(filters)
    join_sql = "JOIN Localization l ON e.ID = l.ID" if join_localization else ""
    return where_clause, values, join_sql


def build_catalog_order_by(sort=None):
    area_expression = """
        CASE
            WHEN TRIM(COALESCE(e.Typ_nieruchomosci, '')) = 'Działka' AND CAST(e.Powierzchnia_dzialki AS REAL) > 0 THEN CAST(e.Powierzchnia_dzialki AS REAL)
            WHEN CAST(e.Powierzchnia AS REAL) > 0 THEN CAST(e.Powierzchnia AS REAL)
            ELSE NULL
        END
    """
    price_per_m2_expression = f"""
        CASE
            WHEN CAST(e.Cena AS REAL) > 0 AND ({area_expression}) > 0
                THEN CAST(e.Cena AS REAL) / ({area_expression})
            ELSE NULL
        END
    """
    sort_map = {
        "oldest": "ORDER BY e.ID ASC",
        "price_asc": "ORDER BY CAST(e.Cena AS REAL) ASC, e.ID DESC",
        "price_desc": "ORDER BY CAST(e.Cena AS REAL) DESC, e.ID DESC",
        "area_asc": f"ORDER BY ({area_expression}) IS NULL ASC, ({area_expression}) ASC, e.ID DESC",
        "area_desc": f"ORDER BY ({area_expression}) IS NULL ASC, ({area_expression}) DESC, e.ID DESC",
        "price_per_m2_asc": f"ORDER BY ({price_per_m2_expression}) IS NULL ASC, ({price_per_m2_expression}) ASC, e.ID DESC",
        "price_per_m2_desc": f"ORDER BY ({price_per_m2_expression}) IS NULL ASC, ({price_per_m2_expression}) DESC, e.ID DESC",
    }
    return sort_map.get(sort, "ORDER BY e.ID DESC")


def get_estates_catalog(
    typ_nieruchomosci=None,
    typ_oferty=None,
    typ_rynku=None,
    stan_nieruchomosci=None,
    miejscowosc=None,
    wojewodztwo=None,
    kraj=None,
    cena_min=None,
    cena_max=None,
    powierzchnia_min=None,
    powierzchnia_max=None,
    sort=None,
    agent_id=None,
    container_only=False,
    q=None,
    page=1,
    per_page=9
):
    offset = get_offset(page, per_page)
    where_clause, values, join_sql = build_catalog_query_parts(
        typ_nieruchomosci=typ_nieruchomosci,
        typ_oferty=typ_oferty,
        typ_rynku=typ_rynku,
        stan_nieruchomosci=stan_nieruchomosci,
        miejscowosc=miejscowosc,
        wojewodztwo=wojewodztwo,
        kraj=kraj,
        cena_min=cena_min,
        cena_max=cena_max,
        powierzchnia_min=powierzchnia_min,
        powierzchnia_max=powierzchnia_max,
        agent_id=agent_id,
        container_only=container_only,
        q=q,
    )
    order_by_clause = build_catalog_order_by(sort)

    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute(f"""
            SELECT COUNT(*)
            FROM EstateData e
            {join_sql}
            WHERE {where_clause}
        """, tuple(values))
        total_records = cursor.fetchone()[0]

        cursor.execute(f"""
            {CATALOG_SELECT_SQL}
            FROM EstateData e
            {join_sql}
            WHERE {where_clause}
            {order_by_clause}
            LIMIT ? OFFSET ?
        """, tuple(values + [per_page, offset]))
        estates = cursor.fetchall()

    return estates, total_records

# ======================================================
# FILTERS / HELPERS
# ======================================================

def _normalize_filter_key(value):
    return " ".join(str(value or "").strip().split()).casefold()


def _title_case_filter_label(value):
    normalized = " ".join(str(value or "").strip().split())
    if not normalized:
        return ""

    if normalized != normalized.lower():
        return normalized

    words = []
    for word in normalized.split(" "):
        parts = []
        for part in word.split("-"):
            parts.append(part[:1].upper() + part[1:] if part else "")
        words.append("-".join(parts))
    return " ".join(words)


def _choose_preferred_filter_label(values):
    candidates = []
    for raw_value in values:
        trimmed = " ".join(str(raw_value or "").strip().split())
        if not trimmed:
            continue
        candidates.append(trimmed)

    if not candidates:
        return ""

    def score(candidate):
        return (
            1 if candidate == candidate.lower() else 0,
            len(candidate),
            candidate,
        )

    preferred = min(candidates, key=score)
    return _title_case_filter_label(preferred)


@ttl_cache(ttl_seconds=120, maxsize=128)
def get_normalized_filter_options(column, table="EstateData", with_count=False, order_by_count=False):
    assert table in {"EstateData", "Localization"}

    join_sql = ""
    column_sql = f"e.{column}"

    if table == "Localization":
        join_sql = "JOIN Localization l ON e.ID = l.ID"
        column_sql = f"l.{column}"

    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute(f"""
            SELECT {column_sql}
            FROM EstateData e
            {join_sql}
            WHERE e.Status_oferty = 'aktywna'
              AND {column_sql} IS NOT NULL
              AND TRIM({column_sql}) != ''
        """)
        rows = [row[0] for row in cursor.fetchall()]

    grouped = defaultdict(list)
    for raw_value in rows:
        normalized_key = _normalize_filter_key(raw_value)
        if not normalized_key or normalized_key == "nd":
            continue
        grouped[normalized_key].append(raw_value)

    options = []
    for normalized_key, values in grouped.items():
        aliases = sorted({" ".join(str(item or "").strip().split()) for item in values if str(item or "").strip()})
        if not aliases:
            continue
        options.append(
            {
                "key": normalized_key,
                "label": _choose_preferred_filter_label(values),
                "values": aliases,
                "count": len(values),
            }
        )

    if with_count:
        if order_by_count:
            options.sort(key=lambda item: (-item["count"], item["label"]))
        else:
            options.sort(key=lambda item: item["label"])
        return [(item["label"], item["count"]) for item in options]

    options.sort(key=lambda item: item["label"])
    return options


def resolve_filter_value_variants(selected_value, column, table="EstateData"):
    normalized_key = _normalize_filter_key(selected_value)
    if not normalized_key:
        return []

    for option in get_normalized_filter_options(column=column, table=table):
        if option["key"] == normalized_key:
            return option["values"]

    fallback = " ".join(str(selected_value or "").strip().split())
    return [fallback] if fallback else []


def normalize_filter_selection(selected_value, column, table="EstateData"):
    normalized_key = _normalize_filter_key(selected_value)
    if not normalized_key:
        return None

    for option in get_normalized_filter_options(column=column, table=table):
        if option["key"] == normalized_key:
            return option["label"]

    fallback = " ".join(str(selected_value or "").strip().split())
    return _title_case_filter_label(fallback) if fallback else None


def normalize_numeric_range_value(value):
    if value in (None, "", "null"):
        return None

    try:
        numeric_value = int(float(value))
    except (TypeError, ValueError):
        return None

    return max(numeric_value, 0)

@ttl_cache(ttl_seconds=120, maxsize=128)
def get_unique_filter_values(
    column,
    table="EstateData",
    with_count=False,
    order_by_count=False
):
    options = get_normalized_filter_options(
        column=column,
        table=table,
        with_count=with_count,
        order_by_count=order_by_count,
    )
    if with_count:
        return options
    return [item["label"] for item in options]


@ttl_cache(ttl_seconds=120, maxsize=8)
def get_catalog_price_bounds():
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT MIN(CAST(Cena AS REAL)), MAX(CAST(Cena AS REAL))
            FROM EstateData
            WHERE Status_oferty = 'aktywna'
              AND Cena IS NOT NULL
              AND CAST(Cena AS REAL) > 0
        """)
        min_price, max_price = cursor.fetchone()

    min_price = int(min_price or 0)
    max_price = int(max_price or 0)
    if max_price <= 0:
        return {"min": 0, "max": 1000000, "step": 10000}

    step = 1000 if max_price <= 100000 else 5000 if max_price <= 500000 else 10000 if max_price <= 2000000 else 50000
    rounded_max = ((max_price + step - 1) // step) * step
    rounded_min = (min_price // step) * step

    return {
        "min": rounded_min,
        "max": rounded_max,
        "step": step,
    }


@ttl_cache(ttl_seconds=120, maxsize=8)
def get_catalog_area_bounds():
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT
                MIN(
                    CASE
                        WHEN CAST(Powierzchnia AS REAL) > 0 THEN CAST(Powierzchnia AS REAL)
                        WHEN CAST(Powierzchnia_dzialki AS REAL) > 0 THEN CAST(Powierzchnia_dzialki AS REAL)
                        ELSE NULL
                    END
                ),
                MAX(
                    CASE
                        WHEN CAST(Powierzchnia AS REAL) > 0 THEN CAST(Powierzchnia AS REAL)
                        WHEN CAST(Powierzchnia_dzialki AS REAL) > 0 THEN CAST(Powierzchnia_dzialki AS REAL)
                        ELSE NULL
                    END
                )
            FROM EstateData
            WHERE Status_oferty = 'aktywna'
        """)
        min_area, max_area = cursor.fetchone()

    min_area = int(min_area or 0)
    max_area = int(max_area or 0)
    if max_area <= 0:
        return {"min": 0, "max": 1000, "step": 1}

    step = 1 if max_area <= 200 else 5 if max_area <= 2000 else 10
    return {"min": min_area, "max": max_area, "step": step}
    
# ======================================================
# AGENTS – ACTIVE
# ======================================================

@ttl_cache(ttl_seconds=120, maxsize=128)
def get_active_agents():
    with DatabaseConnectionManager() as conn, DatabaseConnectionManager("agents") as agents_conn:
        cursor = conn.cursor()
        agents_cursor = agents_conn.cursor()

        cursor.execute("""
            SELECT DISTINCT ID_agenta
            FROM EstateData
            WHERE Status_oferty = 'aktywna'
              AND ID_agenta IS NOT NULL
        """)
        agent_ids = [row[0] for row in cursor.fetchall()]

        if not agent_ids:
            return []

        placeholders = ",".join("?" for _ in agent_ids)

        agents_cursor.execute(f"""
            SELECT id, first_name, last_name
            FROM agents_v2
            WHERE id IN ({placeholders})
              AND is_active = 1
            ORDER BY last_name
        """, agent_ids)

        return [
            (row[0], f"{row[1]} {row[2]}")
            for row in agents_cursor.fetchall()
        ]

def get_agent_email(agent_id):
    if not agent_id:
        return None

    with DatabaseConnectionManager("agents") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT email
            FROM agents_v2
            WHERE id = ?
              AND is_active = 1
        """, (agent_id,))
        row = cursor.fetchone()

    return row[0] if row else None

# ======================================================
# SINGLE OFFER
# ======================================================

def get_active_offer_lead_target(estate_id):
    with DatabaseConnectionManager() as conn:
        return conn.execute(
            "SELECT ID_agenta FROM EstateData WHERE ID = ? AND Status_oferty = 'aktywna'",
            (estate_id,),
        ).fetchone()


def get_estate_offer(estate_id):
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM EstateData WHERE ID = ?", (estate_id,))
        record = cursor.fetchone()

    if not record:
        return None

    agent_id = record[IDX.AGENT_ID]

    with DatabaseConnectionManager("agents") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT
                a.first_name,
                a.last_name,
                a.email,
                a.phone,
                a.license,
                (
                    SELECT GROUP_CONCAT(b2.name, ', ')
                    FROM agent_branches_v2 ab2
                    JOIN branches_v2 b2 ON b2.id = ab2.branch_id
                    WHERE ab2.agent_id = a.id
                      AND b2.is_active = 1
                ) AS branches_csv,
                (
                    SELECT GROUP_CONCAT(r.name, ', ')
                    FROM agent_roles_v2 ar
                    JOIN roles_v2 r ON r.id = ar.role_id
                    WHERE ar.agent_id = a.id
                ) AS roles_csv
            FROM agents_v2 a
            WHERE a.id = ?
              AND a.is_active = 1
        """, (agent_id,))
        agent_with_branch = cursor.fetchone()

    record_data = record + (count_images(record[IDX.ID]),)

    if agent_with_branch:
        record_data += agent_with_branch[:ABIDX.BRANCH]
        branch = agent_with_branch[ABIDX.BRANCH]
        roles = agent_with_branch[ABIDX.ROLES]
    else:
        record_data += (None, None, None, None, None)
        branch = None
        roles = None

    record_data += (branch, roles, get_estate_description(estate_id))

    return record_data, video_exists(estate_id)

# ======================================================
# STATS
# ======================================================

def slugify(text):
    return (
        text.lower()
        .replace("ą", "a").replace("ć", "c").replace("ę", "e")
        .replace("ł", "l").replace("ń", "n").replace("ó", "o")
        .replace("ś", "s").replace("ż", "z").replace("ź", "z")
        .replace(" ", "-")
    )
    
@ttl_cache(ttl_seconds=120, maxsize=32)
def get_estates_count_by_wojewodztwo():
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT l.Wojewodztwo, COUNT(*) as cnt
            FROM EstateData e
            JOIN Localization l ON e.ID = l.ID
            WHERE e.Status_oferty = 'aktywna'
            GROUP BY l.Wojewodztwo
            HAVING cnt > 0
            ORDER BY cnt DESC
        """)
        rows = cursor.fetchall()

    return [
        {"slug": slugify(name), "name": name, "count": count}
        for name, count in rows
    ]
