import base64
import datetime
import hashlib
import io
import os
import re
import shlex
import sqlite3
import tempfile
import unicodedata
import urllib.request
import zipfile
from contextlib import contextmanager
from pathlib import Path

from PIL import Image

from .foreign_tabelaofert_fields import effective_floor, investment_group_id, investment_group_name
from .local_gateway import get_agent_data
from . import runtime_paths
from .local_io import urlopen
from .portals.domiporta.renderer import render_xml_dp
from .portals.tabelaofert.renderer import render_xml_tabelaofert, render_xml_tabelaofert_many

DEFAULT_INVESTMENT_WEBSITE_BASE_URL = "https://investment-nieruchomosci.com"
DOMIPORTA_FOREIGN_CURRENCIES = {"PLN", "EUR", "USD", "GBP", "CHF", "SEK"}
TABELAOFERT_FOREIGN_CURRENCIES = {"PLN", "EUR", "USD", "CHF", "GBP", "THB", "AED"}
# source_platform of Cyprus Constructions developments and offers (Investment cyprus adapter).
CYPRUS_SOURCE_PLATFORM = "cyprus_constructions"


def get_foreign_offers_db_path() -> str:
    """Resolved via modules.runtime_paths.

    Used as a local file when it exists on this machine, otherwise as a remote
    POSIX path over SSH -- so it is kept as a string, never a (Windows) Path.
    """
    candidates = runtime_paths.foreign_offers_db_candidates()
    for candidate in candidates:
        if Path(candidate).exists():
            return candidate
    return candidates[0]


def get_foreign_offers_db_status() -> dict:
    path = get_foreign_offers_db_path()
    return {"path": path, "local_exists": Path(path).is_file(), "remote_exists": False, "mode": "local" if Path(path).is_file() else "missing"}


@contextmanager
def _open_read_connection():
    with runtime_paths.read_connection(runtime_paths.foreign_offers_db_path()) as conn:
        yield conn




def _sql_text(value) -> str:
    return str(value or "").replace("'", "''")






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


def _get_investment_website_base_url() -> str:
    return runtime_paths.current().website_base_url.rstrip("/")


def _encode_offer_token(raw_url: str) -> str:
    return base64.urlsafe_b64encode(raw_url.encode("utf-8")).decode("ascii").rstrip("=")


def _build_investment_offer_url(offer_row: sqlite3.Row) -> str:
    source_url = _clean_text(offer_row["source_url"])
    if not source_url:
        return ""

    platform = _normalize_label(offer_row["source_platform"])
    token = _encode_offer_token(source_url)
    base_url = _get_investment_website_base_url()

    if platform == "avarten":
        return f"{base_url}/nieruchomosci/dubaj/oferta/{token}"

    if platform == "cyprus constructions":
        # source_url is "<project URL>#unit-type=..." (sync identity, not a page). The public
        # page is the project page, keyed by the project URL alone; every unit type shares it.
        project_token = _encode_offer_token(source_url.split("#", 1)[0])
        return f"{base_url}/nieruchomosci/cypr/projekt/{project_token}"

    # tripinvest, and the historical fallback for any other source
    return f"{base_url}/nieruchomosci/hiszpania/oferta/{token}"


def _build_description_with_investment_link(offer_row: sqlite3.Row) -> str:
    description = re.sub(r"\s+", " ", _clean_text(offer_row["offer_description"])).strip()
    if not description:
        description = _clean_text(offer_row["offer_title"])

    investment_offer_url = _build_investment_offer_url(offer_row)
    if not investment_offer_url:
        return description

    intro = f"Sprawdz oferte na stronie Investment Nieruchomosci: {investment_offer_url}"
    if not description:
        return intro

    return f"{intro}\n\n{description}"


def _normalize_label(value) -> str:
    text = _clean_text(value).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_decimal(value) -> str:
    text = _clean_text(value).replace(",", ".")
    if not text:
        return ""
    try:
        return str(float(text))
    except ValueError:
        return ""


def _normalize_geo(value) -> str:
    text = _clean_text(value).replace(",", ".")
    if not text:
        return ""
    try:
        return f"{float(text):.7f}"
    except ValueError:
        return ""


def _normalize_int(value) -> str:
    text = _clean_text(value).replace(",", ".")
    if not text:
        return ""
    try:
        return str(int(float(text)))
    except ValueError:
        return ""


def _normalize_currency(value) -> str:
    currency = _clean_text(value).upper()
    if currency in DOMIPORTA_FOREIGN_CURRENCIES:
        return currency
    return "EUR"


def _normalize_tabelaofert_decimal(value, default: str = "0.00") -> str:
    normalized = _normalize_decimal(value)
    if not normalized:
        return default
    return f"{float(normalized):.2f}"


def _normalize_tabelaofert_currency(value) -> str:
    currency = _clean_text(value).upper()
    if currency in TABELAOFERT_FOREIGN_CURRENCIES:
        return currency
    return "EUR"


def _normalize_tabelaofert_trade_type(value) -> str:
    return "wynajem" if _normalize_trade_operation(value) == "2" else "sprzedaz"


def _map_tabelaofert_tab(category_id: str, property_type: str) -> str:
    normalized_type = _normalize_label(property_type)
    if category_id == "192" or any(token in normalized_type for token in ("dom", "willa", "villa")):
        return "domy"
    if category_id == "193" or "dzialka" in normalized_type or "plot" in normalized_type:
        return "dzialki"
    if category_id == "196" or any(token in normalized_type for token in ("lokal", "commercial", "office")):
        return "lokale"
    return "mieszkania"


def _map_tabelaofert_building_type(category_id: str, property_type: str) -> str:
    normalized_type = _normalize_label(property_type)
    if category_id == "192" or any(token in normalized_type for token in ("willa", "villa")):
        return "dom_wolnostojacy"
    if category_id == "196":
        return "biurowiec" if "office" in normalized_type else ""
    return "apartamentowiec" if category_id == "191" else ""


def _map_tabelaofert_state(value: str, features: list[str]) -> str:
    text = _normalize_label(" ".join([value, *features]))
    if "do remontu" in text:
        return "do_remontu"
    if "deweloperski" in text or "stan deweloperski" in text:
        return "deweloperski"
    if "wysoki standard" in text or "stan idealny" in text or "bardzo dobry" in text:
        return "bardzo_dobry"
    if "dobry" in text:
        return "dobry"
    return ""


def _append_param(params: list[dict], name: str, value, value_type: str = "text") -> None:
    clean_value = _clean_text(value)
    if clean_value:
        params.append({"nazwa": name, "typ": value_type, "value": clean_value})


def _strict_market_type(value) -> str | None:
    normalized = _clean_text(value).lower()
    if normalized in {"primary", "pierwotny"}:
        return "primary"
    if normalized in {"secondary", "wtorny", "wtórny"}:
        return "secondary"
    return None


def _normalize_market_type(value) -> str:
    return _strict_market_type(value) or "secondary"



def _ensure_tabelaofert_primary_market(offer_row: sqlite3.Row) -> None:
    market = _strict_market_type(offer_row["market_type_normalized"])
    if market == "primary":
        return
    if market == "secondary":
        raise ValueError("TabelaOfert eksportuje tylko oferty z rynku pierwotnego; rynek wtorny jest zablokowany.")
    raise ValueError(
        "Nieznany rynek oferty (market_type_normalized="
        f"{_clean_text(offer_row['market_type_normalized']) or 'brak'}); "
        "eksport TabelaOfert przerwany."
    )


def _ensure_active_for_publication(offer_row: sqlite3.Row) -> None:
    """Publishing (insert/update) needs an active offer; withdrawals are not checked here."""
    if int(offer_row["is_active"] or 0) != 1:
        raise ValueError(
            f"Oferta zagraniczna {int(offer_row['id'])} jest nieaktywna; publikacja jest zablokowana."
        )


def _ensure_supported_currency(offer_row: sqlite3.Row, allowed: set[str], portal_label: str) -> None:
    currency = _clean_text(offer_row["price_currency"]).upper()
    if currency in allowed:
        return
    shown = currency or "brak"
    raise ValueError(
        f"Waluta ({shown}) nie jest obslugiwana przez eksport {portal_label}. "
        f"Obslugiwane: {', '.join(sorted(allowed))}."
    )


def _foreign_tabelaofert_transport_profile(offer_row: sqlite3.Row) -> str:
    _ensure_tabelaofert_primary_market(offer_row)
    # Selects only the FTP account; bookkeeping always uses portal key "tabelaofert".
    return "tabelaofert_primary"




def _normalize_trade_operation(value) -> str:
    normalized = _clean_text(value).lower()
    if normalized in {"rent", "wynajem", "lease"}:
        return "2"
    return "1"


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

    # Current nine-column gateway and the two supported historical layouts.
    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 _fallback_agent(agent_identifier: str) -> dict:
    safe_identifier = _clean_text(agent_identifier) or "101"
    try:
        row = get_agent_data(int(safe_identifier))
    except Exception:
        row = None

    if not row:
        return {
            "identifier": safe_identifier,
            "name": "",
            "email": "",
            "phone": "",
        }

    extracted = _extract_agent_contact_fields(row)
    return {
        "identifier": safe_identifier,
        "name": extracted["full_name"],
        "email": extracted["email"],
        "phone": extracted["phone"],
    }


def _resolve_agent(offer_row: sqlite3.Row) -> dict:
    fallback = _fallback_agent(offer_row["agent_identifier"])
    return {
        "identifier": _clean_text(offer_row["agent_identifier"]) or fallback["identifier"],
        "name": _clean_text(offer_row["agent_name"]) or fallback["name"],
        "email": _clean_text(offer_row["agent_email"]) or fallback["email"],
        "phone": _clean_text(offer_row["agent_phone"]).replace(" ", "") or fallback["phone"],
    }


def _fetch_offer_row(conn: sqlite3.Connection, foreign_offer_id: int):
    offer_columns = {row[1] for row in conn.execute("PRAGMA table_info(foreign_offers)")}
    development_table = conn.execute(
        """
        SELECT 1
        FROM sqlite_master
        WHERE type = 'table' AND name = 'foreign_developments'
        LIMIT 1
        """
    ).fetchone()
    development_columns = (
        {row[1] for row in conn.execute("PRAGMA table_info(foreign_developments)")}
        if development_table
        else set()
    )
    if "development_id" in offer_columns and {"id", "name"} <= development_columns:
        return conn.execute(
            """
            SELECT fo.*, fd.name AS development_name
            FROM foreign_offers fo
            LEFT JOIN foreign_developments fd ON fd.id = fo.development_id
            WHERE fo.id = ?
            LIMIT 1
            """,
            (int(foreign_offer_id),),
        ).fetchone()

    return conn.execute(
        """
        SELECT *
        FROM foreign_offers
        WHERE id = ?
        LIMIT 1
        """,
        (int(foreign_offer_id),),
    ).fetchone()


def _fetch_images(conn: sqlite3.Connection, foreign_offer_id: int) -> list[sqlite3.Row]:
    return conn.execute(
        """
        SELECT image_url, sort_order, is_primary
        FROM foreign_offer_images
        WHERE foreign_offer_id = ?
        ORDER BY sort_order ASC, id ASC
        """,
        (int(foreign_offer_id),),
    ).fetchall()


def _fetch_warnings(conn: sqlite3.Connection, foreign_offer_id: int) -> list[sqlite3.Row]:
    return conn.execute(
        """
        SELECT warning_code, warning_message, field_name, is_blocking, created_at
        FROM foreign_offer_export_warnings
        WHERE foreign_offer_id = ? AND resolved_at IS NULL
        ORDER BY is_blocking DESC, created_at ASC, id ASC
        """,
        (int(foreign_offer_id),),
    ).fetchall()


def _has_sold_out_warning(conn: sqlite3.Connection, foreign_offer_id: int) -> bool:
    return any(
        row["warning_code"] == "source_sold_out" and int(row["is_blocking"] or 0) == 1
        for row in _fetch_warnings(conn, foreign_offer_id)
    )


def _fetch_features(conn: sqlite3.Connection, foreign_offer_id: int) -> list[str]:
    rows = conn.execute(
        """
        SELECT feature_text
        FROM foreign_offer_features_raw
        WHERE foreign_offer_id = ?
        ORDER BY id ASC
        """,
        (int(foreign_offer_id),),
    ).fetchall()
    return [_clean_text(row["feature_text"]) for row in rows if _clean_text(row["feature_text"])]


def _has_feature(features_text: str, *tokens: str) -> bool:
    return any(_normalize_label(token) in features_text for token in tokens)


def _append_unique(items: list[str], value: str) -> None:
    if value and value not in items:
        items.append(value)


def _map_feature_payload(category_id: str, features: list[str], description: str = "", title: str = "", property_type: str = "") -> dict:
    text = _normalize_label(" ".join([*features, description, title, property_type]))
    additional: list[str] = []
    amenity: list[str] = []
    surroundings: list[str] = []
    parking_space_count = ""
    building_state = ""
    building_type = ""
    kitchen = ""
    standard = ""

    if category_id == "191":
        if _has_feature(text, "winda"):
            _append_unique(additional, "253")
        if _has_feature(text, "garaz podziemny"):
            _append_unique(additional, "11598")
        elif _has_feature(text, "garaz"):
            _append_unique(additional, "255")
        if _has_feature(text, "parking", "miejsce parkingowe", "miejsce postojowe"):
            _append_unique(additional, "256")
            parking_space_count = "1"
        if _has_feature(text, "taras", "tarasu", "tarasy"):
            _append_unique(additional, "260")
        if _has_feature(text, "ogrod", "ogrodek", "ogrod wspolny", "prywatny ogrod"):
            _append_unique(additional, "10571")
        if _has_feature(text, "komorka lokatorska"):
            _append_unique(additional, "11601")
        if _has_feature(text, "klimatyzacja", "wstepna instalacja klimatyzacji"):
            _append_unique(additional, "11646")
        if _has_feature(text, "ogrzewanie podlogowe", "podgrzewana podloga"):
            _append_unique(additional, "276")
        if _has_feature(text, "umeblowane"):
            _append_unique(amenity, "282")
        if _has_feature(text, "kuchnia wyposazona"):
            _append_unique(amenity, "284")
            kitchen = "kuchnia wyposazona"
        elif _has_feature(text, "kuchnia z zabudowa", "zabudowa meblowa"):
            kitchen = "kuchnia z zabudową meblową"

    if category_id == "192":
        if _has_feature(text, "willa", "villa", "wolnostojaca", "wolnostojacy", "dom wolnostojacy"):
            building_type = "326"
        if _has_feature(text, "garaz podziemny"):
            _append_unique(additional, "11599")
        elif _has_feature(text, "garaz"):
            _append_unique(additional, "362")
        if _has_feature(text, "parking", "miejsce parkingowe", "miejsce postojowe"):
            parking_space_count = "1"
        if _has_feature(text, "taras", "tarasu", "tarasy"):
            _append_unique(additional, "366")
        if _has_feature(text, "ogrod", "ogrodek", "prywatny ogrod"):
            _append_unique(additional, "10572")
        if _has_feature(text, "komorka lokatorska"):
            _append_unique(additional, "11602")
        if _has_feature(text, "klimatyzacja", "wstepna instalacja klimatyzacji"):
            _append_unique(additional, "11648")
        if _has_feature(text, "ogrzewanie podlogowe", "podgrzewana podloga"):
            _append_unique(additional, "379")
        if _has_feature(text, "umeblowane"):
            _append_unique(amenity, "10455")
        if _has_feature(text, "kuchnia wyposazona"):
            _append_unique(amenity, "10452")
            kitchen = "kuchnia wyposazona"
        elif _has_feature(text, "kuchnia z zabudowa", "zabudowa meblowa"):
            kitchen = "kuchnia z zabudową meblową"

    if _has_feature(text, "nowe budownictwo"):
        building_state = "nowe budownictwo"
    if _has_feature(text, "stan idealny"):
        building_state = "stan idealny"
    if _has_feature(text, "wysoki standard"):
        standard = "wysoki standard"

    return {
        "AdditionalInformation": additional,
        "Amenity": amenity,
        "Surroundings": surroundings,
        "ParkingSpaceCount": parking_space_count,
        "BuildingType": building_type,
        "BuildingState": building_state,
        "Kitchen": kitchen,
        "Standard": standard,
    }


def list_foreign_offers_for_export(limit: int = 200) -> list[dict]:
    if get_foreign_offers_db_status()["mode"] == "missing":
        return []

    with _open_read_connection() as conn:
        rows = conn.execute(
            """
            SELECT
                fo.id,
                fo.offer_title,
                fo.source_url,
                fo.source_platform,
                fo.source_offer_ref,
                fo.source_country_name,
                fo.source_region_name,
                fo.source_city_name,
                fo.source_location_text,
                fo.price_value,
                fo.price_currency,
                fo.area_total_m2,
                fo.plot_area_m2,
                fo.rooms_count,
                fo.bedrooms_count,
                fo.bathrooms_count,
                fo.property_type_source,
                fo.category_id_domiporta,
                fo.is_export_ready,
                fo.needs_update,
                fo.last_source_sync_at,
                fo.last_exported_at,
                fo.created_at,
                fps.is_published,
                fps.last_error,
                fps.last_uploaded_at
            FROM foreign_offers fo
            LEFT JOIN foreign_offer_portal_sync fps
                ON fps.foreign_offer_id = fo.id
               AND fps.portal_key = 'domiporta'
            WHERE fo.is_active = 1
            ORDER BY fo.id DESC
            LIMIT ?
            """,
            (int(limit),),
        ).fetchall()

        result = []
        for row in rows:
            warnings = _fetch_warnings(conn, int(row["id"]))
            images = _fetch_images(conn, int(row["id"]))
            result.append(
                {
                    "id": int(row["id"]),
                    "offer_title": _clean_text(row["offer_title"]),
                    "source_url": _clean_text(row["source_url"]),
                    "source_platform": _clean_text(row["source_platform"]),
                    "source_offer_ref": _clean_text(row["source_offer_ref"]),
                    "source_country_name": _clean_text(row["source_country_name"]),
                    "source_region_name": _clean_text(row["source_region_name"]),
                    "source_city_name": _clean_text(row["source_city_name"]),
                    "source_location_text": _clean_text(row["source_location_text"]),
                    "price_value": row["price_value"],
                    "price_currency": _clean_text(row["price_currency"]),
                    "area_total_m2": row["area_total_m2"],
                    "plot_area_m2": row["plot_area_m2"],
                    "rooms_count": row["rooms_count"],
                    "bedrooms_count": row["bedrooms_count"],
                    "bathrooms_count": row["bathrooms_count"],
                    "property_type_source": _clean_text(row["property_type_source"]),
                    "category_id_domiporta": _clean_text(row["category_id_domiporta"]),
                    "is_export_ready": int(row["is_export_ready"] or 0),
                    "needs_update": int(row["needs_update"] or 0),
                    "last_source_sync_at": _clean_text(row["last_source_sync_at"]),
                    "last_exported_at": _clean_text(row["last_exported_at"]),
                    "created_at": _clean_text(row["created_at"]),
                    "is_published": int(row["is_published"] or 0),
                    "last_error": _clean_text(row["last_error"]),
                    "last_uploaded_at": _clean_text(row["last_uploaded_at"]),
                    "images_count": len(images),
                    "warnings": [
                        {
                            "warning_code": _clean_text(warning["warning_code"]),
                            "warning_message": _clean_text(warning["warning_message"]),
                            "field_name": _clean_text(warning["field_name"]),
                            "is_blocking": int(warning["is_blocking"] or 0),
                            "created_at": _clean_text(warning["created_at"]),
                        }
                        for warning in warnings
                    ],
                    "images": [_clean_text(image["image_url"]) for image in images if _clean_text(image["image_url"])],
                }
            )

        return result


def _build_payload(offer_row: sqlite3.Row, agent: dict, image_urls: list[str], features: list[str]) -> tuple[str, dict]:
    advert_id = f"foreign_{int(offer_row['id'])}"
    category_id = _clean_text(offer_row["category_id_domiporta"])
    if not category_id:
        raise ValueError("Brak kategorii Domiporta dla tej oferty.")

    source_description = re.sub(r"\s+", " ", _clean_text(offer_row["offer_description"])).strip()
    if not source_description:
        source_description = _clean_text(offer_row["offer_title"])

    description = _build_description_with_investment_link(offer_row)

    area_total = _normalize_decimal(offer_row["area_total_m2"])
    plot_area = _normalize_decimal(offer_row["plot_area_m2"])
    subject_area = plot_area if category_id == "193" and plot_area else area_total or plot_area or "0"
    feature_payload = _map_feature_payload(
        category_id,
        features,
        source_description,
        _clean_text(offer_row["offer_title"]),
        _clean_text(offer_row["property_type_source"]),
    )

    payload = {
        "AdvertId": advert_id,
        "TradeOperationType": _normalize_trade_operation(offer_row["offer_type_normalized"]),
        "MarketType": _normalize_market_type(offer_row["market_type_normalized"]),
        "CategoryId": category_id,
        "Description": description,
        "Price": _normalize_decimal(offer_row["price_value"]) or "0.0",
        "PriceCurrency": _normalize_currency(offer_row["price_currency"]),
        "IsExclusiveOffer": "0",
        "CountryName": _clean_text(offer_row["source_country_name"]) or "Spain",
        "RegionName": _clean_text(offer_row["source_region_name"]),
        "CountyName": _clean_text(offer_row["county_name"]),
        "CommunityName": _clean_text(offer_row["community_name"]),
        "CityName": _clean_text(offer_row["source_city_name"]),
        "StreetName": _clean_text(offer_row["street_name"]),
        "GeoCodeLatitude": _normalize_geo(offer_row["latitude"]),
        "GeoCodeLongitude": _normalize_geo(offer_row["longitude"]),
        "SubjectArea": subject_area,
        "RoomsCount": _normalize_int(offer_row["rooms_count"]),
        "LivingArea": area_total,
        "Floor": _normalize_int(effective_floor(offer_row)),
        "FloorsCount": _normalize_int(offer_row["floors_count"]),
        "ConstructionYear": _normalize_int(offer_row["construction_year"]),
        "PlotArea": plot_area,
        "BuildingType": _clean_text(offer_row["building_type_domiporta"]) or feature_payload["BuildingType"],
        "Sewerage": _clean_text(offer_row["sewerage_domiporta"]),
        "PlotType": _clean_text(offer_row["plot_type_domiporta"]),
        "CommercialUsage": [_clean_text(offer_row["commercial_usage_domiporta"])]
        if _clean_text(offer_row["commercial_usage_domiporta"]) and category_id == "196"
        else [],
        "Utilities": [],
        "ParkingSpaceCount": feature_payload["ParkingSpaceCount"],
        "AgentIdentifier": agent["identifier"],
        "AgentName": agent["name"],
        "AgentEmail": agent["email"],
        "AgentPhone": agent["phone"],
        "BuildingState": _clean_text(offer_row["standard_normalized"]) or feature_payload["BuildingState"],
        "Kitchen": _clean_text(offer_row["kitchen_normalized"]) or feature_payload["Kitchen"],
        "Standard": _clean_text(offer_row["standard_normalized"]) or feature_payload["Standard"],
        "AdditionalInformation": feature_payload["AdditionalInformation"],
        "Surroundings": feature_payload["Surroundings"],
        "Amenity": feature_payload["Amenity"],
        "PictureSourceType": "HttpUrl",
        "PicturePaths": image_urls,
    }
    return advert_id, payload


def _build_tabelaofert_payload(offer_row: sqlite3.Row, agent: dict, features: list[str]) -> tuple[str, dict]:
    offer_id = f"foreign_{int(offer_row['id'])}"
    category_id = _clean_text(offer_row["category_id_domiporta"])
    description = _build_description_with_investment_link(offer_row)
    params: list[dict] = []

    _append_param(params, "dataaktualizacji", datetime.datetime.now().strftime("%Y-%m-%d"))
    _append_param(params, "kraj", _clean_text(offer_row["source_country_name"]) or "Hiszpania")
    _append_param(params, "region", offer_row["source_region_name"])
    _append_param(params, "miasto", offer_row["source_city_name"])
    _append_param(params, "lokalizacja", offer_row["source_location_text"])
    _append_param(params, "lokalizacjawidoczna", "tak", "boolean")
    _append_param(params, "x", _normalize_geo(offer_row["longitude"]), "float")
    _append_param(params, "y", _normalize_geo(offer_row["latitude"]), "float")
    # Omitted when the offer has no development (or the schema predates it).
    _append_param(params, "id_inwestycji", investment_group_id(offer_row))
    _append_param(params, "nazwa_inwestycji", investment_group_name(offer_row))
    _append_param(params, "powierzchnia", _normalize_tabelaofert_decimal(offer_row["area_total_m2"]), "float")
    _append_param(params, "powierzchniadzialki", _normalize_tabelaofert_decimal(offer_row["plot_area_m2"], default=""), "float")
    # 0 (parter) and -1 (przyziemie) are kept; unknown floor is omitted.
    _append_param(params, "pietro", _normalize_int(effective_floor(offer_row)), "integer")
    _append_param(params, "liczbapokoi", _normalize_int(offer_row["rooms_count"]), "integer")
    _append_param(params, "liczbasypialni", _normalize_int(offer_row["bedrooms_count"]), "integer")
    _append_param(params, "liczbalazienek", _normalize_int(offer_row["bathrooms_count"]), "integer")
    _append_param(
        params,
        "typzabudowy",
        _map_tabelaofert_building_type(category_id, _clean_text(offer_row["property_type_source"])),
    )
    _append_param(params, "stan", _map_tabelaofert_state(_clean_text(offer_row["standard_normalized"]), features))
    _append_param(params, "opis", description)
    _append_param(params, "agent_nazwisko", agent["name"])
    _append_param(params, "agent_email", agent["email"])
    _append_param(params, "agent_tel_biuro", agent["phone"])
    _append_param(params, "agent_tel_kom", agent["phone"])

    return offer_id, {
        "id": offer_id,
        "tab": _map_tabelaofert_tab(category_id, _clean_text(offer_row["property_type_source"])),
        "typ": _normalize_tabelaofert_trade_type(offer_row["offer_type_normalized"]),
        "cena": _normalize_tabelaofert_decimal(offer_row["price_value"]),
        "waluta": _normalize_tabelaofert_currency(offer_row["price_currency"]),
        "params": params,
    }


def _package_foreign_offer(advert_id: str, generated_xml: str) -> tuple[str, bytes]:
    date_str = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    zip_filename = f"domiporta_{advert_id}_{date_str}.zip"
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        zipf.writestr("Domiporta.xml", generated_xml.encode("utf-8"))

    return zip_filename, zip_buffer.getvalue()


def _download_image_as_jpeg(image_url: str) -> bytes:
    request = urllib.request.Request(
        image_url,
        headers={"User-Agent": "InvestmentManager/1.0"},
    )
    with urlopen(request, timeout=30) as response:
        raw_bytes = response.read()

    with Image.open(io.BytesIO(raw_bytes)) as image:
        output = io.BytesIO()
        image.convert("RGB").save(output, format="JPEG", quality=92)
        return output.getvalue()


def _download_foreign_images_as_jpegs(image_urls: list[str]) -> list[bytes]:
    image_files: list[bytes] = []
    for image_url in image_urls:
        try:
            image_files.append(_download_image_as_jpeg(image_url))
        except Exception:
            continue
    return image_files


def _package_foreign_offer_tabelaofert(offer_id: str, generated_xml: str, image_files: list[bytes]) -> tuple[str, bytes]:
    date_str = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    zip_filename = f"to_{offer_id}_{date_str}.zip"
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        for index, image_bytes in enumerate(image_files):
            zipf.writestr(f"image_{offer_id}_url_{index}.jpg", image_bytes)

        zipf.writestr("oferty.xml", generated_xml.encode("utf-8"))

    return zip_filename, zip_buffer.getvalue()


# Event types Investment writes (mark_foreign_offer_requires_update, in the same
# transaction as the data change) whenever a foreign offer changes in a way a
# portal should see. Their ids are AUTOINCREMENT, so MAX(id) is a version marker.
_CHANGE_EVENT_TYPES_SQL = "'update_required', 'update_ignored_no_publication'"


def _change_marker(conn: sqlite3.Connection, foreign_offer_id: int) -> int:
    """Version of the offer's change history; read BEFORE the offer data that is exported."""
    row = conn.execute(
        "SELECT COALESCE(MAX(id), 0) FROM foreign_offer_portal_sync_events WHERE foreign_offer_id = ?",
        (int(foreign_offer_id),),
    ).fetchone()
    return int(row[0] or 0)
















def export_foreign_offer_to_domiporta(foreign_offer_id: int, upload: bool = False) -> tuple[str, bytes, dict]:
    if upload:
        raise RuntimeError("Transport is disabled; generate with upload=False")
    db_status = get_foreign_offers_db_status()
    if db_status["mode"] == "missing":
        raise ValueError("Baza foreign_offers.db nie istnieje.")

    with _open_read_connection() as conn:
        change_marker = _change_marker(conn, int(foreign_offer_id))  # before the data it versions
        offer_row = _fetch_offer_row(conn, int(foreign_offer_id))
        if not offer_row:
            raise ValueError(f"Nie znaleziono oferty zagranicznej o ID {foreign_offer_id}.")
        _ensure_active_for_publication(offer_row)
        _ensure_supported_currency(offer_row, DOMIPORTA_FOREIGN_CURRENCIES, "Domiporta")

        warnings = _fetch_warnings(conn, int(foreign_offer_id))
        blocking_warnings = [row for row in warnings if int(row["is_blocking"] or 0) == 1]
        if blocking_warnings:
            summary = ", ".join(_clean_text(row["warning_message"]) for row in blocking_warnings[:3])
            raise ValueError(f"Oferta ma blokujące warningi eksportu: {summary}")

        image_rows = _fetch_images(conn, int(foreign_offer_id))
        image_urls = [_clean_text(row["image_url"]) for row in image_rows if _clean_text(row["image_url"])]
        if not image_urls:
            raise ValueError("Oferta nie ma obrazów do eksportu.")
        features = _fetch_features(conn, int(foreign_offer_id))

        agent = _resolve_agent(offer_row)
        advert_id, payload = _build_payload(offer_row, agent, image_urls, features)
        generated_xml = render_xml_dp(payload, [], payload["Description"], len(image_urls), option="insert")

        try:
            zip_filename, zip_bytes = _package_foreign_offer(advert_id, generated_xml)
            return zip_filename, zip_bytes, {
                "foreign_offer_id": int(foreign_offer_id),
                "advert_id": advert_id,
                "images_count": len(image_urls),
                "category_id": payload["CategoryId"],
                "uploaded": bool(upload),
            }
        except Exception as exc:
            raise


def export_foreign_offer_to_tabelaofert(foreign_offer_id: int, upload: bool = False) -> tuple[str, bytes, dict]:
    if upload:
        raise RuntimeError("Transport is disabled; generate with upload=False")
    db_status = get_foreign_offers_db_status()
    if db_status["mode"] == "missing":
        raise ValueError("Baza foreign_offers.db nie istnieje.")

    with _open_read_connection() as conn:
        change_marker = _change_marker(conn, int(foreign_offer_id))  # before the data it versions
        offer_row = _fetch_offer_row(conn, int(foreign_offer_id))
        if not offer_row:
            raise ValueError(f"Nie znaleziono oferty zagranicznej o ID {foreign_offer_id}.")
        _ensure_active_for_publication(offer_row)
        _ensure_tabelaofert_primary_market(offer_row)
        _ensure_supported_currency(offer_row, TABELAOFERT_FOREIGN_CURRENCIES, "TabelaOfert")
        # Only an actual upload needs an FTP account; an offline package does not.
        transport_profile = _foreign_tabelaofert_transport_profile(offer_row) if upload else None

        warnings = _fetch_warnings(conn, int(foreign_offer_id))
        blocking_warnings = [row for row in warnings if int(row["is_blocking"] or 0) == 1]
        if blocking_warnings:
            summary = ", ".join(_clean_text(row["warning_message"]) for row in blocking_warnings[:3])
            raise ValueError(f"Oferta ma blokujące warningi eksportu: {summary}")

        image_rows = _fetch_images(conn, int(foreign_offer_id))
        image_urls = [_clean_text(row["image_url"]) for row in image_rows if _clean_text(row["image_url"])]
        if not image_urls:
            raise ValueError("Oferta nie ma obrazów do eksportu.")

        features = _fetch_features(conn, int(foreign_offer_id))
        agent = _resolve_agent(offer_row)
        offer_id, payload = _build_tabelaofert_payload(offer_row, agent, features)
        image_files = _download_foreign_images_as_jpegs(image_urls)
        if not image_files:
            raise ValueError("Nie udało się pobrać żadnego zdjęcia do paczki TabelaOfert.")
        generated_xml = render_xml_tabelaofert(payload, "", len(image_files), option="insert")

        try:
            zip_filename, zip_bytes = _package_foreign_offer_tabelaofert(
                offer_id,
                generated_xml,
                image_files,
            )
            return zip_filename, zip_bytes, {
                "foreign_offer_id": int(foreign_offer_id),
                "advert_id": offer_id,
                "images_count": len(image_files),
                "tab": payload["tab"],
                "type": payload["typ"],
                "uploaded": bool(upload),
            }
        except Exception as exc:
            raise


# ---------------------------------------------------------------------------
# Cyprus: one Cyprus Constructions project (foreign development) with all its
# active offers in one TabelaOfert package. Building the package never uploads;
# upload_cyprus_development_tabelaofert_package sends exactly the bytes built.
# ---------------------------------------------------------------------------


def _table_columns(conn: sqlite3.Connection, table: str) -> set[str]:
    return {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}


def _has_cyprus_development_schema(conn: sqlite3.Connection) -> bool:
    return {"id", "name", "source_platform"} <= _table_columns(conn, "foreign_developments") and (
        "development_id" in _table_columns(conn, "foreign_offers")
    )


def list_cyprus_developments_for_export() -> list[dict]:
    """Cyprus Constructions projects with their active offer counts (empty on an older schema)."""
    if get_foreign_offers_db_status()["mode"] == "missing":
        return []

    with _open_read_connection() as conn:
        if not _has_cyprus_development_schema(conn):
            return []
        rows = conn.execute(
            """
            SELECT fd.id, fd.name, COUNT(fo.id) AS active_offers_count
            FROM foreign_developments fd
            LEFT JOIN foreign_offers fo
                ON fo.development_id = fd.id
               AND fo.is_active = 1
            WHERE fd.source_platform = ?
            GROUP BY fd.id, fd.name
            ORDER BY fd.name COLLATE NOCASE ASC, fd.id ASC
            """,
            (CYPRUS_SOURCE_PLATFORM,),
        ).fetchall()
    return [
        {"id": int(row["id"]), "name": _clean_text(row["name"]), "active_offers_count": int(row["active_offers_count"])}
        for row in rows
    ]


def _download_foreign_images_strict(image_urls: list[str]) -> tuple[list[bytes], list[str]]:
    """Every image, or one reason per failed image: a partial gallery is never accepted."""
    image_files: list[bytes] = []
    errors: list[str] = []
    for index, image_url in enumerate(image_urls, start=1):
        try:
            image_files.append(_download_image_as_jpeg(image_url))
        except Exception as exc:
            errors.append(f"Nie udało się pobrać zdjęcia {index}/{len(image_urls)} ({image_url}): {exc}")
    return image_files, errors


def _cyprus_offer_problems(conn: sqlite3.Connection, offer_row: sqlite3.Row, development: sqlite3.Row) -> list[str]:
    """The single TabelaOfert export guards, collected instead of raised, plus project consistency."""
    problems: list[str] = []
    source_platform = _clean_text(offer_row["source_platform"])
    if source_platform != CYPRUS_SOURCE_PLATFORM:
        problems.append(f"Oferta nie pochodzi z Cyprus Constructions (source_platform={source_platform or 'brak'}).")
    try:
        _ensure_tabelaofert_primary_market(offer_row)
    except ValueError as exc:
        problems.append(str(exc))
    try:
        _ensure_supported_currency(offer_row, TABELAOFERT_FOREIGN_CURRENCIES, "TabelaOfert")
    except ValueError as exc:
        problems.append(str(exc))

    blocking_warnings = [row for row in _fetch_warnings(conn, int(offer_row["id"])) if int(row["is_blocking"] or 0) == 1]
    if blocking_warnings:
        summary = ", ".join(_clean_text(row["warning_message"]) for row in blocking_warnings)
        problems.append(f"Oferta ma blokujące warningi eksportu: {summary}")

    if investment_group_id(offer_row) != f"foreign_dev_{int(development['id'])}":
        problems.append("Oferta nie jest przypisana do wybranego projektu.")
    if investment_group_name(offer_row) != _clean_text(development["name"]):
        problems.append("Nazwa inwestycji oferty różni się od nazwy projektu.")

    # Fields TabelaOfert requires for a primary-market unit; the single export does not enforce them.
    if not _positive_decimal(offer_row["price_value"]):
        problems.append("Brak ceny (musi być większa od zera).")
    if not _positive_decimal(offer_row["area_total_m2"]):
        problems.append("Brak powierzchni (musi być większa od zera).")
    rooms = _normalize_int(offer_row["rooms_count"])
    if not rooms or int(rooms) <= 0:
        problems.append("Brak liczby pokoi (musi być większa od zera).")
    if _normalize_int(effective_floor(offer_row)) == "":
        problems.append("Brak piętra (ustaw piętro w CRM; 0 = parter jest poprawne).")
    return problems


def _positive_decimal(value) -> bool:
    normalized = _normalize_decimal(value)
    return bool(normalized) and float(normalized) > 0


def _package_foreign_development_tabelaofert(
    development_id: int, generated_xml: str, images_by_offer: list[tuple[str, list[bytes]]]
) -> tuple[str, bytes]:
    date_str = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    zip_filename = f"to_foreign_dev_{int(development_id)}_{date_str}.zip"
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        for offer_id, image_files in images_by_offer:
            for index, image_bytes in enumerate(image_files):
                zipf.writestr(f"image_{offer_id}_url_{index}.jpg", image_bytes)

        zipf.writestr("oferty.xml", generated_xml.encode("utf-8"))

    return zip_filename, zip_buffer.getvalue()


def build_cyprus_development_tabelaofert_package(development_id: int) -> dict:
    """Builds one ZIP of active, non-Sold-Out offers, in their existing order.

    Never uploads. ``ready`` is True only when a package was built (``zip_filename``,
    ``zip_bytes``, ``zip_sha256``); otherwise ``problems`` and ``offers[*].problems``
    say why nothing was built. Sold Out exclusions are reported separately;
    they never confirm a withdrawal or change portal publication state.
    """
    if get_foreign_offers_db_status()["mode"] == "missing":
        raise ValueError("Baza foreign_offers.db nie istnieje.")

    with _open_read_connection() as conn:
        if not _has_cyprus_development_schema(conn):
            raise ValueError("Baza foreign_offers.db nie obsługuje projektów (brak foreign_developments.source_platform).")
        development = conn.execute(
            "SELECT id, name, source_platform FROM foreign_developments WHERE id = ? LIMIT 1",
            (int(development_id),),
        ).fetchone()
        if not development:
            raise ValueError(f"Nie znaleziono projektu o ID {development_id}.")
        if _clean_text(development["source_platform"]) != CYPRUS_SOURCE_PLATFORM:
            raise ValueError(f"Projekt {development_id} nie jest projektem Cyprus Constructions.")

        # Change markers first: they version the offer data read just below.
        change_markers = {
            int(row[0]): int(row[1] or 0)
            for row in conn.execute(
                """
                SELECT fo.id, COALESCE(MAX(ev.id), 0)
                FROM foreign_offers fo
                LEFT JOIN foreign_offer_portal_sync_events ev ON ev.foreign_offer_id = fo.id
                WHERE fo.development_id = ?
                GROUP BY fo.id
                """,
                (int(development_id),),
            ).fetchall()
        }
        offer_rows = conn.execute(
            """
            SELECT fo.*, fd.name AS development_name
            FROM foreign_offers fo
            LEFT JOIN foreign_developments fd ON fd.id = fo.development_id
            WHERE fo.development_id = ? AND fo.is_active = 1
            ORDER BY fo.id ASC
            """,
            (int(development_id),),
        ).fetchall()
        inactive_offer_ids = [
            int(row["id"])
            for row in conn.execute(
                "SELECT id FROM foreign_offers WHERE development_id = ? AND is_active <> 1 ORDER BY id",
                (int(development_id),),
            ).fetchall()
        ]

        sold_out_offer_ids = [int(row["id"]) for row in offer_rows if _has_sold_out_warning(conn, int(row["id"]))]
        offer_rows = [row for row in offer_rows if int(row["id"]) not in sold_out_offer_ids]

        report = {
            "development_id": int(development["id"]),
            "development_name": _clean_text(development["name"]),
            "investment_id": f"foreign_dev_{int(development['id'])}",
            "inactive_offer_ids": inactive_offer_ids,
            "sold_out_offer_ids": sold_out_offer_ids,
            "offers": [],
            "problems": [],
            "ready": False,
            "zip_filename": None,
            "zip_bytes": None,
            "zip_sha256": None,
            "images_count": 0,
        }
        if not report["development_name"]:
            report["problems"].append("Projekt nie ma nazwy (nazwa_inwestycji byłaby pusta).")
        if not offer_rows:
            report["problems"].append(
                "Projekt nie ma aktywnych ofert dostępnych do publikacji (Sold Out pominięte)."
                if sold_out_offer_ids else "Projekt nie ma aktywnych ofert."
            )

        rendered: list[tuple[dict, int]] = []
        images_by_offer: list[tuple[str, list[bytes]]] = []
        for offer_row in offer_rows:
            foreign_offer_id = int(offer_row["id"])
            problems = _cyprus_offer_problems(conn, offer_row, development)
            image_urls = [
                _clean_text(row["image_url"]) for row in _fetch_images(conn, foreign_offer_id) if _clean_text(row["image_url"])
            ]
            image_files: list[bytes] = []
            if not image_urls:
                problems.append("Oferta nie ma obrazów do eksportu.")
            elif not problems:
                image_files, image_errors = _download_foreign_images_strict(image_urls)
                problems.extend(image_errors)

            offer_id, payload = _build_tabelaofert_payload(
                offer_row, _resolve_agent(offer_row), _fetch_features(conn, foreign_offer_id)
            )
            report["offers"].append(
                {
                    "foreign_offer_id": foreign_offer_id,
                    "change_marker": change_markers.get(foreign_offer_id, 0),
                    "advert_id": offer_id,
                    "offer_title": _clean_text(offer_row["offer_title"]),
                    "tab": payload["tab"],
                    "type": payload["typ"],
                    "image_urls_count": len(image_urls),
                    "images_count": 0 if problems else len(image_files),
                    "problems": problems,
                }
            )
            if not problems:
                rendered.append((payload, len(image_files)))
                images_by_offer.append((offer_id, image_files))

        if any(offer["problems"] for offer in report["offers"]):
            report["problems"].append("Co najmniej jedna aktywna oferta nie przeszła walidacji; paczka nie została utworzona.")
        if report["problems"]:
            return report

        generated_xml = render_xml_tabelaofert_many(rendered)
        zip_filename, zip_bytes = _package_foreign_development_tabelaofert(int(development_id), generated_xml, images_by_offer)
        report.update(
            {
                "ready": True,
                "zip_filename": zip_filename,
                "zip_bytes": zip_bytes,
                "zip_sha256": hashlib.sha256(zip_bytes).hexdigest(),
                "images_count": sum(len(files) for _offer_id, files in images_by_offer),
            }
        )
        return report




# ---------------------------------------------------------------------------
# Withdrawal of inactive foreign offers from portals (INV-LC-4). An offer
# withdrawn in the CRM (is_active = 0) that a portal still lists
# (is_published = 1) is "to withdraw". The user builds a delete package, reviews
# it and sends it; only a successful upload marks that one portal unpublished.
# ---------------------------------------------------------------------------

# Portal -> FTP account of foreign offers (TabelaOfert foreign offers are on the primary account).
FOREIGN_WITHDRAWAL_TRANSPORT = {"domiporta": "domiporta", "tabelaofert": "tabelaofert_primary"}


def list_foreign_offers_to_withdraw() -> list[dict]:
    """Inactive or confirmed Sold Out offers still published on a portal (no limit)."""
    if get_foreign_offers_db_status()["mode"] == "missing":
        return []

    with _open_read_connection() as conn:
        rows = conn.execute(
            """
            SELECT fo.id, fo.offer_title, fo.source_platform, fo.source_url,
                   fps.portal_key, fps.last_filename, fps.last_uploaded_at, fps.last_error
            FROM foreign_offers fo
            JOIN foreign_offer_portal_sync fps ON fps.foreign_offer_id = fo.id
            WHERE fps.is_published = 1 AND (
                fo.is_active = 0 OR EXISTS (
                    SELECT 1 FROM foreign_offer_export_warnings w
                    WHERE w.foreign_offer_id = fo.id AND w.warning_code = 'source_sold_out'
                      AND w.is_blocking = 1 AND w.resolved_at IS NULL
                )
            )
            ORDER BY fo.id ASC, fps.portal_key ASC
            """
        ).fetchall()

    offers: dict[int, dict] = {}
    for row in rows:
        offer = offers.setdefault(
            int(row["id"]),
            {
                "id": int(row["id"]),
                "advert_id": f"foreign_{int(row['id'])}",
                "offer_title": _clean_text(row["offer_title"]),
                "source_platform": _clean_text(row["source_platform"]),
                "source_url": _clean_text(row["source_url"]),
                "portals": [],
            },
        )
        offer["portals"].append(
            {
                "portal_key": _clean_text(row["portal_key"]),
                "last_filename": _clean_text(row["last_filename"]),
                "last_uploaded_at": _clean_text(row["last_uploaded_at"]),
                "last_error": _clean_text(row["last_error"]),
            }
        )
    return list(offers.values())


def _withdrawal_state_problem(conn: sqlite3.Connection, foreign_offer_id: int, portal_key: str) -> str | None:
    """Why this offer cannot be withdrawn from this portal now, or None."""
    offer = conn.execute("SELECT is_active FROM foreign_offers WHERE id = ?", (int(foreign_offer_id),)).fetchone()
    if offer is None:
        return f"Oferta zagraniczna {foreign_offer_id} nie istnieje."
    if int(offer["is_active"] or 0) != 0 and not _has_sold_out_warning(conn, foreign_offer_id):
        return f"Oferta foreign_{foreign_offer_id} jest aktywna; nie zostanie wycofana."
    published = conn.execute(
        "SELECT is_published FROM foreign_offer_portal_sync WHERE foreign_offer_id = ? AND portal_key = ?",
        (int(foreign_offer_id), portal_key),
    ).fetchone()
    if published is None or int(published["is_published"] or 0) != 1:
        return f"Oferta foreign_{foreign_offer_id} nie jest opublikowana na portalu {portal_key}."
    return None


def build_foreign_withdrawal_package(foreign_offer_id: int, portal_key: str) -> dict:
    """Builds (never sends) the delete package of one offer for one portal, for review."""
    if portal_key not in FOREIGN_WITHDRAWAL_TRANSPORT:
        raise ValueError(f"Nieobsługiwany portal: {portal_key}.")
    if get_foreign_offers_db_status()["mode"] == "missing":
        raise ValueError("Baza foreign_offers.db nie istnieje.")

    with _open_read_connection() as conn:
        problem = _withdrawal_state_problem(conn, foreign_offer_id, portal_key)
        if problem:
            raise ValueError(problem)
        offer_row = _fetch_offer_row(conn, int(foreign_offer_id))

    advert_id = f"foreign_{int(foreign_offer_id)}"
    if portal_key == "domiporta":
        generated_xml = render_xml_dp({"AdvertId": advert_id}, [], "", 0, option="delete")
        zip_filename, zip_bytes = _package_foreign_offer(advert_id, generated_xml)
    else:
        category_id = _clean_text(offer_row["category_id_domiporta"])
        payload = {
            "id": advert_id,
            # Same <dzial> mapping as the publication of this offer.
            "tab": _map_tabelaofert_tab(category_id, _clean_text(offer_row["property_type_source"])),
            "typ": _normalize_tabelaofert_trade_type(offer_row["offer_type_normalized"]),
        }
        generated_xml = render_xml_tabelaofert(payload, "", 0, option="delete")
        zip_filename, zip_bytes = _package_foreign_offer_tabelaofert(advert_id, generated_xml, [])

    return {
        "ready": True,
        "action": "delete",
        "foreign_offer_id": int(foreign_offer_id),
        "advert_id": advert_id,
        "portal_key": portal_key,
        "offer_title": _clean_text(offer_row["offer_title"]),
        "xml": generated_xml,
        "zip_filename": zip_filename,
        "zip_bytes": zip_bytes,
        "zip_sha256": hashlib.sha256(zip_bytes).hexdigest(),
    }






def export_many_foreign_offers_to_domiporta(foreign_offer_ids: list[int], upload: bool = False) -> tuple[dict, dict]:
    if upload:
        raise RuntimeError("Transport is disabled; generate with upload=False")
    results = {}
    errors = {}
    for foreign_offer_id in foreign_offer_ids:
        try:
            zip_filename, zip_bytes, summary = export_foreign_offer_to_domiporta(int(foreign_offer_id), upload=upload)
            results[int(foreign_offer_id)] = (zip_filename, zip_bytes, summary)
        except Exception as exc:
            errors[int(foreign_offer_id)] = str(exc)
    return results, errors


def export_many_foreign_offers_to_tabelaofert(foreign_offer_ids: list[int], upload: bool = False) -> tuple[dict, dict]:
    if upload:
        raise RuntimeError("Transport is disabled; generate with upload=False")
    results = {}
    errors = {}
    for foreign_offer_id in foreign_offer_ids:
        try:
            zip_filename, zip_bytes, summary = export_foreign_offer_to_tabelaofert(int(foreign_offer_id), upload=upload)
            results[int(foreign_offer_id)] = (zip_filename, zip_bytes, summary)
        except Exception as exc:
            errors[int(foreign_offer_id)] = str(exc)
    return results, errors
