﻿import json
import logging
import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Any

from InvestmentManager.foreign_offer_validation import (
    read_foreign_offer_export_state,
    refresh_foreign_offer_export_state,
)
from InvestmentManager.foreign_sync_merge import (
    SYNC_MANAGED_FIELDS,
    SyncContractError,
    canonical_current_value,
    canonical_value,
)
from modules.core import storage_paths

logger = logging.getLogger(__name__)

VALID_FOREIGN_PORTALS = ("domiporta", "tabelaofert")


def _now_iso() -> str:
    return datetime.utcnow().isoformat(timespec="seconds")


def open_foreign_offers_connection() -> sqlite3.Connection:
    db_path = storage_paths.foreign_offers_db_path()
    db_path.parent.mkdir(parents=True, exist_ok=True)
    from InvestmentManager.integrator.foreign_consistency import ForeignConnection
    conn = sqlite3.connect(str(db_path), factory=ForeignConnection, cached_statements=0)
    try:
        conn.row_factory = sqlite3.Row
        conn.execute("PRAGMA journal_mode=WAL")
        conn.execute("PRAGMA synchronous=NORMAL")
        conn.execute("PRAGMA foreign_keys=ON")
        return conn
    except BaseException:
        conn.close()
        raise


def ensure_foreign_offers_schema(conn: sqlite3.Connection) -> None:
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS foreign_developments (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL COLLATE NOCASE UNIQUE,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
        );

        CREATE TABLE IF NOT EXISTS foreign_offers (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            source_platform TEXT NOT NULL,
            source_url TEXT NOT NULL,
            source_offer_ref TEXT,
            source_country_code TEXT,
            source_country_name TEXT,
            source_region_name TEXT,
            source_city_name TEXT,
            source_location_text TEXT,
            source_market_type TEXT,
            offer_title TEXT,
            offer_description TEXT,
            price_value NUMERIC,
            price_currency TEXT,
            price_value_pln NUMERIC,
            area_total_m2 NUMERIC,
            area_net_m2 NUMERIC,
            area_gross_m2 NUMERIC,
            area_living_m2 NUMERIC,
            plot_area_m2 NUMERIC,
            rooms_count INTEGER,
            bedrooms_count INTEGER,
            bathrooms_count INTEGER,
            floor INTEGER,
            floor_override INTEGER,
            floors_count INTEGER,
            construction_year INTEGER,
            latitude REAL,
            longitude REAL,
            map_place TEXT,
            map_accuracy TEXT,
            property_type_source TEXT,
            property_type_normalized TEXT,
            offer_type_normalized TEXT,
            market_type_normalized TEXT,
            category_id_domiporta TEXT,
            building_type_source TEXT,
            building_type_domiporta TEXT,
            plot_type_source TEXT,
            plot_type_domiporta TEXT,
            commercial_usage_source TEXT,
            commercial_usage_domiporta TEXT,
            sewerage_source TEXT,
            sewerage_domiporta TEXT,
            kitchen_source TEXT,
            kitchen_normalized TEXT,
            standard_source TEXT,
            standard_normalized TEXT,
            street_name TEXT,
            county_name TEXT,
            community_name TEXT,
            agent_identifier TEXT NOT NULL DEFAULT '101',
            agent_name TEXT,
            agent_email TEXT,
            agent_phone TEXT,
            development_id INTEGER REFERENCES foreign_developments(id),
            is_active INTEGER NOT NULL DEFAULT 1,
            is_export_ready INTEGER NOT NULL DEFAULT 0,
            needs_update INTEGER NOT NULL DEFAULT 0,
            last_source_sync_at TEXT,
            last_source_change_at TEXT,
            last_exported_at TEXT,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            UNIQUE(source_platform, source_url)
        );

        CREATE TABLE IF NOT EXISTS foreign_offer_images (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            foreign_offer_id INTEGER NOT NULL,
            image_url TEXT NOT NULL,
            sort_order INTEGER NOT NULL DEFAULT 0,
            is_primary INTEGER NOT NULL DEFAULT 0,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS foreign_offer_features_raw (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            foreign_offer_id INTEGER NOT NULL,
            feature_text TEXT NOT NULL,
            normalized_key TEXT,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS foreign_offer_raw_snapshots (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            foreign_offer_id INTEGER NOT NULL,
            payload_json TEXT NOT NULL,
            payload_hash TEXT NOT NULL,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS foreign_offer_sync_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            foreign_offer_id INTEGER NOT NULL,
            sync_status TEXT NOT NULL,
            change_detected INTEGER NOT NULL DEFAULT 0,
            summary TEXT,
            raw_hash_before TEXT,
            raw_hash_after TEXT,
            started_at TEXT,
            finished_at TEXT,
            FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS foreign_offer_export_warnings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            foreign_offer_id INTEGER NOT NULL,
            warning_code TEXT NOT NULL,
            warning_message TEXT NOT NULL,
            field_name TEXT,
            is_blocking INTEGER NOT NULL DEFAULT 0,
            resolved_at TEXT,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS foreign_offer_portal_sync (
            foreign_offer_id INTEGER NOT NULL,
            portal_key TEXT NOT NULL,
            is_published INTEGER NOT NULL DEFAULT 0,
            needs_update INTEGER NOT NULL DEFAULT 0,
            last_action TEXT,
            last_filename TEXT,
            last_bytes INTEGER,
            last_error TEXT,
            last_uploaded_at TEXT,
            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (foreign_offer_id, portal_key),
            FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
        );

        CREATE TABLE IF NOT EXISTS foreign_offer_portal_sync_events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            foreign_offer_id INTEGER NOT NULL,
            portal_key TEXT,
            event_type TEXT NOT NULL,
            payload_json TEXT,
            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (foreign_offer_id) REFERENCES foreign_offers(id) ON DELETE CASCADE
        );

        -- One row per run of a source synchronization (SYNC-1: persistence only;
        -- nothing writes here yet). Must exist before foreign_offers.last_sync_run_id
        -- is added below, which references it.
        CREATE TABLE IF NOT EXISTS foreign_sync_runs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            source_platform TEXT NOT NULL,
            status TEXT NOT NULL DEFAULT 'running'
                CHECK (status IN ('running', 'completed', 'failed')),
            started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
            finished_at TEXT,
            discovered_count INTEGER NOT NULL DEFAULT 0,
            new_count INTEGER NOT NULL DEFAULT 0,
            updated_count INTEGER NOT NULL DEFAULT 0,
            unchanged_count INTEGER NOT NULL DEFAULT 0,
            missing_count INTEGER NOT NULL DEFAULT 0,
            error_count INTEGER NOT NULL DEFAULT 0,
            error_message TEXT
        );

        CREATE INDEX IF NOT EXISTS idx_foreign_sync_runs_source
            ON foreign_sync_runs(source_platform, id DESC);

        CREATE INDEX IF NOT EXISTS idx_foreign_offers_source_platform
            ON foreign_offers(source_platform);

        CREATE INDEX IF NOT EXISTS idx_foreign_offers_source_offer_ref
            ON foreign_offers(source_offer_ref);

        CREATE INDEX IF NOT EXISTS idx_foreign_offers_country_city
            ON foreign_offers(source_country_name, source_city_name);

        CREATE INDEX IF NOT EXISTS idx_foreign_offers_export_ready
            ON foreign_offers(is_active, is_export_ready, needs_update);

        CREATE INDEX IF NOT EXISTS idx_foreign_offer_images_offer_id
            ON foreign_offer_images(foreign_offer_id, sort_order);

        CREATE INDEX IF NOT EXISTS idx_foreign_offer_features_offer_id
            ON foreign_offer_features_raw(foreign_offer_id);

        CREATE INDEX IF NOT EXISTS idx_foreign_offer_snapshots_offer_id
            ON foreign_offer_raw_snapshots(foreign_offer_id, created_at DESC);

        CREATE INDEX IF NOT EXISTS idx_foreign_offer_sync_log_offer_id
            ON foreign_offer_sync_log(foreign_offer_id, started_at DESC);

        CREATE INDEX IF NOT EXISTS idx_foreign_offer_warnings_offer_id
            ON foreign_offer_export_warnings(foreign_offer_id, is_blocking);

        CREATE INDEX IF NOT EXISTS idx_foreign_offer_portal_sync_offer_id
            ON foreign_offer_portal_sync(foreign_offer_id, is_published, needs_update);

        CREATE INDEX IF NOT EXISTS idx_foreign_offer_portal_events_offer_id
            ON foreign_offer_portal_sync_events(foreign_offer_id, created_at DESC);

        CREATE TRIGGER IF NOT EXISTS trg_foreign_offers_updated_at
        AFTER UPDATE ON foreign_offers
        FOR EACH ROW
        BEGIN
            UPDATE foreign_offers
            SET updated_at = CURRENT_TIMESTAMP
            WHERE id = NEW.id;
        END;
        """
    )
    _ensure_foreign_offers_development_column(conn)
    _add_foreign_offers_column_if_missing(conn, "floor_override", "INTEGER")
    _add_foreign_offers_column_if_missing(conn, "area_net_m2", "NUMERIC")
    _add_foreign_offers_column_if_missing(conn, "area_gross_m2", "NUMERIC")
    _ensure_foreign_source_identity(conn)
    _ensure_foreign_sync_merge_columns(conn)
    from InvestmentManager.integrator.foreign_consistency import install_guards
    install_guards(conn,allow_upgrade=True)


def _add_column_if_missing(conn: sqlite3.Connection, table: str, column: str, definition: str) -> None:
    # Databases created before a column existed lack it; CREATE TABLE IF NOT
    # EXISTS in ensure_foreign_offers_schema never alters an existing table.
    columns = {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}
    if column in columns:
        return
    try:
        conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition}")
    except sqlite3.OperationalError as exc:
        # A concurrent initialization may have added it in the meantime.
        if "duplicate column name" not in str(exc).lower():
            raise


def _add_foreign_offers_column_if_missing(conn: sqlite3.Connection, column: str, definition: str) -> None:
    _add_column_if_missing(conn, "foreign_offers", column, definition)


# Providers whose source_offer_ref is NOT enforced unique. TripInvest predates
# source identity: its ref is the numeric id at the end of a slug URL and is
# not guaranteed to map 1:1 to source_url (UNIQUE(source_platform, source_url)
# is its only key). Enforcing (platform, ref) there would turn today's silent
# duplicate on a renamed URL into a failing import, i.e. change TripInvest
# behaviour. Lookups for it still work but may report ambiguity.
_SOURCE_OFFER_REF_UNENFORCED_PLATFORMS = ("tripinvest",)

_source_identity_warning_logged = False


def _ensure_foreign_sync_merge_columns(conn: sqlite3.Connection) -> None:
    """SYNC-2B: what the generic sync merge needs on top of the SYNC-1 identity.

    - foreign_offers.source_values_json: the last non-NULL values the source
      reported for the sync-managed fields, the gallery and the features, plus
      whether the sync assigned a development. It is the "previous source"
      side of the three-way merge (see InvestmentManager/foreign_sync_merge.py).
      Written by the sync layer only; the working columns stay the values the
      CRM and exports read.
    - foreign_offer_sync_log.sync_run_id: which run produced a log row.
    """
    _add_column_if_missing(conn, "foreign_offers", "source_values_json", "TEXT")
    _add_column_if_missing(
        conn, "foreign_offer_sync_log", "sync_run_id", "INTEGER REFERENCES foreign_sync_runs(id)"
    )


def _ensure_foreign_source_identity(conn: sqlite3.Connection) -> None:
    """SYNC-1: additive columns/indexes for source identity and sync metadata.

    Field ownership (documented here because it constrains SYNC-2): source
    synchronization must preserve explicit CRM/manual overrides. Everything
    added here is written by the sync layer only; nothing in SYNC-1 overwrites
    an offer field, and the ownership policy per field is a SYNC-2 decision.

    - foreign_developments.source_platform / source_key: identity of a
      development at its source. Both NULL for manually created ones (legal).
      foreign_developments.id stays the canonical Investment identity
      (exports use foreign_dev_<id>).
    - foreign_offers.last_sync_run_id / source_payload_hash: which run last saw
      the offer and the hash of the source payload then. "Last seen" is the
      existing last_source_sync_at, which every successful source import
      already sets; it means "present in the source", NOT "active".
    """
    global _source_identity_warning_logged

    _add_column_if_missing(conn, "foreign_developments", "source_platform", "TEXT")
    _add_column_if_missing(conn, "foreign_developments", "source_key", "TEXT")
    _add_column_if_missing(
        conn, "foreign_offers", "last_sync_run_id", "INTEGER REFERENCES foreign_sync_runs(id)"
    )
    _add_column_if_missing(conn, "foreign_offers", "source_payload_hash", "TEXT")

    # New columns, so no existing row can violate this.
    conn.execute(
        """
        CREATE UNIQUE INDEX IF NOT EXISTS ux_foreign_developments_source_identity
            ON foreign_developments(source_platform, source_key)
            WHERE source_platform IS NOT NULL AND source_key IS NOT NULL
        """
    )

    excluded = ", ".join(f"'{platform}'" for platform in _SOURCE_OFFER_REF_UNENFORCED_PLATFORMS)
    try:
        conn.execute(
            f"""
            CREATE UNIQUE INDEX IF NOT EXISTS ux_foreign_offers_source_identity
                ON foreign_offers(source_platform, source_offer_ref)
                WHERE source_offer_ref IS NOT NULL
                  AND source_offer_ref <> ''
                  AND source_platform NOT IN ({excluded})
            """
        )
    except sqlite3.IntegrityError:
        # Existing rows already duplicate an identity. This runs on every
        # request, so never take the CRM down over it: skip the constraint,
        # say so once, and let lookups report the ambiguity.
        if not _source_identity_warning_logged:
            _source_identity_warning_logged = True
            logger.warning(
                "foreign_offers has duplicate (source_platform, source_offer_ref) rows; "
                "ux_foreign_offers_source_identity was not created."
            )


def _ensure_foreign_offers_development_column(conn: sqlite3.Connection) -> None:
    _add_foreign_offers_column_if_missing(
        conn, "development_id", "INTEGER REFERENCES foreign_developments(id)"
    )
    # Must run only after the column is guaranteed to exist.
    conn.execute(
        """
        CREATE INDEX IF NOT EXISTS idx_foreign_offers_development_id
            ON foreign_offers(development_id)
        """
    )


def get_foreign_offer_refresh_row(foreign_offer_id: int):
    """Row (id, source_platform, source_url) of one foreign offer, or None. Opens its own connection (the caller initialises the database)."""
    with open_foreign_offers_connection() as conn:
        return conn.execute(
            """
            SELECT id, source_platform, source_url
            FROM foreign_offers
            WHERE id = ?
            LIMIT 1
            """,
            (int(foreign_offer_id),),
        ).fetchone()


def list_active_tripinvest_refresh_rows() -> list:
    """Rows (id, source_url) of the active TripInvest foreign offers, by id. Opens its own connection (the caller initialises the database)."""
    with open_foreign_offers_connection() as conn:
        return conn.execute(
            """
            SELECT id, source_url
            FROM foreign_offers
            WHERE source_platform = 'tripinvest'
              AND is_active = 1
            ORDER BY id ASC
            """
        ).fetchall()


def initialize_foreign_offers_db() -> Path:
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        conn.commit()
    return storage_paths.foreign_offers_db_path()


def _insert_portal_event(conn, foreign_offer_id: int, portal_key: str | None, event_type: str, payload: dict[str, Any]) -> None:
    conn.execute(
        """
        INSERT INTO foreign_offer_portal_sync_events (foreign_offer_id, portal_key, event_type, payload_json, created_at)
        VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
        """,
        (int(foreign_offer_id), portal_key, event_type, json.dumps(payload, ensure_ascii=False, sort_keys=True)),
    )


def mark_foreign_offer_requires_update(conn, foreign_offer_id: int, reason: str, changed_fields: list[str]) -> int:
    published_rows = conn.execute(
        """
        SELECT portal_key
        FROM foreign_offer_portal_sync
        WHERE foreign_offer_id = ? AND is_published = 1
        """,
        (int(foreign_offer_id),),
    ).fetchall()
    published_portals = [str(row["portal_key"]) for row in published_rows if row["portal_key"]]
    payload = {"reason": reason, "changed_fields": changed_fields}

    if not published_portals:
        _insert_portal_event(conn, foreign_offer_id, None, "update_ignored_no_publication", payload)
        return 0

    for portal_key in published_portals:
        conn.execute(
            """
            UPDATE foreign_offer_portal_sync
            SET needs_update = 1,
                updated_at = CURRENT_TIMESTAMP
            WHERE foreign_offer_id = ? AND portal_key = ?
            """,
            (int(foreign_offer_id), portal_key),
        )
        _insert_portal_event(conn, foreign_offer_id, portal_key, "update_required", payload)

    conn.execute(
        """
        UPDATE foreign_offers
        SET needs_update = 1
        WHERE id = ?
        """,
        (int(foreign_offer_id),),
    )
    return len(published_portals)


def ensure_foreign_offer_sync_defaults(conn: sqlite3.Connection, foreign_offer_id: int) -> None:
    now = _now_iso()
    for portal_key in VALID_FOREIGN_PORTALS:
        conn.execute(
            """
            INSERT INTO foreign_offer_portal_sync (
                foreign_offer_id, portal_key, is_published, needs_update, last_action,
                last_filename, last_bytes, last_error, last_uploaded_at, updated_at
            )
            VALUES (?, ?, 0, 0, 'unpublished', NULL, NULL, NULL, NULL, ?)
            ON CONFLICT(foreign_offer_id, portal_key) DO NOTHING
            """,
            (int(foreign_offer_id), portal_key, now),
        )


def _foreign_offer_filter_conditions(filters: dict | None) -> tuple[list[str], list]:
    filters = filters or {}
    conditions = []
    params = []

    source = filters.get("source")
    if source:
        conditions.append("fo.source_platform = ?")
        params.append(str(source))

    market = filters.get("market")
    if market == "missing":
        conditions.append("(fo.market_type_normalized IS NULL OR TRIM(fo.market_type_normalized) = '')")
    elif market:
        conditions.append("fo.market_type_normalized = ?")
        params.append(str(market))

    development_id = filters.get("development_id")
    if development_id is not None:
        conditions.append("fo.development_id = ?")
        params.append(int(development_id))

    readiness = filters.get("readiness")
    if readiness == "ready":
        conditions.append("fo.is_export_ready = 1")
    elif readiness == "needs_completion":
        conditions.append("fo.is_export_ready = 0")

    activity = filters.get("activity")
    if activity == "active":
        conditions.append("fo.is_active = 1")
    elif activity == "inactive":
        conditions.append("fo.is_active = 0")

    return conditions, params


def _where_clause(filters: dict | None) -> tuple[str, list]:
    conditions, params = _foreign_offer_filter_conditions(filters)
    if not conditions:
        return "", params
    return "WHERE " + " AND ".join(conditions), params


def _offer_id_filter_clause(offer_ids: list[int]) -> tuple[str, list[int]]:
    if not offer_ids:
        return "WHERE 1 = 0", []
    placeholders = ", ".join("?" for _ in offer_ids)
    return f"WHERE foreign_offer_id IN ({placeholders})", offer_ids


def list_foreign_offer_filter_developments(filters: dict | None = None) -> list[dict]:
    filter_values = dict(filters or {})
    filter_values.pop("development_id", None)
    where_clause, params = _where_clause(filter_values)
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        rows = conn.execute(
            f"""
            SELECT DISTINCT fd.id, fd.name, fd.created_at, fd.updated_at
            FROM foreign_offers fo
            JOIN foreign_developments fd ON fd.id = fo.development_id
            {where_clause}
            ORDER BY fd.name COLLATE NOCASE ASC, fd.id ASC
            """,
            params,
        ).fetchall()
    return [_serialize_development_row(row) for row in rows]


def list_foreign_offers_page(filters: dict | None = None, page: int = 1, per_page: int = 200) -> dict:
    page = max(1, int(page))
    per_page = max(1, int(per_page))
    offset = (page - 1) * per_page
    where_clause, params = _where_clause(filters)

    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        total_count = int(
            conn.execute(
                f"""
                SELECT COUNT(*)
                FROM foreign_offers fo
                {where_clause}
                """,
                params,
            ).fetchone()[0]
        )
        rows = conn.execute(
            f"""
            SELECT
                fo.id,
                fo.source_platform,
                fo.source_url,
                fo.source_offer_ref,
                fo.offer_title,
                fo.source_country_name,
                fo.source_region_name,
                fo.source_city_name,
                fo.source_location_text,
                fo.source_market_type,
                fo.price_value,
                fo.price_currency,
                fo.area_total_m2,
                fo.rooms_count,
                fo.bedrooms_count,
                fo.bathrooms_count,
                fo.floor,
                fo.floor_override,
                COALESCE(fo.floor_override, fo.floor) AS effective_floor,
                fo.offer_description,
                fo.property_type_source,
                fo.offer_type_normalized,
                fo.market_type_normalized,
                fo.map_place,
                fo.map_accuracy,
                fo.latitude,
                fo.longitude,
                fo.category_id_domiporta,
                fo.is_export_ready,
                fo.is_active,
                fo.needs_update,
                fo.last_source_sync_at,
                fo.last_source_change_at,
                fo.created_at,
                fo.development_id,
                fd.name AS development_name,
                (
                    SELECT COUNT(*)
                    FROM foreign_offer_export_warnings few
                    WHERE few.foreign_offer_id = fo.id
                ) AS warning_count,
                (
                    SELECT COUNT(*)
                    FROM foreign_offer_export_warnings few
                    WHERE few.foreign_offer_id = fo.id AND few.is_blocking = 1
                ) AS blocking_warning_count
            FROM foreign_offers fo
            LEFT JOIN foreign_developments fd ON fd.id = fo.development_id
            {where_clause}
            ORDER BY fo.id DESC
            LIMIT ? OFFSET ?
            """,
            [*params, per_page, offset],
        ).fetchall()

        offer_ids = [int(row["id"]) for row in rows]
        related_clause, related_params = _offer_id_filter_clause(offer_ids)

        portal_rows = conn.execute(
            f"""
            SELECT foreign_offer_id, portal_key, is_published, needs_update, last_error, last_uploaded_at
            FROM foreign_offer_portal_sync
            {related_clause}
            ORDER BY foreign_offer_id DESC, portal_key ASC
            """,
            related_params,
        ).fetchall()

        warning_rows = conn.execute(
            f"""
            SELECT foreign_offer_id, warning_code, warning_message, field_name, is_blocking, created_at
            FROM foreign_offer_export_warnings
            {related_clause} AND resolved_at IS NULL
            ORDER BY foreign_offer_id DESC, is_blocking DESC, created_at ASC, id ASC
            """,
            related_params,
        ).fetchall()

        image_rows = conn.execute(
            f"""
            SELECT foreign_offer_id, image_url, sort_order, is_primary
            FROM foreign_offer_images
            {related_clause}
            ORDER BY foreign_offer_id DESC, sort_order ASC, id ASC
            """,
            related_params,
        ).fetchall()

        feature_rows = conn.execute(
            f"""
            SELECT foreign_offer_id, feature_text, normalized_key
            FROM foreign_offer_features_raw
            {related_clause}
            ORDER BY foreign_offer_id DESC, id ASC
            """,
            related_params,
        ).fetchall()

    portal_map: dict[int, dict] = {}
    for row in portal_rows:
        offer_portals = portal_map.setdefault(int(row["foreign_offer_id"]), {})
        offer_portals[str(row["portal_key"])] = {
            "is_published": int(row["is_published"] or 0),
            "needs_update": int(row["needs_update"] or 0),
            "last_error": row["last_error"] or "",
            "last_uploaded_at": row["last_uploaded_at"] or "",
        }

    warnings_map: dict[int, list[dict]] = {}
    for row in warning_rows:
        warnings_map.setdefault(int(row["foreign_offer_id"]), []).append(
            {
                "warning_code": row["warning_code"] or "",
                "warning_message": row["warning_message"] or "",
                "field_name": row["field_name"] or "",
                "is_blocking": int(row["is_blocking"] or 0),
                "created_at": row["created_at"] or "",
            }
        )

    images_map: dict[int, list[dict]] = {}
    for row in image_rows:
        images_map.setdefault(int(row["foreign_offer_id"]), []).append(
            {
                "image_url": row["image_url"] or "",
                "sort_order": int(row["sort_order"] or 0),
                "is_primary": int(row["is_primary"] or 0),
            }
        )

    features_map: dict[int, list[dict]] = {}
    for row in feature_rows:
        features_map.setdefault(int(row["foreign_offer_id"]), []).append(
            {
                "feature_text": row["feature_text"] or "",
                "normalized_key": row["normalized_key"] or "",
            }
        )

    result = []
    for row in rows:
        offer_id = int(row["id"])
        result.append(
            {
                "id": offer_id,
                "source_platform": row["source_platform"] or "",
                "source_url": row["source_url"] or "",
                "source_offer_ref": row["source_offer_ref"] or "",
                "offer_title": row["offer_title"] or "",
                "source_country_name": row["source_country_name"] or "",
                "source_region_name": row["source_region_name"] or "",
                "source_city_name": row["source_city_name"] or "",
                "source_location_text": row["source_location_text"] or "",
                "source_market_type": row["source_market_type"] or "",
                "price_value": row["price_value"],
                "price_currency": row["price_currency"] or "",
                "area_total_m2": row["area_total_m2"],
                "rooms_count": row["rooms_count"],
                "bedrooms_count": row["bedrooms_count"],
                "bathrooms_count": row["bathrooms_count"],
                "floor": row["floor"],
                "floor_override": row["floor_override"],
                "effective_floor": row["effective_floor"],
                "offer_description": row["offer_description"] or "",
                "property_type_source": row["property_type_source"] or "",
                "offer_type_normalized": row["offer_type_normalized"] or "",
                "market_type_normalized": row["market_type_normalized"] or "",
                "map_place": row["map_place"] or "",
                "map_accuracy": row["map_accuracy"] or "",
                "latitude": row["latitude"],
                "longitude": row["longitude"],
                "category_id_domiporta": row["category_id_domiporta"] or "",
                "is_export_ready": int(row["is_export_ready"] or 0),
                "is_active": int(row["is_active"] or 0),
                "needs_update": int(row["needs_update"] or 0),
                "last_source_sync_at": row["last_source_sync_at"] or "",
                "last_source_change_at": row["last_source_change_at"] or "",
                "created_at": row["created_at"] or "",
                "development_id": row["development_id"],
                "development_name": row["development_name"],
                "warning_count": int(row["warning_count"] or 0),
                "blocking_warning_count": int(row["blocking_warning_count"] or 0),
                "warnings": warnings_map.get(offer_id, []),
                "images": images_map.get(offer_id, []),
                "features": features_map.get(offer_id, []),
                "portal_sync": portal_map.get(offer_id, {}),
            }
        )
    total_pages = max(1, (total_count + per_page - 1) // per_page)
    return {
        "items": result,
        "pagination": {
            "page": page,
            "per_page": per_page,
            "total_count": total_count,
            "total_pages": total_pages,
        },
    }


def list_foreign_offers(limit: int = 200) -> list[dict]:
    return list_foreign_offers_page(per_page=limit)["items"]


def _serialize_development_row(row: sqlite3.Row) -> dict:
    return {
        "id": int(row["id"]),
        "name": row["name"],
        "created_at": row["created_at"] or "",
        "updated_at": row["updated_at"] or "",
    }


def _normalize_development_name(name) -> str:
    normalized = " ".join(str(name or "").split())
    if not normalized:
        raise ValueError("Nazwa inwestycji jest wymagana.")
    return normalized


def _fetch_development(conn: sqlite3.Connection, development_id: int) -> sqlite3.Row | None:
    return conn.execute(
        """
        SELECT id, name, created_at, updated_at
        FROM foreign_developments
        WHERE id = ?
        """,
        (int(development_id),),
    ).fetchone()


def list_foreign_developments() -> list[dict]:
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        rows = conn.execute(
            """
            SELECT id, name, created_at, updated_at
            FROM foreign_developments
            ORDER BY name COLLATE NOCASE ASC, id ASC
            """
        ).fetchall()
    return [_serialize_development_row(row) for row in rows]


def _normalize_source_identity_part(value, label: str) -> str:
    normalized = str(value).strip() if value is not None else ""
    if not normalized:
        raise ValueError(f"{label} is required.")
    return normalized


def create_foreign_development(name, source_platform=None, source_key=None) -> dict:
    """Raises sqlite3.IntegrityError when the name (case-insensitive) is taken.

    A source-owned development also passes source_platform and source_key
    (both or neither; manual developments pass neither). A duplicate
    (source_platform, source_key) raises sqlite3.IntegrityError too. Any
    normalization of source_key (e.g. slug casing) is the caller's job.
    """
    normalized_name = _normalize_development_name(name)
    if (source_platform is None) != (source_key is None):
        raise ValueError("source_platform and source_key must be given together.")
    identity = (None, None)
    if source_platform is not None:
        identity = (
            _normalize_source_identity_part(source_platform, "source_platform"),
            _normalize_source_identity_part(source_key, "source_key"),
        )
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        cursor = conn.execute(
            "INSERT INTO foreign_developments (name, source_platform, source_key) VALUES (?, ?, ?)",
            (normalized_name, *identity),
        )
        row = _fetch_development(conn, cursor.lastrowid)
        conn.commit()
    return _serialize_development_row(row)


def find_foreign_development_by_source(source_platform, source_key) -> dict | None:
    """The development a source identity maps to, or None (manual ones have none)."""
    platform = _normalize_source_identity_part(source_platform, "source_platform")
    key = _normalize_source_identity_part(source_key, "source_key")
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        row = conn.execute(
            """
            SELECT id, name, source_platform, source_key, created_at, updated_at
            FROM foreign_developments
            WHERE source_platform = ? AND source_key = ?
            """,
            (platform, key),
        ).fetchone()
    if row is None:
        return None
    return {
        "id": int(row["id"]),
        "name": row["name"],
        "source_platform": row["source_platform"],
        "source_key": row["source_key"],
        "created_at": row["created_at"] or "",
        "updated_at": row["updated_at"] or "",
    }


class AmbiguousSourceIdentityError(RuntimeError):
    """More than one foreign_offers row carries the same (source_platform, source_offer_ref)."""


def find_foreign_offer_by_source_identity(source_platform, source_offer_ref) -> dict | None:
    """The offer a source identity maps to, or None.

    Reads only the identity and sync metadata a synchronizer needs; it never
    writes. Raises AmbiguousSourceIdentityError instead of guessing when the
    identity is not unique (possible for providers exempt from the unique
    index, see _SOURCE_OFFER_REF_UNENFORCED_PLATFORMS).
    """
    platform = _normalize_source_identity_part(source_platform, "source_platform")
    ref = _normalize_source_identity_part(source_offer_ref, "source_offer_ref")
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        rows = conn.execute(
            """
            SELECT id, source_platform, source_offer_ref, source_url, development_id, is_active,
                   last_source_sync_at, last_sync_run_id, source_payload_hash
            FROM foreign_offers
            WHERE source_platform = ? AND source_offer_ref = ?
            ORDER BY id
            LIMIT 2
            """,
            (platform, ref),
        ).fetchall()
    if not rows:
        return None
    if len(rows) > 1:
        raise AmbiguousSourceIdentityError(
            f"More than one foreign offer has source identity ({platform}, {ref})."
        )
    row = rows[0]
    return {
        "id": int(row["id"]),
        "source_platform": row["source_platform"],
        "source_offer_ref": row["source_offer_ref"],
        "source_url": row["source_url"],
        "development_id": row["development_id"],
        "is_active": int(row["is_active"] or 0),
        "last_source_sync_at": row["last_source_sync_at"],
        "last_sync_run_id": row["last_sync_run_id"],
        "source_payload_hash": row["source_payload_hash"],
    }


def record_foreign_offer_seen(foreign_offer_id: int, sync_run_id: int, source_payload_hash: str) -> dict | None:
    """Marks an offer as present in the source during a sync run.

    Sets only last_source_sync_at ("last seen"), last_sync_run_id and
    source_payload_hash. It deliberately leaves is_active, needs_update,
    export/portal state and every CRM-owned or source-owned business field
    untouched: "seen" is not "active" and not "changed". Returns None for an
    unknown offer; an unknown run id raises sqlite3.IntegrityError.
    """
    payload_hash = _normalize_source_identity_part(source_payload_hash, "source_payload_hash")
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        cursor = conn.execute(
            """
            UPDATE foreign_offers
            SET last_source_sync_at = CURRENT_TIMESTAMP,
                last_sync_run_id = ?,
                source_payload_hash = ?
            WHERE id = ?
            """,
            (int(sync_run_id), payload_hash, int(foreign_offer_id)),
        )
        if cursor.rowcount == 0:
            return None
        row = conn.execute(
            """
            SELECT id, last_source_sync_at, last_sync_run_id, source_payload_hash
            FROM foreign_offers
            WHERE id = ?
            """,
            (int(foreign_offer_id),),
        ).fetchone()
        conn.commit()
    return {
        "foreign_offer_id": int(row["id"]),
        "last_source_sync_at": row["last_source_sync_at"],
        "last_sync_run_id": row["last_sync_run_id"],
        "source_payload_hash": row["source_payload_hash"],
    }


SYNC_RUN_STATUS_RUNNING = "running"
SYNC_RUN_STATUS_COMPLETED = "completed"
SYNC_RUN_STATUS_FAILED = "failed"
_SYNC_RUN_FINISH_STATUSES = (SYNC_RUN_STATUS_COMPLETED, SYNC_RUN_STATUS_FAILED)

_SYNC_RUN_COLUMNS = (
    "id, source_platform, status, started_at, finished_at, discovered_count, new_count, "
    "updated_count, unchanged_count, missing_count, error_count, error_message"
)


def _serialize_sync_run_row(row: sqlite3.Row) -> dict:
    return {
        "id": int(row["id"]),
        "source_platform": row["source_platform"],
        "status": row["status"],
        "started_at": row["started_at"],
        "finished_at": row["finished_at"],
        "discovered_count": int(row["discovered_count"]),
        "new_count": int(row["new_count"]),
        "updated_count": int(row["updated_count"]),
        "unchanged_count": int(row["unchanged_count"]),
        "missing_count": int(row["missing_count"]),
        "error_count": int(row["error_count"]),
        "error_message": row["error_message"],
    }


def create_foreign_sync_run(source_platform) -> dict:
    """Starts a run in the 'running' state. Deliberately no concurrency guard:
    what to do about a second or a stale 'running' run belongs to the runner."""
    platform = _normalize_source_identity_part(source_platform, "source_platform")
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        cursor = conn.execute(
            "INSERT INTO foreign_sync_runs (source_platform) VALUES (?)",
            (platform,),
        )
        row = conn.execute(
            f"SELECT {_SYNC_RUN_COLUMNS} FROM foreign_sync_runs WHERE id = ?",
            (cursor.lastrowid,),
        ).fetchone()
        conn.commit()
    return _serialize_sync_run_row(row)


def finish_foreign_sync_run(
    run_id: int,
    status: str,
    *,
    discovered_count: int = 0,
    new_count: int = 0,
    updated_count: int = 0,
    unchanged_count: int = 0,
    missing_count: int = 0,
    error_count: int = 0,
    error_message: str | None = None,
) -> dict | None:
    """Closes a running run as 'completed' or 'failed' and stores its counts.

    Returns None when the run does not exist or is no longer 'running' (a
    finished run is never rewritten). Raises ValueError for an invalid status
    or a negative/non-integer count.
    """
    if status not in _SYNC_RUN_FINISH_STATUSES:
        raise ValueError(f"status must be one of {_SYNC_RUN_FINISH_STATUSES}.")
    counts = {
        "discovered_count": discovered_count,
        "new_count": new_count,
        "updated_count": updated_count,
        "unchanged_count": unchanged_count,
        "missing_count": missing_count,
        "error_count": error_count,
    }
    for label, value in counts.items():
        if isinstance(value, bool) or not isinstance(value, int) or value < 0:
            raise ValueError(f"{label} must be a non-negative integer.")

    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        cursor = conn.execute(
            """
            UPDATE foreign_sync_runs
            SET status = ?,
                finished_at = CURRENT_TIMESTAMP,
                discovered_count = ?,
                new_count = ?,
                updated_count = ?,
                unchanged_count = ?,
                missing_count = ?,
                error_count = ?,
                error_message = ?
            WHERE id = ? AND status = 'running'
            """,
            (
                status,
                counts["discovered_count"],
                counts["new_count"],
                counts["updated_count"],
                counts["unchanged_count"],
                counts["missing_count"],
                counts["error_count"],
                error_message,
                int(run_id),
            ),
        )
        if cursor.rowcount == 0:
            return None
        row = conn.execute(
            f"SELECT {_SYNC_RUN_COLUMNS} FROM foreign_sync_runs WHERE id = ?",
            (int(run_id),),
        ).fetchone()
        conn.commit()
    return _serialize_sync_run_row(row)


def get_foreign_sync_run(run_id: int) -> dict | None:
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        row = conn.execute(
            f"SELECT {_SYNC_RUN_COLUMNS} FROM foreign_sync_runs WHERE id = ?",
            (int(run_id),),
        ).fetchone()
    return None if row is None else _serialize_sync_run_row(row)


def get_latest_foreign_sync_run(source_platform) -> dict | None:
    """Newest run of a source (by id, which is monotonic; timestamps can tie)."""
    platform = _normalize_source_identity_part(source_platform, "source_platform")
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        row = conn.execute(
            f"""
            SELECT {_SYNC_RUN_COLUMNS}
            FROM foreign_sync_runs
            WHERE source_platform = ?
            ORDER BY id DESC
            LIMIT 1
            """,
            (platform,),
        ).fetchone()
    return None if row is None else _serialize_sync_run_row(row)


def rename_foreign_development(development_id: int, name) -> dict | None:
    """Keeps the id stable. Raises sqlite3.IntegrityError when the name is taken.

    The name is exported (TabelaOfert nazwa_inwestycji), so an actual change flags
    every offer assigned to the development through the shared needs_update helper,
    in the same transaction as the rename (any failure rolls both back). Renaming to
    the name it already has propagates nothing. The validator is not involved: a
    rename changes neither warnings nor readiness.
    """
    normalized_name = _normalize_development_name(name)
    conn = open_foreign_offers_connection()
    try:
        _begin_write_transaction(conn)
        current = _fetch_development(conn, development_id)
        if current is None:
            conn.rollback()
            return None
        conn.execute(
            """
            UPDATE foreign_developments
            SET name = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
            """,
            (normalized_name, int(development_id)),
        )
        if current["name"] != normalized_name:
            for offer in conn.execute(
                "SELECT id FROM foreign_offers WHERE development_id = ? ORDER BY id", (int(development_id),)
            ).fetchall():
                mark_foreign_offer_requires_update(
                    conn, int(offer["id"]), "foreign_development_rename", ["development_name"]
                )
        row = _fetch_development(conn, development_id)
        conn.commit()
    except BaseException:
        conn.rollback()
        raise
    finally:
        conn.close()
    return _serialize_development_row(row)


def delete_foreign_development(development_id: int) -> bool:
    """Raises sqlite3.IntegrityError while any foreign offer still references it."""
    with open_foreign_offers_connection() as conn:
        ensure_foreign_offers_schema(conn)
        cursor = conn.execute(
            "DELETE FROM foreign_developments WHERE id = ?",
            (int(development_id),),
        )
        conn.commit()
    return cursor.rowcount > 0


def _begin_write_transaction(conn: sqlite3.Connection) -> None:
    ensure_foreign_offers_schema(conn)
    conn.commit()
    conn.execute("BEGIN IMMEDIATE")


def set_foreign_offer_development(foreign_offer_id: int, development_id: int | None) -> dict | None:
    """Assigns (or with None unassigns) a CRM-owned development.

    An actual change is written, the export warnings/readiness are recomputed
    and a published offer is flagged needs_update (shared helper), all in one
    transaction. Assigning what is already assigned changes nothing: no write,
    no needs_update, no event. Raises sqlite3.IntegrityError for an unknown
    development id (nothing is saved).
    """
    normalized_development_id = None if development_id is None else int(development_id)
    conn = open_foreign_offers_connection()
    try:
        _begin_write_transaction(conn)
        current = conn.execute(
            "SELECT development_id FROM foreign_offers WHERE id = ?", (int(foreign_offer_id),)
        ).fetchone()
        if current is None:
            conn.rollback()
            return None
        if current["development_id"] != normalized_development_id:
            conn.execute(
                "UPDATE foreign_offers SET development_id = ? WHERE id = ?",
                (normalized_development_id, int(foreign_offer_id)),
            )
            refresh_foreign_offer_export_state(conn, foreign_offer_id)
            mark_foreign_offer_requires_update(
                conn, foreign_offer_id, "foreign_offer_development_assignment", ["development_id"]
            )
        row = conn.execute(
            """
            SELECT fo.id, fo.development_id, fd.name AS development_name
            FROM foreign_offers fo
            LEFT JOIN foreign_developments fd ON fd.id = fo.development_id
            WHERE fo.id = ?
            """,
            (int(foreign_offer_id),),
        ).fetchone()
        conn.commit()
    except BaseException:
        conn.rollback()
        raise
    finally:
        conn.close()
    return {
        "foreign_offer_id": int(row["id"]),
        "development_id": row["development_id"],
        "development_name": row["development_name"],
    }


FOREIGN_OFFER_ACTIVITY_EVENTS = {0: "offer_withdrawn", 1: "offer_restored"}


def set_foreign_offer_active(foreign_offer_id: int, is_active: bool, user_id=None) -> dict | None:
    """Manual withdrawal (False) or restoration (True) of a foreign offer.

    Only the business field is_active changes, together with one audit event,
    in one transaction; the existing SQLite trigger also refreshes updated_at.
    Nothing is deleted, readiness and needs_update are untouched (restoring does
    not republish anything) and no portal is contacted: IDBManager lists an
    inactive offer that is still published as "to withdraw". Setting the current
    state again changes nothing and writes no event. None for an unknown offer.
    """
    target = 1 if is_active else 0
    conn = open_foreign_offers_connection()
    try:
        _begin_write_transaction(conn)
        current = conn.execute(
            "SELECT is_active FROM foreign_offers WHERE id = ?", (int(foreign_offer_id),)
        ).fetchone()
        if current is None:
            conn.rollback()
            return None
        changed = int(current["is_active"] or 0) != target
        if changed:
            conn.execute("UPDATE foreign_offers SET is_active = ? WHERE id = ?", (target, int(foreign_offer_id)))
            _insert_portal_event(
                conn, foreign_offer_id, None, FOREIGN_OFFER_ACTIVITY_EVENTS[target],
                {"reason": "manual", "user_id": user_id, "is_active": target},
            )
        published_portals = [
            str(row["portal_key"])
            for row in conn.execute(
                """
                SELECT portal_key FROM foreign_offer_portal_sync
                WHERE foreign_offer_id = ? AND is_published = 1
                ORDER BY portal_key
                """,
                (int(foreign_offer_id),),
            )
        ]
        conn.commit()
    except BaseException:
        conn.rollback()
        raise
    finally:
        conn.close()
    return {
        "foreign_offer_id": int(foreign_offer_id),
        "is_active": target,
        "changed": changed,
        "published_portals": published_portals,
    }


def set_foreign_offer_floor_override(foreign_offer_id: int, floor_override: int | None) -> dict | None:
    """Sets (or with None clears) the CRM-owned manual floor.

    An actual change of floor_override is written, the export warnings/readiness
    are recomputed and a published offer is flagged needs_update (shared helper),
    all in one transaction. Saving the value that is already stored changes
    nothing: no write, no needs_update, no event. The source-owned floor is never
    touched; the TripInvest importer never writes floor_override.
    """
    conn = open_foreign_offers_connection()
    try:
        _begin_write_transaction(conn)
        current = conn.execute(
            "SELECT floor_override FROM foreign_offers WHERE id = ?", (int(foreign_offer_id),)
        ).fetchone()
        if current is None:
            conn.rollback()
            return None
        if current["floor_override"] != floor_override:
            conn.execute(
                "UPDATE foreign_offers SET floor_override = ? WHERE id = ?",
                (floor_override, int(foreign_offer_id)),
            )
            refresh_foreign_offer_export_state(conn, foreign_offer_id)
            mark_foreign_offer_requires_update(
                conn, foreign_offer_id, "foreign_offer_floor_override", ["floor_override"]
            )
        row = conn.execute(
            """
            SELECT id, floor, floor_override, COALESCE(floor_override, floor) AS effective_floor
            FROM foreign_offers
            WHERE id = ?
            """,
            (int(foreign_offer_id),),
        ).fetchone()
        conn.commit()
    except BaseException:
        conn.rollback()
        raise
    finally:
        conn.close()
    return {
        "foreign_offer_id": int(row["id"]),
        "floor": row["floor"],
        "floor_override": row["floor_override"],
        "effective_floor": row["effective_floor"],
    }


# ---------------------------------------------------------------------------
# Manual completion of a foreign offer (SYNC-2C2)
# ---------------------------------------------------------------------------

# Essential first (what an export needs), then useful optional fields. All of
# them are sync-managed fields, so a manual value is written with the same
# normalization the merge uses (canonical_value) and stays comparable to the
# observed source value. floor_override and development_id have their own
# endpoints; identity and sync/system columns are not editable.
FOREIGN_OFFER_EDITABLE_FIELDS = (
    "price_value", "price_currency", "area_total_m2", "category_id_domiporta", "market_type_normalized",
    "source_country_name", "source_city_name",
    "offer_title", "offer_description", "source_region_name", "source_location_text", "latitude", "longitude",
    "rooms_count", "bedrooms_count", "bathrooms_count", "offer_type_normalized", "property_type_source",
    "source_country_code",
)
_EDITABLE_MARKET_TYPES = ("primary", "secondary")
_EDITABLE_OFFER_TYPES = ("sale", "rent")
_EDITABLE_CATEGORIES = ("191", "192", "193", "196")
_EDITABLE_COUNT_FIELDS = ("rooms_count", "bedrooms_count", "bathrooms_count")
_EDITABLE_TEXT_LIMIT = 20000
_FIELD_KIND_MESSAGES = {
    "text": "Wartość musi być tekstem.",
    "currency": "Waluta musi być trzyliterowym kodem (np. EUR).",
    "int": "Podaj liczbę całkowitą.",
    "amount": "Podaj liczbę nie mniejszą od zera.",
    "lat": "Szerokość geograficzna musi być liczbą od -90 do 90.",
    "lng": "Długość geograficzna musi być liczbą od -180 do 180.",
}


class ForeignOfferFieldErrors(ValueError):
    """One or more edited fields are invalid; `errors` maps field name -> message."""

    def __init__(self, errors: dict[str, str]):
        super().__init__("Nieprawidłowe dane oferty.")
        self.errors = errors


def _prepare_foreign_offer_changes(changes) -> dict:
    if not isinstance(changes, dict) or not changes:
        raise ForeignOfferFieldErrors({"fields": "Brak pól do zapisu."})
    prepared: dict = {}
    errors: dict[str, str] = {}
    for name, raw in changes.items():
        if name not in FOREIGN_OFFER_EDITABLE_FIELDS:
            errors[str(name)] = "Pole nie jest edytowalne."
            continue
        kind = SYNC_MANAGED_FIELDS[name]
        if name == "category_id_domiporta" and isinstance(raw, int) and not isinstance(raw, bool):
            raw = str(raw)
        try:
            value = canonical_value(name, raw)
        except SyncContractError:
            errors[name] = _FIELD_KIND_MESSAGES[kind]
            continue
        if value is not None:
            if kind == "text" and len(value) > _EDITABLE_TEXT_LIMIT:
                errors[name] = "Tekst jest za długi."
            elif name in _EDITABLE_COUNT_FIELDS and value < 0:
                errors[name] = "Podaj liczbę całkowitą nie mniejszą od zera."
            elif kind == "currency" and not (len(value) == 3 and value.isalpha() and value.isascii()):
                errors[name] = _FIELD_KIND_MESSAGES["currency"]
            elif name == "market_type_normalized" and value not in _EDITABLE_MARKET_TYPES:
                errors[name] = "Rynek musi mieć wartość: primary lub secondary."
            elif name == "offer_type_normalized" and value not in _EDITABLE_OFFER_TYPES:
                errors[name] = "Typ oferty musi mieć wartość: sale lub rent."
            elif name == "category_id_domiporta" and value not in _EDITABLE_CATEGORIES:
                errors[name] = f"Kategoria musi być jedną z: {', '.join(_EDITABLE_CATEGORIES)}."
        prepared[name] = value
    if errors:
        raise ForeignOfferFieldErrors(errors)
    return prepared


def update_foreign_offer_fields(foreign_offer_id: int, changes) -> dict | None:
    """Manual edit of the completion fields of one foreign offer, atomically.

    Writes ordinary columns only. It never touches source_values_json,
    source_payload_hash, last_source_sync_at, last_source_change_at or the
    source identity, so the next sync still sees current != previous source
    and keeps the manual value. A value equal to the current one is not a
    change: nothing is written and needs_update is not raised. When something
    did change, the validator recomputes the export warnings and readiness and
    the existing shared helper flags a published offer as needing an update.

    Returns None for an unknown offer; raises ForeignOfferFieldErrors for
    invalid input (before any write).
    """
    prepared = _prepare_foreign_offer_changes(changes)
    conn = open_foreign_offers_connection()
    try:
        ensure_foreign_offers_schema(conn)
        conn.commit()
        conn.execute("BEGIN IMMEDIATE")
        row = conn.execute(
            f"SELECT id, needs_update, {', '.join(prepared)} FROM foreign_offers WHERE id = ?",
            (int(foreign_offer_id),),
        ).fetchone()
        if row is None:
            conn.rollback()
            return None

        changed = [name for name, value in prepared.items() if canonical_current_value(name, row[name]) != value]
        if changed:
            assignments = ", ".join(f"{name} = ?" for name in changed)
            conn.execute(
                f"UPDATE foreign_offers SET {assignments} WHERE id = ?",
                (*(prepared[name] for name in changed), int(foreign_offer_id)),
            )
            state = refresh_foreign_offer_export_state(conn, foreign_offer_id)
            mark_foreign_offer_requires_update(conn, foreign_offer_id, "foreign_offer_manual_edit", changed)
        else:
            state = read_foreign_offer_export_state(conn, foreign_offer_id)
        needs_update = conn.execute(
            "SELECT needs_update FROM foreign_offers WHERE id = ?", (int(foreign_offer_id),)
        ).fetchone()[0]
        conn.commit()
    except BaseException:
        conn.rollback()
        raise
    finally:
        conn.close()
    return {
        "foreign_offer_id": int(foreign_offer_id),
        "changed_fields": changed,
        "values": dict(prepared),
        "is_export_ready": state["is_export_ready"],
        "warnings": state["warnings"],
        "needs_update": int(needs_update or 0),
    }
