"""Read-only repository for domestic CRM offers.

Writes remain in the existing route transaction boundaries.
"""
from modules.classes import DatabaseConnectionManager


def get_location_values(column_name, wojewodztwo=None, normalize_label=None):
    if column_name not in {"Wojewodztwo", "Powiat"}:
        return []

    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        if wojewodztwo and column_name == "Powiat":
            cursor.execute(
                f"""
                SELECT Wojewodztwo, {column_name}
                FROM localization
                WHERE Wojewodztwo IS NOT NULL AND TRIM(Wojewodztwo) != ''
                  AND {column_name} IS NOT NULL AND TRIM({column_name}) != ''
                """
            )
            normalized_target = normalize_label(wojewodztwo)
            normalized_matches = []
            for row in cursor.fetchall():
                if not row or len(row) < 2:
                    continue
                region_value, district_value = row[0], row[1]
                if normalize_label(region_value) != normalized_target:
                    continue
                district_text = str(district_value).strip()
                if district_text:
                    normalized_matches.append(district_text)
            return sorted(set(normalized_matches))

        cursor.execute(
            f"""
            SELECT DISTINCT {column_name}
            FROM localization
            WHERE {column_name} IS NOT NULL AND TRIM({column_name}) != ''
            ORDER BY {column_name}
            """
        )
        return [row[0] for row in cursor.fetchall() if row and row[0]]


def fetch_portal_sync_map(conn, offer_ids):
    if not offer_ids:
        return {}

    try:
        placeholders = ",".join("?" for _ in offer_ids)
        cursor = conn.cursor()
        cursor.execute(
            f"""
            SELECT offer_id, portal_key, is_published, needs_update, last_action, last_uploaded_at, last_error
            FROM offer_portal_sync
            WHERE offer_id IN ({placeholders})
            """,
            tuple(int(offer_id) for offer_id in offer_ids),
        )
        rows = cursor.fetchall()
    except Exception:
        return {}

    result = {}
    for row in rows:
        offer_id = int(row[0])
        portal_key = str(row[1])
        result.setdefault(offer_id, {})[portal_key] = {
            "is_published": int(row[2] or 0),
            "needs_update": int(row[3] or 0),
            "last_action": row[4],
            "last_uploaded_at": row[5],
            "last_error": row[6],
        }
    return result


def list_offers(is_master, user_id):
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        if is_master:
            cursor.execute(
                """
                SELECT e.*, l.*
                FROM estatedata e
                LEFT JOIN localization l ON e.id = l.id
                ORDER BY e.ID DESC
                """
            )
        else:
            cursor.execute(
                """
                SELECT e.*, l.*
                FROM estatedata e
                LEFT JOIN localization l ON e.id = l.id
                WHERE e.ID_agenta = ?
                ORDER BY e.ID DESC
                """,
                (user_id,),
            )

        rows = cursor.fetchall()
        columns = [column[0] for column in cursor.description]
        offers = [dict(zip(columns, row)) for row in rows]
        offer_ids = [offer.get("ID") for offer in offers if offer.get("ID") is not None]
        portal_sync_map = fetch_portal_sync_map(conn, offer_ids)

        for offer in offers:
            offer_id = offer.get("ID")
            try:
                offer["Portal_sync"] = portal_sync_map.get(int(offer_id), {})
            except Exception:
                offer["Portal_sync"] = {}
        return offers


def get_offer_card_data(offer_id):
    with DatabaseConnectionManager() as conn:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT e.*, l.Miejscowosc, l.Wojewodztwo, l.Powiat, l.Gmina, l.Ulica
            FROM estatedata e
            LEFT JOIN localization l ON l.ID = e.ID
            WHERE e.ID = ?
            """,
            (offer_id,),
        )
        row = cursor.fetchone()
        if not row:
            return None
        columns = [column[0] for column in cursor.description]
        return dict(zip(columns, row))


def get_offer_card_agent(agent_id):
    if agent_id is None:
        return None
    try:
        with DatabaseConnectionManager("agents") as conn:
            cursor = conn.cursor()
            try:
                cursor.execute(
                    """
                    SELECT first_name, last_name, email, phone, license
                    FROM agents_v2
                    WHERE id = ?
                      AND is_active = 1
                    """,
                    (agent_id,),
                )
                return cursor.fetchone()
            except Exception:
                try:
                    cursor.execute(
                        """
                        SELECT first_name, last_name, email, phone
                        FROM agents_v2
                        WHERE id = ?
                        """,
                        (agent_id,),
                    )
                    row = cursor.fetchone()
                    return (row[0], row[1], row[2], row[3], "") if row else None
                except Exception:
                    return None
    except Exception:
        return None
