from InvestmentManager.integrator.input_consistency import guarded_route, serialized_write, write_inputs, write_failed
from flask import jsonify, session, request, current_app, make_response, send_from_directory
from InvestmentManager import investmentmanager_bp
from InvestmentManager import offer_cards, offers_store
from InvestmentManager.middleware.access import offer_access_denied
from InvestmentManager.form_config import (
    flat_apartment_field_options,
    house_field_options,
    local_field_options,
    object_field_options,
    plot_field_options,
)
from InvestmentManager.integrator.portals.otodom.dictionaries import fetch_otodom_dictionaries
from InvestmentManager.integrator.portal_sync_state import (
    mark_offer_requires_update,
    ensure_offer_sync_defaults,
)
from modules.classes import DatabaseConnectionManager
from modules.connector import backup_idb_database
from modules.core import offer_media, storage_paths
from modules.core.error_responses import internal_error_payload
from modules.core.html_safety import sanitize_description_html
from modules.core.file_safety import (
    UnsafeFilename,
    safe_child_path,
    validate_document_filename,
    validate_offer_image_filename,
)
from InvestmentWebsite.services.catalog import invalidate_offer_caches
from functools import wraps
import os
from PIL import Image, ImageDraw, ImageFont
import shutil
from datetime import datetime
import unicodedata
from urllib.parse import unquote
import markdown

_LOCATION_TRANSLITERATION = str.maketrans({
    "ą": "a",
    "ć": "c",
    "ę": "e",
    "ł": "l",
    "ń": "n",
    "ó": "o",
    "ś": "s",
    "ź": "z",
    "ż": "z",
    "Ą": "a",
    "Ć": "c",
    "Ę": "e",
    "Ł": "l",
    "Ń": "n",
    "Ó": "o",
    "Ś": "s",
    "Ź": "z",
    "Ż": "z",
})


def _offer_access_denied(offer_id):
    """None when the session may access this domestic offer, else a JSON error response.

    Master: every offer (no lookup, so master behaviour is unchanged). Anyone
    else -- agent, and the legacy 'admin' value too, exactly as /offers/all
    scopes the list -- only offers whose EstateData.ID_agenta is their user_id.
    """
    return offer_access_denied(offer_id)


def offer_access_required(view):
    """Backend ownership check for every route taking a domestic <offer_id>."""
    @wraps(view)
    def wrapper(*args, **kwargs):
        denied = _offer_access_denied(kwargs['offer_id'])
        if denied is not None:
            return denied
        return view(*args, **kwargs)
    wrapper.offer_access_checked = True
    return wrapper


def trigger_idb_backup():
    try:
        backup_idb_database()
    except Exception as exc:
        current_app.logger.warning("Nie udalo sie utworzyc backupu IDB.db: %s", exc)


@investmentmanager_bp.route('/offers/<int:offer_id>/export-package', methods=['POST'])
@offer_access_required
def prepare_domestic_export_package(offer_id):
    """Prepare only: no transport, publication flags or sync history writes."""
    if session.get('access_level') != 'master':
        return jsonify({'outcome': 'refused', 'error': 'Brak uprawnień.'}), 403
    body = request.get_json(silent=True)
    if isinstance(body, dict) and set(body) == {'action'}:
        if not isinstance(body['action'], str) or body['action'] not in {'add', 'delete'}:
            return jsonify({'error': 'Nieprawidłowa operacja zestawu.'}), 400
        from InvestmentManager.integrator.domestic_sets import prepare_set
        from InvestmentManager.integrator.domestic_package_catalog import CatalogError
        from InvestmentManager.integrator.domestic_packages import COMPANY_KEYS, PreparationError
        settings = {key: current_app.config.get(key, os.environ.get(key)) for key in COMPANY_KEYS}
        try:
            result = prepare_set(offer_id, body['action'], settings=settings)
            return jsonify(result), 201 if result['replaced'] else 200
        except (PreparationError, CatalogError) as exc:
            return jsonify({'outcome': getattr(exc, 'outcome', 'refused'), 'error': str(exc)}), exc.status
        except Exception:
            # Lock/storage failures before portal generation must also be JSON
            # and must not expose private paths or suggest a successful swap.
            return jsonify({'outcome': 'not_replaced', 'replaced': False,
                            'error': 'Nie można bezpiecznie przygotować zestawu. Sprawdź magazyn i ponów operację.'}), 503
    if not isinstance(body, dict) or set(body) != {'portal', 'action'}:
        return jsonify({'outcome': 'refused', 'error': 'Wymagane są portal i akcja.'}), 400
    from InvestmentManager.integrator.domestic_packages import (
        COMPANY_KEYS, PreparationError, prepare_package,
    )
    if not isinstance(body['portal'], str) or not isinstance(body['action'], str):
        return jsonify({'outcome': 'refused', 'error': 'Nieprawidłowy portal lub akcja.'}), 400
    settings = {key: current_app.config.get(key, os.environ.get(key)) for key in COMPANY_KEYS}
    try:
        result = prepare_package(offer_id, body['portal'], body['action'], settings=settings)
        return jsonify(result), 201
    except PreparationError as exc:
        return jsonify({'outcome': exc.outcome, 'error': str(exc),
                        'portal': body['portal'], 'action': body['action']}), exc.status


def mark_offer_sync_dirty(offer_id, reason, changed_fields=None):
    from InvestmentManager.integrator.input_consistency import _held
    if _held.get() is not None:
        # serialized_write compares the actual before/after portal projections.
        # Keep explicit/manual portal status operations independent.
        return
    try:
        affected = mark_offer_requires_update(
            offer_id=offer_id,
            reason=reason,
            changed_fields=changed_fields or [],
        )
        if affected:
            current_app.logger.info(
                "Oferta %s oznaczona jako wymagajaca aktualizacji na %s portalach (%s).",
                offer_id,
                affected,
                reason,
            )
    except Exception as exc:
        current_app.logger.warning(
            "Nie udalo sie oznaczyc potrzeby aktualizacji oferty %s: %s",
            offer_id,
            exc,
        )
        raise


def _normalize_location_label(value):
    text = "" if value is None else str(value).strip().lower()
    text = text.translate(_LOCATION_TRANSLITERATION)
    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 _decode_region_param(value):
    text = "" if value is None else str(value).strip()
    if not text:
        return ""
    # Defensive decode in case upstream passes already URL-encoded value.
    for _ in range(2):
        decoded = unquote(text)
        if decoded == text:
            break
        text = decoded
    return text


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

    dictionaries = fetch_otodom_dictionaries()
    common = dictionaries.get("Common", {})

    if column_name == "Wojewodztwo":
        provinces = common.get("Province", {})
        if not isinstance(provinces, dict):
            return []
        return sorted({str(value).strip() for value in provinces.values() if str(value).strip()})

    districts = common.get("District", {})
    if not isinstance(districts, dict):
        return []

    district_names = []
    if wojewodztwo:
        province_code_by_label = {}
        provinces = common.get("Province", {})
        if isinstance(provinces, dict):
            for province_code, province_name in provinces.items():
                normalized = _normalize_location_label(province_name)
                if normalized:
                    province_code_by_label[normalized] = str(province_code)

        target_code = province_code_by_label.get(_normalize_location_label(wojewodztwo))
        if not target_code:
            return []

        district_province_map = common.get("District:Province", {})
        if not isinstance(district_province_map, dict):
            return []

        for district_code, district_name in districts.items():
            province_for_district = district_province_map.get(str(district_code))
            if str(province_for_district) == target_code:
                district_names.append(str(district_name).strip())
    else:
        district_names = [str(value).strip() for value in districts.values()]

    return sorted({name for name in district_names if name})


def _get_location_values_from_db(column_name, wojewodztwo=None):
    try:
        return offers_store.get_location_values(
            column_name,
            wojewodztwo=wojewodztwo,
            normalize_label=_normalize_location_label,
        )
    except Exception as exc:
        current_app.logger.warning("Nie udalo sie pobrac listy %s: %s", column_name, exc)
        return []


def _get_location_values(column_name, wojewodztwo=None):
    if column_name == "Powiat" and wojewodztwo:
        db_values = _get_location_values_from_db(column_name, wojewodztwo=wojewodztwo)
        if db_values:
            return db_values

    try:
        values = _get_location_values_from_otodom(column_name, wojewodztwo=wojewodztwo)
        if values:
            return values
        current_app.logger.warning(
            "Otodom dictionary returned empty values for %s (wojewodztwo=%s). Fallback to DB.",
            column_name,
            wojewodztwo,
        )
    except Exception as exc:
        current_app.logger.warning(
            "Nie udalo sie pobrac listy %s z Otodom (%s). Fallback do DB.",
            column_name,
            exc,
        )
    return _get_location_values_from_db(column_name, wojewodztwo=wojewodztwo)


def _get_otodom_values(section_name, key_name):
    try:
        dictionaries = fetch_otodom_dictionaries()
        section = dictionaries.get(section_name, {})
        raw_values = section.get(key_name)
        if isinstance(raw_values, list):
            return [str(value).strip() for value in raw_values if str(value).strip()]
        if isinstance(raw_values, dict):
            return [str(value).strip() for value in raw_values.values() if str(value).strip()]
    except Exception as exc:
        current_app.logger.warning(
            "Nie udalo sie pobrac slownika Otodom %s.%s: %s",
            section_name,
            key_name,
            exc,
        )
    return []

def _normalize_property_type(property_type):
    text = (property_type or "").strip()
    if not text:
        return text

    # Naprawa sporadycznego mojibake z URL.
    try:
        repaired = text.encode("latin-1").decode("utf-8")
        if repaired:
            text = repaired
    except Exception:
        pass

    return text


def _property_type_token(value):
    normalized = _normalize_location_label(value)
    token = "".join(ch for ch in normalized if ch.isalpha())
    if token.startswith("dzia") and token.endswith("ka"):
        return "dzialka"
    return token


def _resolve_property_type_key(raw_value, available_keys):
    normalized_raw = _normalize_property_type(raw_value)
    token = _property_type_token(normalized_raw)
    if not token:
        return normalized_raw

    for key in available_keys:
        if _property_type_token(key) == token:
            return key

    return normalized_raw

def _get_otodom_field_options(property_type):
    per_type_map = {
        "Mieszkanie": {
            "Typ_oferty": ("Common", "OfferType"),
            "Typ_rynku": ("Common", "MarketType"),
            "Rodzaj_budynku": ("FlatDetails", "BuildingType"),
            "Stan_nieruchomosci": ("FlatDetails", "ConstructionStatus"),
            "Typ_okien": ("FlatDetails", "WindowsType"),
            "Ogrzewanie": ("FlatDetails", "Heating"),
        },
        "Apartament": {
            "Typ_oferty": ("Common", "OfferType"),
            "Typ_rynku": ("Common", "MarketType"),
            "Rodzaj_budynku": ("FlatDetails", "BuildingType"),
            "Stan_nieruchomosci": ("FlatDetails", "ConstructionStatus"),
            "Typ_okien": ("FlatDetails", "WindowsType"),
            "Ogrzewanie": ("FlatDetails", "Heating"),
        },
        "Dom": {
            "Typ_oferty": ("Common", "OfferType"),
            "Typ_rynku": ("Common", "MarketType"),
            "Typ_domu": ("HouseDetails", "Type"),
            "Typ_dachu": ("HouseDetails", "Roofing"),
            "Rodzaj_budynku": ("HouseDetails", "BuildingType"),
            "Stan_budynku": ("HouseDetails", "ConstructionStatus"),
            "Typ_okien": ("HouseDetails", "WindowsType"),
            "Ogrzewanie": ("HouseDetails", "HeatingMask"),
        },
        "Działka": {
            "Typ_oferty": ("Common", "OfferType"),
            "Typ_rynku": ("Common", "MarketType"),
            "Przeznaczenie_dzialki": ("TerrainDetails", "Type"),
        },
        "Lokal": {
            "Typ_oferty": ("Common", "OfferType"),
            "Typ_rynku": ("Common", "MarketType"),
            "Rodzaj_budynku": ("CommercialPropertyDetails", "BuildingType"),
            "Stan_nieruchomosci": ("CommercialPropertyDetails", "ConstructionStatus"),
            "Przeznaczenie_nieruchomosci": ("CommercialPropertyDetails", "PropertyUseMask"),
        },
        "Obiekt": {
            "Typ_oferty": ("Common", "OfferType"),
            "Typ_rynku": ("Common", "MarketType"),
            "Rodzaj_budynku": ("CommercialPropertyDetails", "BuildingType"),
            "Stan_budynku": ("CommercialPropertyDetails", "ConstructionStatus"),
            "Przeznaczenie_nieruchomosci": ("CommercialPropertyDetails", "PropertyUseMask"),
        },
    }
    type_key = _resolve_property_type_key(property_type, per_type_map.keys())

    resolved = {}
    for field_name, (section_name, key_name) in per_type_map.get(type_key, {}).items():
        values = _get_otodom_values(section_name, key_name)
        if values:
            resolved[field_name] = values
    return resolved


def _build_combined_field_options(property_type):
    options_dict = {
        'Mieszkanie': flat_apartment_field_options,
        'Apartament': flat_apartment_field_options,
        'Dom': house_field_options,
        'Działka': plot_field_options,
        'Lokal': local_field_options,
        'Obiekt': object_field_options,
    }
    property_type = _resolve_property_type_key(property_type, options_dict.keys())

    global_options = {
        'Wojewodztwo': _get_location_values('Wojewodztwo'),
        'Powiat': _get_location_values('Powiat'),
    }

    combined = options_dict.get(property_type, {}).copy()
    combined.update(global_options)
    combined.update(_get_otodom_field_options(property_type))
    return combined


def _fetch_portal_sync_map(conn, offer_ids):
    """Compatibility wrapper; the read implementation belongs to offers_store."""
    return offers_store.fetch_portal_sync_map(conn, offer_ids)


def _read_offer_description_text(offer_id):
    """Compatibility wrapper for the shared offer-media read contract."""
    return offer_media.read_description_text(offer_id)


def _resolve_agent_avatar_url(agent_id):
    """Compatibility wrapper for existing card and storage consumers."""
    return offer_cards.resolve_agent_avatar_url(
        agent_id, request.url_root.rstrip("/")
    )


@investmentmanager_bp.route('/offers/all')
def get_all_offers():
    access_level = session.get('access_level')
    user_id = session.get('user_id')

    try:
        is_master = access_level == 'master'
        return jsonify(offers_store.list_offers(is_master, user_id))

    except Exception as e:
        print(f"Blad pobierania ofert: {e}")
        return jsonify({'error': 'Wystapil blad podczas pobierania danych.'}), 500

@investmentmanager_bp.route('/offers/toggle/<int:offer_id>', methods=['POST'])
@offer_access_required
@guarded_route
def toggle_offer_status(offer_id):
    try:
        trigger_idb_backup()
        with DatabaseConnectionManager() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT Status_oferty FROM estatedata WHERE ID = ?", (offer_id,))
            row = cursor.fetchone()

            if not row:
                return jsonify({'error': 'Oferta nie istnieje'}), 404

            current_status = (row[0] or '').lower()

            if current_status == 'sprzedane':
                return jsonify({'error': 'Nie można zmienić statusu oferty sprzedanej.'}), 400

            new_status = 'nieaktywna' if current_status == 'aktywna' else 'aktywna'

            write_inputs(offer_ids=[offer_id])
            cursor.execute("UPDATE estatedata SET Status_oferty = ? WHERE ID = ?", (new_status, offer_id))
            conn.commit()

            mark_offer_sync_dirty(offer_id, reason='offer_status_toggled', changed_fields=['Status_oferty'])
            invalidate_offer_caches()
            return jsonify({'success': True, 'new_status': new_status})

    except Exception as e:
        print(f"Błąd przy zmianie statusu: {e}")
        return jsonify({'error': 'Wystąpił błąd podczas aktualizacji'}), 500

def get_field_options_backend(field, property_type):
    return _build_combined_field_options(property_type).get(field)

@investmentmanager_bp.route('/offers/options/<property_type>', methods=['GET'])
def get_field_options(property_type):
    try:
        return jsonify(_build_combined_field_options(property_type))
    except Exception as e:
        print(f"Błąd pobierania opcji: {e}")
        return jsonify({'error': 'Nie udało się pobrać opcji'}), 500

@investmentmanager_bp.route('/offers/districts', defaults={'region_name': ''}, methods=['GET'])
@investmentmanager_bp.route('/offers/districts/<path:region_name>', methods=['GET'])
def get_districts_by_region(region_name):
    try:
        selected_region = request.args.get('region') or region_name
        selected_region = _decode_region_param(selected_region)
        if not selected_region:
            return jsonify([])
        district_names = _get_location_values('Powiat', wojewodztwo=selected_region)
        return jsonify(district_names)
    except Exception as e:
        # A lookup failure is NOT "no districts": answer 503 (all form scripts already treat !res.ok as "could not load"), log the cause.
        payload = internal_error_payload("offers.districts", e, "Nie można odczytać listy powiatów.", code="location_lookup_failed")
        return jsonify(payload), 503

@investmentmanager_bp.route('/offers/add', methods=['POST'])
@guarded_route
def add_offer():
    try:
        trigger_idb_backup()
        form = request.form
        files = request.files.getlist('images')

        # 🟡 Lista wszystkich kolumn z estatedata i localization (oprócz ID)
        estatedata_fields = [
            'Typ_nieruchomosci', 'Typ_oferty', 'Typ_rynku', 'Kraj', 'Miejscowosc',
            'Lokalizacja', 'Cena', 'Data_dodania', 'Status_oferty', 'Powierzchnia_dzialki',
            'Uksztaltowanie_dzialki', 'Ksztalt_dzialki', 'Rodzaj_budynku', 'Typ_domu',
            'Typ_dachu', 'Parking', 'Liczba_pieter', 'Pietro', 'Powierzchnia',
            'Powierzchnia_uzytkowa', 'Liczba_pokoi', 'Umeblowanie', 'Typ_okien',
            'Typ_kuchni', 'Rodzaj_kanalizacji', 'Ogrzewanie', 'Prad', 'Gaz',
            'Czynsz_administracyjny', 'Przeznaczenie_dzialki', 'Stan_budynku',
            'Przeznaczenie_nieruchomosci', 'Stan_nieruchomosci', 'Rok_budowy', 'Tytul'
        ]
        localization_fields = ['Miejscowosc', 'Wojewodztwo', 'Powiat', 'Gmina', 'Ulica']

        today = datetime.today().strftime('%Y-%m-%d')
        agent_id = session['user_id']
        offer_description = form.get('Opis_oferty', '')

        # 🔹 Zbuduj dane z formularza — brakujące uzupełnij 'nd'
        estatedata = {f: form.get(f, 'nd') for f in estatedata_fields}
        raw_date = str(estatedata.get('Data_dodania', '')).strip().lower()
        if not raw_date or raw_date == 'nd':
            estatedata['Data_dodania'] = today
        estatedata['Status_oferty'] = 'Nieaktywna'
        estatedata['ID_agenta'] = agent_id

        localization = {f: form.get(f, 'nd') for f in localization_fields}

        with DatabaseConnectionManager() as conn:
            cursor = conn.cursor()

            # 🔹 Oblicz nowy ID
            cursor.execute("SELECT MAX(ID) FROM estatedata")
            max_estate = cursor.fetchone()[0] or 0

            cursor.execute("SELECT MAX(ID) FROM localization")
            max_loc = cursor.fetchone()[0] or 0

            offer_id = max(max_estate, max_loc) + 1

            # 🔸 Wstaw estatedata
            write_inputs(offer_ids=[offer_id])
            est_fields = ', '.join(['ID', 'ID_agenta'] + estatedata_fields)
            est_placeholders = ', '.join(['?'] * (len(estatedata_fields) + 2))
            est_values = [offer_id, estatedata['ID_agenta']] + [estatedata[f] for f in estatedata_fields]
            cursor.execute(
                f"INSERT INTO estatedata ({est_fields}) VALUES ({est_placeholders})",
                est_values
            )

            # 🔸 Wstaw localization
            loc_fields = ', '.join(['ID'] + localization_fields)
            loc_placeholders = ', '.join(['?'] * (len(localization_fields) + 1))
            loc_values = [offer_id] + [localization[f] for f in localization_fields]
            cursor.execute(
                f"INSERT INTO localization ({loc_fields}) VALUES ({loc_placeholders})",
                loc_values
            )

            conn.commit()

        # 📝 Zapisz opis jako .md
        folder = offer_media.offer_directory(offer_id)
        os.makedirs(folder, exist_ok=True)
        with open(offer_media.description_path(offer_id), 'w', encoding='utf-8') as f:
            f.write(offer_description)

        # 🖼️ Zapisz zdjęcia
        for idx, file in enumerate(files):
            if file and file.filename:
                ext = os.path.splitext(file.filename)[1]
                filename = offer_media.image_filename(offer_id, idx, ext)
                file.save(os.path.join(folder, filename))

        ensure_offer_sync_defaults(offer_id=offer_id)

        invalidate_offer_caches()
        return jsonify({'success': True, 'offer_id': offer_id})

    except Exception as e:
        print(f"Błąd podczas dodawania oferty: {e}")
        return jsonify({'error': 'Błąd podczas dodawania oferty'}), 500
    

@investmentmanager_bp.route('/offers/update/<int:offer_id>', methods=['POST'])
@offer_access_required
@guarded_route
def update_offer(offer_id):
    try:
        trigger_idb_backup()
        data = request.get_json()
        if not data:
            return jsonify({'error': 'Brak danych'}), 400

        # Oddziel opis
        offer_description = data.pop('Opis_oferty', None)

        # Pola lokalizacji
        localization_fields = {'Miejscowosc', 'Gmina', 'Powiat', 'Ulica', 'Wojewodztwo'}

        # Pola, których nie wolno edytować
        excluded_fields = {'Typ_nieruchomosci', 'Data_dodania', 'ID', 'ID_agenta', 'Status_oferty'}

        # Rozdzielenie danych
        estatedata_update = {
            k: v for k, v in data.items()
            if v != 'nd' and k not in excluded_fields and k not in localization_fields
        }

        localization_update = {
            k: v for k, v in data.items()
            if v != 'nd' and k in localization_fields
        }

        # Walidacja wartości zgodnie ze słownikiem
        property_type = data.get('Typ_nieruchomosci')
        validated_update = {}

        for field, value in estatedata_update.items():
            valid_options = get_field_options_backend(field, property_type)
            if valid_options:
                if value not in valid_options:
                    return jsonify({'error': f'Nieprawidłowa wartość dla pola {field}: {value}'}), 400
            validated_update[field] = value

        estatedata_update = validated_update

        # Utrzymuj spojna wartosc Miejscowosc w obu tabelach.
        # Czesci widokow korzystaja z e.Miejscowosc, a czesc z localization.Miejscowosc.
        if 'Miejscowosc' in localization_update:
            estatedata_update['Miejscowosc'] = localization_update['Miejscowosc']

        with DatabaseConnectionManager() as conn:
            cursor = conn.cursor()

            # Odrzuć pola techniczne/nieistniejące w schemacie, np. Portal_sync.
            cursor.execute("PRAGMA table_info(estatedata)")
            estatedata_columns = {row[1] for row in cursor.fetchall()}
            cursor.execute("PRAGMA table_info(localization)")
            localization_columns = {row[1] for row in cursor.fetchall()}

            raw_estatedata_keys = set(estatedata_update.keys())
            raw_localization_keys = set(localization_update.keys())

            estatedata_update = {
                field: value for field, value in estatedata_update.items()
                if field in estatedata_columns
            }
            localization_update = {
                field: value for field, value in localization_update.items()
                if field in localization_columns
            }

            skipped_fields = sorted(
                (raw_estatedata_keys - set(estatedata_update.keys())) |
                (raw_localization_keys - set(localization_update.keys()))
            )
            if skipped_fields:
                current_app.logger.info(
                    "Pominięto nieznane pola podczas update oferty %s: %s",
                    offer_id,
                    ", ".join(skipped_fields),
                )

            if not estatedata_update and not localization_update and offer_description is None:
                return jsonify({'error': 'Brak pól do aktualizacji'}), 400

            # Aktualizacja estatedata
            write_inputs(offer_ids=[offer_id], media=offer_description is not None)
            if estatedata_update:
                set_clause = ', '.join([f"{field} = ?" for field in estatedata_update])
                values = list(estatedata_update.values())
                cursor.execute(f"UPDATE estatedata SET {set_clause} WHERE ID = ?", (*values, offer_id))

            # Aktualizacja localization
            if localization_update:
                loc_clause = ', '.join([f"{field} = ?" for field in localization_update])
                loc_values = list(localization_update.values())
                cursor.execute(f"UPDATE localization SET {loc_clause} WHERE ID = ?", (*loc_values, offer_id))

            conn.commit()

        # Zapis opisu oferty do pliku markdown
        if offer_description is not None:
            folder = offer_media.offer_directory(offer_id)
            os.makedirs(folder, exist_ok=True)
            filepath = offer_media.description_path(offer_id)
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(offer_description)

        changed_fields = list(estatedata_update.keys()) + list(localization_update.keys())
        if offer_description is not None:
            changed_fields.append('Opis_oferty')
        mark_offer_sync_dirty(offer_id, reason='offer_update', changed_fields=changed_fields)

        invalidate_offer_caches()
        return jsonify({'success': True})

    except Exception as e:
        print(f"Błąd aktualizacji oferty: {e}")
        return jsonify({'error': 'Wystąpił błąd podczas zapisu'}), 500
    

@investmentmanager_bp.route('/offers/images/<int:offer_id>')
@offer_access_required
def list_offer_images(offer_id):
    return jsonify(offer_media.list_image_filenames(offer_id))

@investmentmanager_bp.route('/offers/images/<int:offer_id>/delete', methods=['POST'])
@offer_access_required
@guarded_route
def delete_offer_image(offer_id):
    data = request.get_json(silent=True) or {}
    filename = data.get('filename')
    folder = offer_media.offer_directory(offer_id)
    try:
        filename = validate_offer_image_filename(offer_id, filename or '')
        filepath = safe_child_path(folder, filename)
    except UnsafeFilename:
        return jsonify({'error': 'Nieprawidłowa nazwa pliku'}), 400

    if not os.path.isfile(filepath):
        return jsonify({'error': 'Plik nie istnieje'}), 404

    try:
        # Wyciągnij index usuwanego zdjęcia (np. 5 z 'image_123_url_5.jpg')
        deleted_index = int(filename.split('_url_')[-1].split('.')[0])
        extension = os.path.splitext(filename)[1]

        # Usuń wybrany plik
        write_inputs(offer_ids=[offer_id])
        os.remove(filepath)

        # Pobierz wszystkie pozostałe zdjęcia i przesortuj rosnąco wg indeksu
        files = offer_media.list_image_filenames(
            offer_id,
            extensions=offer_media.EDITABLE_IMAGE_EXTENSIONS,
            case_sensitive_prefix=True,
        )

        def extract_index(f):
            try:
                return int(f.split('_url_')[-1].split('.')[0])
            except:
                return -1

        files_with_index = sorted(
            [(f, extract_index(f)) for f in files if extract_index(f) > deleted_index],
            key=lambda x: x[1]
        )

        # Przesuń wszystkie z indexem > deleted_index
        for f, idx in files_with_index:
            old_path = os.path.join(folder, f)
            new_name = offer_media.image_filename(offer_id, idx - 1, os.path.splitext(f)[1])
            new_path = os.path.join(folder, new_name)
            os.rename(old_path, new_path)

        mark_offer_sync_dirty(offer_id, reason='image_deleted', changed_fields=['images'])
        invalidate_offer_caches()
        return jsonify({'success': True})
    except Exception as e:
        print(f"Błąd usuwania pliku lub reorganizacji: {e}")
        return jsonify({'error': 'Błąd usuwania lub reorganizacji'}), 500

    
@investmentmanager_bp.route('/offers/images/<int:offer_id>/upload', methods=['POST'])
@offer_access_required
@guarded_route
def upload_offer_image(offer_id):
    if 'image' not in request.files:
        return jsonify({'error': 'Brak pliku'}), 400

    image = request.files['image']
    original_filename = image.filename
    extension = os.path.splitext(original_filename)[1].lower()

    if extension not in ['.jpg', '.jpeg', '.png']:
        return jsonify({'error': 'Nieprawidłowy format'}), 400

    folder = offer_media.offer_directory(offer_id)
    os.makedirs(folder, exist_ok=True)

    try:
        # Znajdź najwyższy numer "url_N"
        existing = offer_media.list_image_filenames(
            offer_id,
            extensions=offer_media.EDITABLE_IMAGE_EXTENSIONS,
            case_sensitive_prefix=True,
        )
        max_index = -1
        for f in existing:
            try:
                idx = int(f.split('_url_')[-1].split('.')[0])
                if idx > max_index:
                    max_index = idx
            except:
                continue

        next_index = max_index + 1
        new_filename = offer_media.image_filename(offer_id, next_index, extension)
        save_path = os.path.join(folder, new_filename)
        write_inputs(offer_ids=[offer_id])
        image.save(save_path)

        mark_offer_sync_dirty(offer_id, reason='image_uploaded', changed_fields=['images'])
        invalidate_offer_caches()
        return jsonify({'success': True, 'filename': new_filename})
    except Exception as e:
        print(f"Błąd zapisu zdjęcia: {e}")
        return jsonify({'error': 'Nie udało się zapisać pliku'}), 500

    
@investmentmanager_bp.route('/offers/images/<int:offer_id>/set-main', methods=['POST'])
@offer_access_required
@guarded_route
def set_main_offer_image(offer_id):
    data = request.get_json(silent=True) or {}
    selected_filename = data.get('filename')

    if not selected_filename:
        return jsonify({'error': 'Brak pliku'}), 400

    folder = offer_media.offer_directory(offer_id)
    try:
        selected_filename = validate_offer_image_filename(offer_id, selected_filename)
        selected_path = safe_child_path(folder, selected_filename)
    except UnsafeFilename:
        return jsonify({'error': 'Nieprawidłowa nazwa pliku'}), 400

    if not os.path.isfile(selected_path):
        return jsonify({'error': 'Plik nie istnieje'}), 404

    try:
        # Przeskanuj wszystkie pliki zgodne z image_{id}_url_*
        files = sorted(offer_media.list_image_filenames(
            offer_id,
            extensions=offer_media.EDITABLE_IMAGE_EXTENSIONS,
            case_sensitive_prefix=True,
        ))

        # Znajdź aktualne główne zdjęcie (url_0)
        current_main = next((f for f in files if f'url_0' in f), None)
        if not current_main:
            return jsonify({'error': 'Nie znaleziono aktualnego głównego zdjęcia'}), 400

        # Jeśli wybrane zdjęcie to już główne – nic nie rób
        if selected_filename == current_main:
            return jsonify({'success': True})

        # Zamień nazwy: najpierw na tymczasowe, by nie nadpisać plików
        temp_name = os.path.join(folder, '__temp_main.jpg')
        write_inputs(offer_ids=[offer_id])
        os.rename(os.path.join(folder, selected_filename), temp_name)
        os.rename(os.path.join(folder, current_main), os.path.join(folder, selected_filename))
        os.rename(temp_name, os.path.join(folder, current_main))

        mark_offer_sync_dirty(offer_id, reason='main_image_changed', changed_fields=['images'])
        invalidate_offer_caches()
        return jsonify({'success': True})
    except Exception as e:
        print(f"Błąd przy ustawianiu zdjęcia jako głównego: {e}")
        return jsonify({'error': 'Wystąpił błąd podczas operacji'}), 500

@serialized_write
def save_backup_image(base_image: Image.Image, offer_id: int):
    write_inputs(offer_ids=[offer_id])
    folder = offer_media.offer_directory(offer_id)
    os.makedirs(folder, exist_ok=True)

    existing = offer_media.list_image_filenames(
        offer_id,
        extensions=offer_media.EDITABLE_IMAGE_EXTENSIONS,
        case_sensitive_prefix=True,
    )

    max_index = -1
    for f in existing:
        try:
            idx = int(f.split('_url_')[-1].split('.')[0])
            if idx > max_index:
                max_index = idx
        except:
            continue

    next_index = max_index + 1
    new_filename = offer_media.image_filename(offer_id, next_index, '.jpg')
    save_path = os.path.join(folder, new_filename)

    base_image.save(save_path, format='JPEG')
    return new_filename

@investmentmanager_bp.route('/offers/images/<int:offer_id>/label', methods=['POST'])
@offer_access_required
@guarded_route
def label_offer_image(offer_id):
    data = request.get_json(silent=True) or {}
    filename = data.get('filename')
    label = data.get('label', '').upper()

    folder = offer_media.offer_directory(offer_id)
    try:
        filename = validate_offer_image_filename(offer_id, filename or '')
        filepath = safe_child_path(folder, filename)
    except UnsafeFilename:
        return jsonify({'error': 'Nieprawidłowa nazwa pliku'}), 400

    if not os.path.isfile(filepath):
        return jsonify({'error': 'Plik nie istnieje'}), 404

    try:
        base = Image.open(filepath).convert('RGBA')
        txt = Image.new('RGBA', base.size, (255, 255, 255, 0))
        draw = ImageDraw.Draw(txt)

        font_size = int(base.size[1] * 0.12)

        font_path = os.path.join(
            current_app.root_path,
            'fonts',
            'DejaVuSans-Bold.ttf'
        )

        font = ImageFont.truetype(font_path, font_size)

        text_bbox = draw.textbbox((0, 0), label, font=font)
        text_width = text_bbox[2] - text_bbox[0]
        text_height = text_bbox[3] - text_bbox[1]

        position = (
            (base.size[0] - text_width) // 2,
            (base.size[1] - text_height) // 2
        )

        # Obrys (stroke)
        for dx in (-2, -1, 0, 1, 2):
            for dy in (-2, -1, 0, 1, 2):
                draw.text(
                    (position[0] + dx, position[1] + dy),
                    label,
                    font=font,
                    fill=(255, 0, 0, 180)
                )

        # Backup oryginału
        write_inputs(offer_ids=[offer_id])
        save_backup_image(base.convert('RGB'), offer_id)

        labeled = Image.alpha_composite(base, txt).convert('RGB')
        labeled.save(filepath, format='JPEG', quality=95)

        mark_offer_sync_dirty(offer_id, reason='image_label_changed', changed_fields=['images'])
        invalidate_offer_caches()
        return jsonify({'success': True})

    except Exception:
        current_app.logger.exception("Blad dodawania etykiety")
        return jsonify({'error': 'Blad przetwarzania zdjecia'}), 500

    
@investmentmanager_bp.route('/offers/sold/<int:offer_id>', methods=['POST'])
@offer_access_required
@guarded_route
def mark_offer_sold(offer_id):
    try:
        trigger_idb_backup()
        data = request.get_json()
        typ = data.get('typ')

        if typ not in ['sprzedaż', 'wynajem']:
            return jsonify({'error': 'Nieprawidłowy typ transakcji.'}), 400

        with DatabaseConnectionManager() as conn:
            cursor = conn.cursor()

            cursor.execute("SELECT Data_dodania FROM EstateData WHERE ID = ?", (offer_id,))
            row = cursor.fetchone()
            if not row:
                return jsonify({'error': 'Oferta nie istnieje'}), 404

            data_dodania = row[0]

            # Sprawdź duplikat
            cursor.execute("SELECT 1 FROM Sold WHERE ID = ?", (offer_id,))
            if cursor.fetchone():
                return jsonify({'error': 'Oferta już oznaczona jako sprzedana/wynajęta.'}), 400

            # Wstaw dane w zależności od typu
            if typ == 'sprzedaż':
                cena = data.get('cena_sprzedazy')
                procent = data.get('procent')
                if not cena or not procent:
                    return jsonify({'error': 'Brak danych sprzedaży.'}), 400

                write_inputs(offer_ids=[offer_id])
                cursor.execute("""
                    INSERT INTO Sold (ID, Data_dodania, Cena_wynajmu, Cena_sprzedaży, Procent)
                    VALUES (?, ?, ?, ?, ?)
                """, (offer_id, data_dodania, 'nd', cena, procent))

                cursor.execute("UPDATE EstateData SET Status_oferty = 'sprzedane' WHERE ID = ?", (offer_id,))

            elif typ == 'wynajem':
                cena = data.get('cena_wynajmu')
                if not cena:
                    return jsonify({'error': 'Brak ceny wynajmu.'}), 400

                write_inputs(offer_ids=[offer_id])
                cursor.execute("""
                    INSERT INTO Sold (ID, Data_dodania, Cena_wynajmu, Cena_sprzedaży, Procent)
                    VALUES (?, ?, ?, ?, ?)
                """, (offer_id, data_dodania, cena, 'nd', 'nd'))

                cursor.execute("UPDATE EstateData SET Status_oferty = 'wynajem' WHERE ID = ?", (offer_id,))

            conn.commit()

        mark_offer_sync_dirty(offer_id, reason='offer_marked_sold_or_rent', changed_fields=['Status_oferty'])
        invalidate_offer_caches()
        return jsonify({'success': True})

    except Exception as e:
        print(f"❌ Błąd w /offers/sold/{offer_id}: {e}")
        return jsonify({'error': 'Wystąpił błąd.'}), 500


@investmentmanager_bp.route('/offers/delete/<int:offer_id>', methods=['POST'])
@offer_access_required
@guarded_route
def delete_offer(offer_id):
    try:
        with DatabaseConnectionManager() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT Status_oferty FROM EstateData WHERE ID = ?", (offer_id,))
            offer_row = cursor.fetchone()
            if not offer_row:
                return jsonify({"error": "Oferta nie istnieje."}), 404

            status_oferty = (offer_row[0] or "").strip().lower()
            if status_oferty != "nieaktywna":
                return jsonify({"error": "Oferte mozna usunac tylko gdy ma status nieaktywna."}), 400

            cursor.execute(
                """
                SELECT COUNT(1)
                FROM offer_portal_sync
                WHERE offer_id = ?
                  AND (is_published = 1 OR needs_update = 1)
                """,
                (offer_id,),
            )
            blocking_portal_rows = int((cursor.fetchone() or [0])[0] or 0)
            if blocking_portal_rows > 0:
                return jsonify({"error": "Aby usunąć ofertę z aplikacji, nie może ona być opublikowana na portalach zewnętrznych."}), 400

        trigger_idb_backup()
        # 1. Usuń dane z bazy
        with DatabaseConnectionManager() as conn:
            cursor = conn.cursor()
            from InvestmentManager.integrator.export_attempts import has_unresolved_transport
            if has_unresolved_transport(conn,offer_id):
                return jsonify({"error":"Unresolved export transport; reconcile it before deleting the offer."}),409
            write_inputs(offer_ids=[offer_id])
            cursor.execute("DELETE FROM EstateData WHERE ID = ?", (offer_id,))
            cursor.execute("DELETE FROM Localization WHERE ID = ?", (offer_id,))
            cursor.execute("DELETE FROM offer_portal_sync WHERE offer_id = ?", (offer_id,))
            # Keep durable attempt/mutation history, including after ID reuse.
            conn.commit()

        # 2. Usuń folder oferty razem ze zdjęciami, opisem i dokumentami
        image_folder = storage_paths.offer_dir(offer_id)
        if os.path.isdir(image_folder):
            shutil.rmtree(image_folder)

        invalidate_offer_caches()
        return jsonify({"success": True})

    except Exception as e:
        print(f"Błąd usuwania oferty {offer_id}: {e}")
        return jsonify({"error": "Wystąpił błąd podczas usuwania oferty."}), 500
    




# 📌 ŚCIEŻKA GŁÓWNA DO OFERT

# ============================
# ✏️ API: ZAPISZ / ODCZYTAJ NOTATKI
# ============================

@investmentmanager_bp.route('/offers/notes/<int:offer_id>', methods=['GET', 'POST'])
@offer_access_required
def handle_notes(offer_id):
    offer_path = storage_paths.offer_dir(offer_id)
    notes_file = os.path.join(offer_path, 'notes.md')

    # 📝 POST – zapis notatki
    if request.method == 'POST':
        try:
            data = request.get_json()
            content = data.get('content', '')

            os.makedirs(offer_path, exist_ok=True)  # utwórz folder, jeśli nie istnieje

            with open(notes_file, 'w', encoding='utf-8') as f:
                f.write(content)

            return jsonify({'success': True})
        except Exception as e:
            print(f"Błąd zapisu notatek: {e}")
            return jsonify({'error': 'Nie udało się zapisać notatek'}), 500

    # 📖 GET – odczyt notatki
    try:
        if not os.path.isfile(notes_file):
            return jsonify({'content': ''})  # Brak notatki = pusty string

        with open(notes_file, 'r', encoding='utf-8') as f:
            content = f.read()

        return jsonify({'content': content})
    except Exception as e:
        print(f"Błąd odczytu notatek: {e}")
        return jsonify({'error': 'Nie udało się wczytać notatek'}), 500


DESCRIPTION_PREVIEW_MAX_CHARS = 200_000


@investmentmanager_bp.route('/offers/description/preview', methods=['POST'])
def preview_offer_description():
    """Editor preview rendered like the published page: Markdown -> HTML -> nh3 allow-list sanitizer (never raw HTML to the browser)."""
    payload = request.get_json(silent=True)
    text = payload.get('markdown') if isinstance(payload, dict) else None
    if not isinstance(text, str):
        return jsonify({'error': 'Wymagane pole "markdown" (tekst).'}), 400
    if len(text) > DESCRIPTION_PREVIEW_MAX_CHARS:
        return jsonify({'error': 'Opis jest zbyt długi do podglądu.'}), 413
    return jsonify({'html': str(sanitize_description_html(markdown.markdown(text)))})


@investmentmanager_bp.route('/offers/description/<int:offer_id>', methods=['GET'])
@offer_access_required
def get_offer_description(offer_id):
    try:
        content = offer_media.read_description_text(offer_id)
        response = make_response(content)
        response.headers["Content-Type"] = "text/plain; charset=utf-8"
        return response
    except Exception as e:
        current_app.logger.warning("Nie udalo sie wczytac opisu oferty %s: %s", offer_id, e)
        return jsonify({'error': 'Nie udało się wczytać opisu oferty'}), 500
    

# ============================
# 📂 API: DODAJ / POBIERZ / USUŃ DOKUMENTY
# ============================

@investmentmanager_bp.route('/offers/documents/<int:offer_id>', methods=['GET', 'POST'])
@offer_access_required
def handle_documents(offer_id):
    docs_path = storage_paths.offer_dir(offer_id) / 'docs'
    os.makedirs(docs_path, exist_ok=True)

    # 📤 POST – upload dokumentu
    if request.method == 'POST':
        try:
            file = request.files.get('file')
            if not file:
                return jsonify({'error': 'Brak pliku'}), 400

            try:
                filename = validate_document_filename(file.filename)
                save_path = safe_child_path(docs_path, filename)
            except UnsafeFilename:
                return jsonify({'error': 'Nieprawidłowa nazwa pliku'}), 400
            force = request.args.get('force') == 'true'

            file_already_exists = os.path.exists(save_path)

            if file_already_exists and not force:
                return jsonify({'exists': True, 'filename': filename}), 200

            file.save(save_path)
            return jsonify({
                'success': True,
                'overwritten': file_already_exists
            })

        except Exception as e:
            print(f"Błąd uploadu dokumentu: {e}")
            return jsonify({'error': 'Nie udało się zapisać dokumentu'}), 500

    # 📦 GET – lista dokumentów
    try:
        files = os.listdir(docs_path)
        documents = [f for f in files if os.path.isfile(os.path.join(docs_path, f))]
        return jsonify({'documents': documents})
    except Exception as e:
        print(f"Błąd pobierania listy dokumentów: {e}")
        return jsonify({'error': 'Nie udało się pobrać dokumentów'}), 500
    
@investmentmanager_bp.route('/offers/documents/<int:offer_id>/file/<string:filename>', methods=['GET'])
@offer_access_required
def download_offer_document(offer_id, filename):
    """Storage Path Layer / Phase 2: authenticated document download.

    Offer documents live under storage_paths.offer_dir(offer_id)/docs/,
    which in external DATA_DIR mode is fully outside the checkout and
    outside Flask's static_folder -- nothing serves them publicly any
    more (see blueprints/media/media.py, which deliberately does NOT
    allow-list docs/*). This route is the CRM-authenticated replacement:
    it inherits the blueprint's existing require_crm_session before_request
    gate (InvestmentManager/__init__.py), so an anonymous request is
    rejected before this function body ever runs, in both legacy and
    external mode.

    <string:filename> (not <path:filename>) structurally rejects any
    slash, so this cannot be used to escape docs_path via '../'.

    Served inline (as_attachment=False), not as a forced download: the
    frontend (offers_documents.js) reuses this same URL both for inline
    preview (iframe/img/text fetch) and for the actual download link,
    where the anchor's own `download` attribute already forces a save
    dialog client-side regardless of Content-Disposition.
    """
    docs_path = storage_paths.offer_dir(offer_id) / 'docs'
    # <string:filename> already rejects any slash; validate + contain as
    # defense in depth (also catches backslashes/drive prefixes) without
    # changing legitimate URLs.
    try:
        safe_name = validate_document_filename(filename)
        safe_path = safe_child_path(docs_path, safe_name)
    except UnsafeFilename:
        return jsonify({'error': 'Plik nie istnieje'}), 404
    if not safe_path.is_file():
        return jsonify({'error': 'Plik nie istnieje'}), 404
    return _document_response(docs_path, safe_name)


# Types the offers panel previews inline (iframe / img / text fetch). Everything else - html, htm, svg, xml, js, unknown types -
# is an ACTIVE or opaque document uploaded by an agent and is only ever served as a download, so it cannot run in the CRM origin.
INLINE_DOCUMENT_IMAGES = frozenset({'jpg', 'jpeg', 'png', 'gif', 'webp'})
INLINE_DOCUMENT_TEXT = frozenset({'txt', 'csv', 'json'})
INLINE_DOCUMENT_TYPES = INLINE_DOCUMENT_IMAGES | INLINE_DOCUMENT_TEXT | {'pdf'}


def _document_response(docs_path, safe_name):
    extension = safe_name.rsplit('.', 1)[-1].lower() if '.' in safe_name else ''
    inline = extension in INLINE_DOCUMENT_TYPES
    response = send_from_directory(docs_path, safe_name, as_attachment=not inline)
    response.headers['X-Content-Type-Options'] = 'nosniff'
    if extension in INLINE_DOCUMENT_TEXT:
        response.headers['Content-Type'] = 'text/plain; charset=utf-8'          # never rendered as markup, even if opened directly
    if extension == 'pdf':
        # the browser's own PDF viewer needs no `sandbox` and no `object-src 'none'` (both disable it in the iframe preview):
        # an explicit policy here also keeps the site-wide one off this response
        response.headers['Content-Security-Policy'] = "frame-ancestors 'self'"
    else:
        response.headers['Content-Security-Policy'] = "default-src 'none'; sandbox"
    return response


@investmentmanager_bp.route('/offers/documents/<int:offer_id>/delete', methods=['POST'])
@offer_access_required
def delete_document(offer_id):
    try:
        data = request.get_json(silent=True) or {}
        filename = data.get('filename')

        if not filename:
            return jsonify({'error': 'Brak nazwy pliku'}), 400

        try:
            filename = validate_document_filename(filename)
            doc_path = safe_child_path(storage_paths.offer_dir(offer_id) / 'docs', filename)
        except UnsafeFilename:
            return jsonify({'error': 'Nieprawidłowa nazwa pliku'}), 400
        if not os.path.isfile(doc_path):
            return jsonify({'error': 'Plik nie istnieje'}), 404

        os.remove(doc_path)
        return jsonify({'success': True})

    except Exception as e:
        print(f"Błąd usuwania dokumentu: {e}")
        return jsonify({'error': 'Wystąpił błąd podczas usuwania dokumentu'}), 500


@investmentmanager_bp.route('/offers/card/<int:offer_id>', methods=['GET'])
@offer_access_required
def download_offer_card(offer_id):
    try:
        preview_mode = request.args.get("preview") == "1"
        rendered = offer_cards.generate_offer_card(
            offer_id, request.url_root.rstrip("/")
        )
        response = make_response(rendered)
        response.headers["Content-Type"] = "text/html; charset=utf-8"
        if preview_mode:
            response.headers["Content-Disposition"] = "inline"
        else:
            response.headers["Content-Disposition"] = f'attachment; filename="Karta_{offer_id}.html"'
        return response
    except offer_cards.OfferNotFound:
        return jsonify({"error": "Oferta nie istnieje"}), 404
    except Exception as exc:
        current_app.logger.exception("Błąd generowania karty oferty %s: %s", offer_id, exc)
        return jsonify({"error": "Nie udało się wygenerować karty oferty"}), 500

@investmentmanager_bp.route('/offers/announcement-card/<int:offer_id>', methods=['GET'])
@offer_access_required
def download_announcement_card(offer_id):
    try:
        preview_mode = request.args.get("preview") == "1"
        base_url = request.url_root.rstrip("/")
        rendered, download_prefix = offer_cards.generate_announcement_card(
            offer_id,
            base_url,
            request.args.get("bg"),
            request.args.get("accent"),
            request.args.get("variant"),
        )

        response = make_response(rendered)
        response.headers["Content-Type"] = "text/html; charset=utf-8"
        if preview_mode:
            response.headers["Content-Disposition"] = "inline"
        else:
            response.headers["Content-Disposition"] = f'attachment; filename="{download_prefix}_{offer_id}.html"'
        return response
    except offer_cards.OfferNotFound:
        return jsonify({"error": "Oferta nie istnieje"}), 404
    except Exception as exc:
        current_app.logger.exception("Blad generowania karty ogloszenia %s: %s", offer_id, exc)
        return jsonify({"error": "Nie udalo sie wygenerowac karty ogloszenia"}), 500




