import logging
import re

from .aliases import NO_ALIASES
from .dictionaries import map_no_code


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 build_no_payload(offer_data, location_data):
    available_from = str(offer_data[8] or "")
    available_parts = available_from.split("-")
    available_year = available_parts[0] if len(available_parts) > 0 else ""
    available_month = available_parts[1] if len(available_parts) > 1 else ""
    missing_mappings = []

    def _map(section, value, default=""):
        return map_no_code(section, value, aliases=NO_ALIASES.get(section, {}), default=default)

    def _resolve_or_track(field_name, section, source_value, default=""):
        resolved_value = _map(section, source_value, default=default)

        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

    total_floors = _normalize_int_value(offer_data[17]) or "0"
    floor = _map("floor", offer_data[18], default=_normalize_int_value(offer_data[18]) or "0")
    rooms = _normalize_int_value(offer_data[21]) or "1"
    description = str(offer_data[36] if len(offer_data) > 36 else "")
    description = re.sub(r"\s+", " ", description).strip()

    payload = {
        "id": offer_data[0],
        "idCategory": _resolve_or_track("idCategory", "idCategory", offer_data[1]),
        "idAdType": _resolve_or_track("idAdType", "idAdType", offer_data[2]),
        "idRegion": _resolve_or_track("idRegion", "idRegion", location_data[2]),
        "idMarketType": _resolve_or_track("idMarketType", "idMarketType", offer_data[3]),
        "districtName": location_data[3],
        "communeName": location_data[4],
        # offer_data[4] - country
        "cityName": offer_data[5],
        "streetName": location_data[5],  # instead of offer_data[6] - location
        "price": offer_data[7],
        "availableFrom": available_from,
        "availableYear": available_year,
        "availableMonth": available_month,
        # offer_data[9] - status
        "areaPlot": offer_data[10],
        "jPlotSituationLookType": _resolve_or_track(
            "jPlotSituationLookType", "jPlotSituationLookType", offer_data[11]
        ),
        "idPlotShapeType": _resolve_or_track("idPlotShapeType", "idPlotShapeType", offer_data[12]),
        "idBuildingType": _resolve_or_track("idBuildingType", "idBuildingType", offer_data[13]),
        "idBuildingType_d": _resolve_or_track("idBuildingType_d", "idBuildingType", offer_data[14]),
        "idRoofType": _resolve_or_track("idRoofType", "idRoofType", offer_data[15]),
        "idGarageType": _resolve_or_track("idGarageType", "idGarageType", offer_data[16], default="0"),
        "totalFloors": total_floors,
        "floor": floor,
        "area": offer_data[19],
        "areaUse": offer_data[20],
        "rooms": rooms,
        "isFurnished": _resolve_or_track("isFurnished", "isFurnished", offer_data[22]),
        "jWindows": _resolve_or_track("jWindows", "jWindows", offer_data[23]),
        "jKitchen": _resolve_or_track("jKitchen", "jKitchen", offer_data[24]),
        "idSewageType": _resolve_or_track("idSewageType", "idSewageType", offer_data[25]),
        "jHeatingType": _resolve_or_track("jHeatingType", "jHeatingType", offer_data[26]),
        "isMElectricity": _resolve_or_track("isMElectricity", "isMElectricity", offer_data[27]),
        "isMGas": _resolve_or_track("isMGas", "isMGas", offer_data[28]),
        "rent": offer_data[29],
        "idPlotType": _resolve_or_track("idPlotType", "idPlotType", offer_data[30]),
        "idConditionType_b": _resolve_or_track("idConditionType_b", "idConditionType", offer_data[31]),
        "idBPDestType": _resolve_or_track("idBPDestType", "idBPDestType", offer_data[32]),
        "idConditionType_n": _resolve_or_track("idConditionType_n", "idConditionType", offer_data[33]),
        "yearBuilt": _normalize_int_value(offer_data[34]),
        "idAgent": offer_data[35],
        "Description": description,
    }

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

    return payload
