import logging
import re

from .aliases import OTODOM_ALIASES
from .dictionaries import map_otodom_code, map_otodom_codes


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_bool_01(value):
    text = "" if value is None else str(value).strip().lower()
    if text in {"1", "true", "tak", "yes"}:
        return "1"
    if text in {"0", "false", "nie", "no"}:
        return "0"
    return ""


def build_otodom_payload(offer_data, location_data, street_source="location"):
    if street_source == "offer":
        street_value = offer_data[6]
    else:
        street_value = location_data[5]

    missing_mappings = []

    def _resolve_or_track(field_name, source_value, dynamic_value, empty_value=""):
        if dynamic_value is None:
            resolved_value = empty_value
        elif isinstance(dynamic_value, str) and not dynamic_value.strip():
            resolved_value = empty_value
        elif isinstance(dynamic_value, (list, tuple, set, dict)) and len(dynamic_value) == 0:
            resolved_value = empty_value
        else:
            resolved_value = dynamic_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

    object_name = map_otodom_code(
        "Common",
        "ObjectName",
        offer_data[1],
        aliases=OTODOM_ALIASES["common_object_name"],
        default="",
    )
    offer_type = map_otodom_code(
        "Common",
        "OfferType",
        offer_data[2],
        aliases=OTODOM_ALIASES["common_offer_type"],
        default="",
    )
    market_type = map_otodom_code(
        "Common",
        "MarketType",
        offer_data[3],
        aliases=OTODOM_ALIASES["common_market_type"],
        default="",
    )
    province = map_otodom_code(
        "Common",
        "Province",
        location_data[2],
        default="",
    )
    building_type_m = _resolve_or_track(
        "FlatDetails.BuildingType",
        offer_data[13],
        map_otodom_code("FlatDetails", "BuildingType", offer_data[13], aliases=OTODOM_ALIASES["flat_building_type"]),
    )
    building_type_d = _resolve_or_track(
        "HouseDetails.BuildingType",
        offer_data[14],
        map_otodom_code("HouseDetails", "BuildingType", offer_data[14], aliases=OTODOM_ALIASES["house_building_type"]),
    )
    plot_type = _resolve_or_track(
        "TerrainDetails.Type",
        offer_data[30],
        map_otodom_code("TerrainDetails", "Type", offer_data[30], aliases=OTODOM_ALIASES["terrain_type"]),
    )
    construction_status_m = _resolve_or_track(
        "FlatDetails.ConstructionStatus",
        offer_data[33],
        map_otodom_code(
            "FlatDetails",
            "ConstructionStatus",
            offer_data[33],
            aliases=OTODOM_ALIASES["flat_construction_status"],
        ),
    )
    construction_status_d = _resolve_or_track(
        "HouseDetails.ConstructionStatus",
        offer_data[31],
        map_otodom_code(
            "HouseDetails",
            "ConstructionStatus",
            offer_data[31],
            aliases=OTODOM_ALIASES["house_construction_status"],
        ),
    )
    construction_status_l = _resolve_or_track(
        "CommercialPropertyDetails.ConstructionStatus",
        offer_data[33],
        map_otodom_code(
            "CommercialPropertyDetails",
            "ConstructionStatus",
            offer_data[33],
            aliases=OTODOM_ALIASES["commercial_construction_status"],
        ),
    )
    property_use = _resolve_or_track(
        "CommercialPropertyDetails.PropertyUseMask",
        offer_data[32],
        map_otodom_code(
            "CommercialPropertyDetails",
            "PropertyUseMask",
            offer_data[32],
            aliases=OTODOM_ALIASES["commercial_property_use"],
        ),
    )
    roofing = _resolve_or_track(
        "HouseDetails.Roofing",
        offer_data[15],
        map_otodom_code("HouseDetails", "Roofing", offer_data[15], aliases=OTODOM_ALIASES["house_roofing"]),
    )
    windows_m = _resolve_or_track(
        "FlatDetails.WindowsType",
        offer_data[23],
        map_otodom_code("FlatDetails", "WindowsType", offer_data[23], aliases=OTODOM_ALIASES["flat_windows_type"]),
    )
    windows_d = _resolve_or_track(
        "HouseDetails.WindowsType",
        offer_data[23],
        map_otodom_code("HouseDetails", "WindowsType", offer_data[23], aliases=OTODOM_ALIASES["house_windows_type"]),
    )
    heating_mask_d = _resolve_or_track(
        "HouseDetails.HeatingMask",
        offer_data[26],
        map_otodom_codes(
            "HouseDetails",
            "HeatingMask",
            [offer_data[26]],
            aliases=OTODOM_ALIASES["house_heating_mask"],
        ),
    )
    house_media_labels = []
    terrain_media_labels = []
    if str(offer_data[27] or "").strip() == "Tak":
        house_media_labels.append("prąd")
        terrain_media_labels.append("prąd")
    if str(offer_data[28] or "").strip() == "Tak":
        house_media_labels.append("gaz")
        terrain_media_labels.append("gaz")
    if str(offer_data[25] or "").strip().lower() in {"miejska", "miejski", "tak"}:
        house_media_labels.append("kanalizacja")
        terrain_media_labels.append("kanalizacja")

    media_mask_d = _resolve_or_track(
        "HouseDetails.MediaMask",
        ",".join(house_media_labels),
        map_otodom_codes("HouseDetails", "MediaMask", house_media_labels),
        [],
    )
    media_mask_t = _resolve_or_track(
        "TerrainDetails.MediaMask",
        ",".join(terrain_media_labels),
        map_otodom_codes("TerrainDetails", "MediaMask", terrain_media_labels),
        [],
    )
    property_use_mask = _resolve_or_track(
        "CommercialPropertyDetails.PropertyUseMask",
        offer_data[32],
        [property_use] if property_use else [],
        [],
    )
    heating_flat = _resolve_or_track(
        "FlatDetails.Heating",
        offer_data[26],
        map_otodom_code("FlatDetails", "Heating", offer_data[26], aliases=OTODOM_ALIASES["flat_heating"]),
    )
    floor_no = _resolve_or_track(
        "FlatDetails.FloorNo",
        offer_data[18],
        map_otodom_code("FlatDetails", "FloorNo", offer_data[18], aliases=OTODOM_ALIASES["flat_floor_no"], default="0"),
    )
    floors_num = _resolve_or_track(
        "HouseDetails.FloorsNum",
        offer_data[17],
        map_otodom_code(
            "HouseDetails",
            "FloorsNum",
            offer_data[17],
            aliases=OTODOM_ALIASES["house_floors_num"],
            default="0",
        ),
    )
    rooms_num = _normalize_int_value(offer_data[21]) or "1"
    building_floors_num = _normalize_int_value(offer_data[17]) or "0"
    terrain_area = _normalize_int_value(offer_data[10]) or "0"
    furnished = _normalize_bool_01(offer_data[22])
    description = str(offer_data[36] if len(offer_data) > 36 else "")
    description = re.sub(r"\s+", " ", description).strip()

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

    return {
        "ID": offer_data[0],
        "ObjectName": object_name,
        "OfferType": offer_type,
        "Province": province,
        "MarketType": market_type,
        "District": location_data[3],
        "City": offer_data[5],
        "Street": street_value,
        "Price": offer_data[7],
        "availableFrom": offer_data[8],
        "TerrainArea": terrain_area,
        "BuildingType_m": building_type_m,
        "BuildingType_l": "",
        "BuildingType_o": "",
        "BuildingType_d": building_type_d,
        "Roofing": roofing,
        "BuildingFloorsNum": building_floors_num,
        "FloorNo": floor_no,
        "Area": offer_data[19],
        "RoomsNum": rooms_num,
        "FloorsNum": floors_num,
        "Furnished": furnished,
        "WindowsType_m": windows_m,
        "WindowsType_d": windows_d,
        "HeatingMask": heating_mask_d,
        "Heating": heating_flat,
        "MediaMask_d": media_mask_d,
        "MediaMask_t": media_mask_t,
        "Rent": offer_data[29],
        "PlotType": plot_type,
        "ConstructionStatus_m": construction_status_m,
        "ConstructionStatus_d": construction_status_d,
        "ConstructionStatus_l": construction_status_l,
        "ConstructionStatus_o": "",
        "PropertyUseMask": property_use_mask,
        "BuildYear": offer_data[34],
        "idAgent": offer_data[35],
        "Description": description,
    }
