import logging
import re
import unicodedata

from .aliases import DOMIPORTA_ALIASES
from .dictionaries import map_category_code, map_feature_code

_ALLOWED_CURRENCIES = {"PLN", "CHF", "EUR", "GBP", "SEK", "USD"}
_LOCAL_BUILDING_TYPE_IDS = {
    "191": {
        "blok": "10432",
        "blok mieszkalny": "10432",
        "apartamentowiec": "10433",
        "kamienica": "10434",
        "dom wielorodzinny": "10435",
        "mieszkalny": "10432",
        "budynek wolnostojacy": "10436",
        "budynek wolnostojący": "10436",
        "inny": "10436",
    },
    "192": {
        "blizniak": "317",
        "bliźniak": "317",
        "kamienica": "324",
        "dom wolnostojacy": "326",
        "dom wolnostojący": "326",
        "wolnostojacy": "326",
        "wolnostojący": "326",
        "dom szeregowy": "10437",
        "szeregowiec": "10437",
        "rekreacyjny": "321",
        "mieszkalny": "327",
        "budynek wolnostojacy": "327",
        "budynek wolnostojący": "327",
        "dom z funkcja uslugowa": "327",
        "dom z funkcją usługową": "327",
        "inny": "327",
    },
}
_LOCAL_SEWERAGE_IDS = {
    "192": {
        "miejska": "462",
        "kanalizacja": "462",
        "w drodze": "462",
        "szambo": "463",
        "brak": "10471",
        "oczyszczalnia": "10574",
        "oczyszczalnia sciekow": "10574",
        "oczyszczalnia ścieków": "10574",
    },
    "193": {
        "miejska": "479",
        "kanalizacja": "479",
        "w drodze": "479",
        "szambo": "480",
        "brak": "10472",
        "oczyszczalnia": "10575",
        "oczyszczalnia sciekow": "10575",
        "oczyszczalnia ścieków": "10575",
    },
    "0": {
        "miejska": "11581",
        "kanalizacja": "11581",
        "w drodze": "11581",
        "szambo": "11580",
        "brak": "11579",
        "oczyszczalnia": "11582",
        "oczyszczalnia sciekow": "11582",
        "oczyszczalnia ścieków": "11582",
    },
}
_LOCAL_PLOT_TYPE_IDS = {
    "budowlana": "415",
    "komercyjna": "416",
    "uslugowa": "416",
    "usługowa": "416",
    "budowlano uslugowa": "416",
    "budowlano-usługowa": "416",
    "lesna": "417",
    "leśna": "417",
    "lesna z prawem budowy": "418",
    "leśna z prawem budowy": "418",
    "przemyslowo handlowa": "419",
    "przemysłowo handlowa": "419",
    "sklady": "419",
    "składy": "419",
    "składy magazyny": "419",
    "składy, magazyny": "419",
    "rekreacyjna": "420",
    "rolna": "421",
    "budowlano rolna": "421",
    "budowlano-rolna": "421",
    "siedliskowa": "422",
    "inwestycyjna": "423",
    "inna": "424",
}
_LOCAL_COMMERCIAL_USAGE_IDS = {
    "biuro": "1061",
    "biurowe": "1061",
    "biurowy": "1061",
    "magazyn": "1062",
    "uslugi": "1063",
    "usługi": "1063",
    "uslugowy": "1063",
    "usługowy": "1063",
    "handlowo uslugowy": "1063",
    "handlowo-usługowy": "1063",
    "handel": "1064",
    "gastronomia": "1065",
    "gastronomiczny": "1065",
    "gabinet": "1066",
    "warsztat": "1067",
    "pawilon": "1068",
    "hala": "1069",
    "centrum dystrybucyjne": "1070",
    "centrum handlowe": "1071",
    "hotel pensjonat": "1072",
    "hotel-pensjonat": "1072",
    "noclegowe": "1072",
    "hotelowy": "1072",
    "produkcja": "1073",
    "inne": "1074",
}
_LOCAL_UTILITY_IDS = {
    "192": {"prad": "459", "prąd": "459", "gaz": "461"},
    "193": {"prad": "10263", "prąd": "10263", "gaz": "10265"},
}


def _normalize_label(value):
    text = "" if value is None else str(value).strip().lower()
    normalized = unicodedata.normalize("NFKD", text)
    ascii_only = "".join(ch for ch in normalized if not unicodedata.combining(ch))
    return " ".join(ascii_only.replace("-", " ").replace("_", " ").split())


def _normalize_int_value(value):
    if value is None:
        return ""
    text = str(value).strip()
    if not text or text.lower() == "nd":
        return ""
    try:
        return str(int(float(text.replace(",", "."))))
    except ValueError:
        return ""


def _normalize_decimal_value(value):
    if value is None:
        return ""
    text = str(value).strip()
    if not text or text.lower() == "nd":
        return ""
    text = text.replace(",", ".")
    try:
        return str(float(text))
    except ValueError:
        return ""


def _clean_text(value):
    if value is None:
        return ""
    return str(value).strip()


def _lookup_local_id(mapping, value, fallback_keys=()):
    normalized = _normalize_label(value)
    normalized_mapping = {_normalize_label(key): mapped_value for key, mapped_value in mapping.items()}
    if normalized in normalized_mapping:
        return normalized_mapping[normalized]
    for key in fallback_keys:
        normalized_key = _normalize_label(key)
        if normalized_key in normalized_mapping:
            return normalized_mapping[normalized_key]
    return ""


def _extract_agent_contact_fields(agent_data):
    agent_data = list(agent_data or [])

    def _get(idx, default=""):
        try:
            value = agent_data[idx]
            return "" if value is None else str(value).strip()
        except Exception:
            return default

    # The current gateway has an explicit nine-column agents_v2 contract.
    # Empty email must never reinterpret access_level (index 3) as a name.
    email_idx = {7: 3, 8: 5, 9: 6}.get(len(agent_data))
    for idx in (() if email_idx is not None else (3, 5, 6)):
        candidate = _get(idx)
        if "@" in candidate:
            email_idx = idx
            break

    if email_idx == 3:
        first_name = _get(1)
        last_name = _get(2)
        email = _get(3)
        phone = _get(4)
    elif email_idx == 6:
        first_name = _get(4)
        last_name = _get(5)
        email = _get(6)
        phone = _get(7)
    else:
        first_name = _get(3)
        last_name = _get(4)
        email = _get(5)
        phone = _get(6)

    full_name = " ".join(part for part in (first_name, last_name) if part).strip()
    return {
        "full_name": full_name or last_name,
        "email": email,
        "phone": phone.replace(" ", ""),
    }


def _normalize_price_currency(country_name, source_currency=None):
    source = _clean_text(source_currency).upper()
    if source in _ALLOWED_CURRENCIES:
        return source

    country = _normalize_label(country_name)
    if country in {"hiszpania", "spain"}:
        return "EUR"

    if country in {
        "dubaj",
        "dubai",
        "zea",
        "uae",
        "zjednoczone emiraty arabskie",
        "united arab emirates",
    }:
        return "PLN"

    return "PLN"


def build_domiporta_payload(offer_data, location_data, agent_data=None):
    missing_mappings = []

    def _track(field_name, source_value, resolved_value):
        if (
            not resolved_value
            and source_value is not None
            and str(source_value).strip()
            and str(source_value).strip().lower() != "nd"
        ):
            missing_mappings.append(f"{field_name}='{source_value}'")
        return resolved_value

    property_type = str(offer_data[1] or "")
    offer_type = str(offer_data[2] or "")
    market_type = str(offer_data[3] or "")

    category_id = map_category_code(
        property_type,
        aliases=DOMIPORTA_ALIASES["category"],
        default="196",
    )

    trade_operation_aliases = {
        _normalize_label(k): str(v) for k, v in DOMIPORTA_ALIASES["trade_operation"].items()
    }
    market_type_aliases = {_normalize_label(k): str(v) for k, v in DOMIPORTA_ALIASES["market_type"].items()}

    if offer_type in ("1", "2"):
        trade_operation = offer_type
    else:
        trade_operation = trade_operation_aliases.get(_normalize_label(offer_type), "1")

    market_type_value = market_type_aliases.get(_normalize_label(market_type), "secondary")

    price_raw = str(offer_data[7] or "0").replace(",", ".")
    try:
        price = f"{float(price_raw):.2f}"
    except ValueError:
        price = "0.00"

    country_name = _clean_text(offer_data[4] or "Polska")
    agent = _extract_agent_contact_fields(agent_data)

    description = str(offer_data[36] if len(offer_data) > 36 else "")
    description = re.sub(r"\s+", " ", description).strip()

    building_source = str(offer_data[13] or "") if category_id == "191" else str(offer_data[14] or "")
    building_type = _lookup_local_id(_LOCAL_BUILDING_TYPE_IDS.get(category_id, {}), building_source)
    if not building_type:
        building_type = map_feature_code(
            "typbudynku",
            building_source,
            category_id=category_id,
            aliases=DOMIPORTA_ALIASES["building_type"],
            default="",
        )
    building_type = _track("BuildingType", building_source, building_type)

    sewerage_source = str(offer_data[25] or "")
    sewerage = _lookup_local_id(
        _LOCAL_SEWERAGE_IDS.get(category_id, _LOCAL_SEWERAGE_IDS["0"]),
        sewerage_source,
    )
    if not sewerage:
        sewerage = map_feature_code(
            "kanalizacja",
            sewerage_source,
            category_id=category_id,
            aliases=DOMIPORTA_ALIASES["sewerage"],
            default="",
        )
    sewerage = _track("Sewerage", sewerage_source, sewerage)

    plot_source = str(offer_data[30] or "")
    plot_type = _lookup_local_id(_LOCAL_PLOT_TYPE_IDS, plot_source)
    if not plot_type:
        plot_type = map_feature_code(
            "rodzajdzialki",
            plot_source,
            category_id="193",
            aliases=DOMIPORTA_ALIASES["plot_type"],
            default="",
        )
    plot_type = _track("PlotType", plot_source, plot_type)

    usage_source = str(offer_data[32] or "")
    commercial_usage = _lookup_local_id(_LOCAL_COMMERCIAL_USAGE_IDS, usage_source)
    if not commercial_usage:
        commercial_usage = map_feature_code(
            "przeznaczenieallads",
            usage_source,
            category_id="196",
            aliases=DOMIPORTA_ALIASES["commercial_usage"],
            default="",
        )
    commercial_usage = _track("CommercialUsage", usage_source, commercial_usage)

    utilities = []
    for field_name, flag, utility_label in (("Prad", offer_data[27], "Prąd"), ("Gaz", offer_data[28], "Gaz")):
        if str(flag or "") != "Tak":
            continue

        utility = _lookup_local_id(_LOCAL_UTILITY_IDS.get(category_id, {}), utility_label)
        if not utility:
            utility = map_feature_code(
                "media",
                utility_label,
                category_id=category_id,
                aliases=DOMIPORTA_ALIASES["utility"],
                default="",
            )

        utility = _track(f"Utilities.{field_name}", utility_label, utility)
        if utility:
            utilities.append(utility)

    standard_value = ""
    if str(offer_data[33] or "") != "nd":
        standard_value = str(offer_data[33] or "")
    elif str(offer_data[31] or "") != "nd":
        standard_value = str(offer_data[31] or "")

    subject_area = _normalize_decimal_value(offer_data[19])
    plot_area = _normalize_decimal_value(offer_data[10])
    if not subject_area:
        subject_area = plot_area or "0"

    if missing_mappings:
        logging.warning("Domiporta missing mappings for offer %s: %s", offer_data[0], ", ".join(missing_mappings))

    return {
        "AdvertId": str(offer_data[0]),
        "TradeOperationType": trade_operation,
        "MarketType": market_type_value,
        "CategoryId": category_id,
        "Description": description,
        "Price": price,
        "PriceCurrency": _normalize_price_currency(country_name),
        "IsExclusiveOffer": "0",
        "CountryName": country_name,
        "RegionName": str(location_data[2] or ""),
        "CountyName": str(location_data[3] or ""),
        "CommunityName": str(location_data[4] or ""),
        "CityName": str(offer_data[5] or ""),
        "StreetName": str(location_data[5] or ""),
        "SubjectArea": subject_area,
        "RoomsCount": _normalize_int_value(offer_data[21]),
        "LivingArea": _normalize_decimal_value(offer_data[20]),
        "Floor": _normalize_int_value(offer_data[18]),
        "FloorsCount": _normalize_int_value(offer_data[17]),
        "ConstructionYear": _normalize_int_value(offer_data[34]),
        "PlotArea": plot_area,
        "BuildingType": building_type,
        "Sewerage": sewerage,
        "PlotType": plot_type,
        "CommercialUsage": [commercial_usage] if (commercial_usage and category_id == "196") else [],
        "Utilities": utilities,
        "Kitchen": "" if str(offer_data[24] or "") == "nd" else str(offer_data[24] or ""),
        "Standard": standard_value,
        "AgentIdentifier": _clean_text(agent_data[0] if agent_data and len(agent_data) > 0 else ""),
        "AgentName": agent["full_name"],
        "AgentEmail": agent["email"],
        "AgentPhone": agent["phone"],
    }
