"""Source-independent export requirements for foreign offers (SYNC-2C2).

Works only on the final state of a foreign offer in the database: no raw source
payload, and nothing that knows TripInvest, Avarten or Cyprus. It is what makes
"complete the offer in the CRM, then export" work: values a source could not
provide are filled by a user (or a later sync), and the offer becomes ready
once nothing blocks it.

Readiness: is_export_ready = 1 when no unresolved blocking warning exists in
foreign_offer_export_warnings, otherwise 0. (The exporters refuse an offer with
a blocking warning; is_export_ready itself is informational there.)

Ownership: the validator manages only VALIDATOR_WARNING_CODES. Every other
warning row (the TripInvest importer's own advisory rows) is left alone, but
counts towards readiness. Codes that TripInvest also emits (missing_images,
missing_city_name, missing_category_id_domiporta) are managed here as one row
per code: a legacy row with such a code is replaced, since it describes the
same condition.

What blocks follows shared data completeness plus currencies accepted natively
by at least one foreign export channel. Portal-specific exclusions still live
in the exporters themselves (for example TabelaOfert primary-only, or a
currency accepted by TabelaOfert but not Domiporta).
"""
from __future__ import annotations

import sqlite3
from dataclasses import dataclass
from typing import Any, Mapping

# Currencies accepted natively by at least one foreign export channel. Keep
# portal-specific currency guards in idbmanager exporters.
SUPPORTED_EXPORT_CURRENCIES = ("AED", "CHF", "EUR", "GBP", "PLN", "SEK", "THB", "USD")

# What the exporters accept for the market (idbmanager _strict_market_type).
_PRIMARY_MARKETS = ("primary", "pierwotny")
_SECONDARY_MARKETS = ("secondary", "wtorny", "wtórny")

_APARTMENT_CATEGORY = "191"

BLOCKING_WARNING_CODES = (
    "missing_images",
    "missing_category_id_domiporta",
    "missing_market_type",
    "missing_city_name",
    "missing_price",
    "missing_area",
    "missing_country_name",
    "unsupported_currency",
)
ADVISORY_WARNING_CODES = (
    "missing_development",
    "missing_floor",
    "missing_rooms",
)
VALIDATOR_WARNING_CODES = BLOCKING_WARNING_CODES + ADVISORY_WARNING_CODES

# Warnings the sync layer derives from what the source reports about an offer
# (not from the row), set and cleared with set_source_warning. Blocking ones
# make the offer not export-ready like any other blocking warning; they never
# change is_active and never affect a withdrawal.
SOURCE_SOLD_OUT = "source_sold_out"
SOURCE_AVAILABILITY_UNCLEAR = "source_availability_unclear"
SOURCE_MISSING = "source_missing"
SOURCE_WARNING_CODES = (SOURCE_SOLD_OUT, SOURCE_AVAILABILITY_UNCLEAR, SOURCE_MISSING)

# Columns evaluate_export_requirements reads.
VALIDATION_COLUMNS = (
    "price_value", "price_currency", "area_total_m2", "source_country_name", "source_city_name",
    "market_type_normalized", "category_id_domiporta", "development_id", "floor", "floor_override",
    "rooms_count",
)


@dataclass(frozen=True)
class ExportWarning:
    code: str
    message: str
    field_name: str
    is_blocking: bool


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


def _positive_number(value: Any) -> bool:
    if value is None or isinstance(value, bool):
        return False
    try:
        return float(value) > 0
    except (TypeError, ValueError):
        return False


def _market(value: Any) -> str | None:
    text = _text(value).lower()
    if text in _PRIMARY_MARKETS:
        return "primary"
    if text in _SECONDARY_MARKETS:
        return "secondary"
    return None


def effective_floor(row: Mapping[str, Any]) -> Any:
    """floor_override when set, else floor (0 and negative floors are valid)."""
    override = row.get("floor_override")
    return override if override is not None else row.get("floor")


def evaluate_export_requirements(row: Mapping[str, Any], image_count: int) -> list[ExportWarning]:
    """Warnings for the final state of one offer (pure; `row` maps VALIDATION_COLUMNS)."""
    warnings: list[ExportWarning] = []

    def add(code: str, message: str, field_name: str, blocking: bool) -> None:
        warnings.append(ExportWarning(code, message, field_name, blocking))

    if image_count < 1:
        add("missing_images", "Oferta nie ma żadnych zdjęć. Eksport wymaga co najmniej jednego.", "images", True)
    if not _text(row.get("category_id_domiporta")):
        add("missing_category_id_domiporta", "Brak kategorii Domiporta. Eksport do Domiporta jej wymaga.",
            "category_id_domiporta", True)
    market = _market(row.get("market_type_normalized"))
    if market is None:
        add("missing_market_type", "Brak rynku oferty (pierwotny lub wtórny). Eksport do TabelaOfert go wymaga.",
            "market_type_normalized", True)
    if not _text(row.get("source_city_name")):
        add("missing_city_name", "Brak miasta oferty.", "source_city_name", True)
    if not _positive_number(row.get("price_value")):
        add("missing_price", "Brak ceny (musi być większa od zera). Eksport podstawiłby cenę 0.", "price_value", True)
    if not _positive_number(row.get("area_total_m2")):
        add("missing_area", "Brak powierzchni (musi być większa od zera). Eksport podstawiłby powierzchnię 0.",
            "area_total_m2", True)
    if not _text(row.get("source_country_name")):
        add("missing_country_name", "Brak kraju. Eksport podstawiłby Hiszpanię.", "source_country_name", True)

    currency = _text(row.get("price_currency")).upper()
    if currency not in SUPPORTED_EXPORT_CURRENCIES:
        shown = currency or "brak"
        add(
            "unsupported_currency",
            f"Waluta ({shown}) nie jest bezpiecznie obsługiwana przez eksport. "
            f"Obsługiwane: {', '.join(SUPPORTED_EXPORT_CURRENCIES)}.",
            "price_currency",
            True,
        )

    category = _text(row.get("category_id_domiporta"))
    if market == "primary" and row.get("development_id") is None:
        add("missing_development",
            "Oferta z rynku pierwotnego nie ma przypisanej inwestycji. Będzie ona wymagana do eksportu TabelaOfert.",
            "development_id", False)
    if market == "primary" and category == _APARTMENT_CATEGORY and effective_floor(row) is None:
        add("missing_floor",
            "Mieszkanie z rynku pierwotnego nie ma ustalonego piętra. Będzie ono wymagane do eksportu TabelaOfert.",
            "floor_override", False)
    if category == _APARTMENT_CATEGORY and row.get("rooms_count") is None:
        add("missing_rooms", "Mieszkanie nie ma liczby pokoi.", "rooms_count", False)
    return warnings


def refresh_foreign_offer_export_state(conn: sqlite3.Connection, offer_id: int) -> dict | None:
    """Recomputes the validator's warnings and is_export_ready for one offer.

    Runs on the caller's connection and inside the caller's transaction (it does
    not commit). Returns {"is_export_ready", "warnings"} (all unresolved
    warnings, including legacy ones) or None for an unknown offer.
    """
    offer_id = int(offer_id)
    row = conn.execute(
        f"SELECT {', '.join(VALIDATION_COLUMNS)} FROM foreign_offers WHERE id = ?", (offer_id,)
    ).fetchone()
    if row is None:
        return None
    image_count = conn.execute(
        "SELECT COUNT(*) FROM foreign_offer_images WHERE foreign_offer_id = ?", (offer_id,)
    ).fetchone()[0]
    desired = {w.code: w for w in evaluate_export_requirements({c: row[c] for c in VALIDATION_COLUMNS}, image_count)}

    marks = ", ".join("?" for _ in VALIDATOR_WARNING_CODES)
    existing: dict[str, list] = {}
    for item in conn.execute(
        f"""
        SELECT id, warning_code, warning_message, field_name, is_blocking
        FROM foreign_offer_export_warnings
        WHERE foreign_offer_id = ? AND warning_code IN ({marks})
        ORDER BY id
        """,
        (offer_id, *VALIDATOR_WARNING_CODES),
    ):
        existing.setdefault(item["warning_code"], []).append(item)

    for code, rows in existing.items():
        keep = rows[0] if code in desired else None
        for extra in rows:
            if extra is not keep:
                conn.execute("DELETE FROM foreign_offer_export_warnings WHERE id = ?", (extra["id"],))
        if keep is not None:
            want = desired[code]
            if (keep["warning_message"], keep["field_name"], int(keep["is_blocking"])) != (
                want.message, want.field_name, int(want.is_blocking)
            ):
                conn.execute(
                    """
                    UPDATE foreign_offer_export_warnings
                    SET warning_message = ?, field_name = ?, is_blocking = ?, resolved_at = NULL
                    WHERE id = ?
                    """,
                    (want.message, want.field_name, int(want.is_blocking), keep["id"]),
                )
            else:
                conn.execute(
                    "UPDATE foreign_offer_export_warnings SET resolved_at = NULL WHERE id = ? AND resolved_at IS NOT NULL",
                    (keep["id"],),
                )
    for code, want in desired.items():
        if code not in existing:
            conn.execute(
                """
                INSERT INTO foreign_offer_export_warnings (
                    foreign_offer_id, warning_code, warning_message, field_name, is_blocking
                )
                VALUES (?, ?, ?, ?, ?)
                """,
                (offer_id, want.code, want.message, want.field_name, int(want.is_blocking)),
            )

    warnings = _unresolved_warnings(conn, offer_id)
    is_ready = 0 if any(item["is_blocking"] for item in warnings) else 1
    conn.execute(
        "UPDATE foreign_offers SET is_export_ready = ? WHERE id = ? AND is_export_ready IS NOT ?",
        (is_ready, offer_id, is_ready),
    )
    return {"is_export_ready": bool(is_ready), "warnings": warnings}


def set_source_warning(conn: sqlite3.Connection, offer_id: int, code: str, message: str | None, *, blocking: bool) -> bool:
    """Keeps exactly one row of a source warning (message given) or none (None).

    Runs in the caller's transaction. Returns True when something changed; the
    caller then recomputes readiness with refresh_foreign_offer_export_state.
    """
    rows = conn.execute(
        "SELECT id, warning_message, is_blocking, resolved_at FROM foreign_offer_export_warnings"
        " WHERE foreign_offer_id = ? AND warning_code = ? ORDER BY id",
        (int(offer_id), code),
    ).fetchall()
    if message is None:
        for row in rows:
            conn.execute("DELETE FROM foreign_offer_export_warnings WHERE id = ?", (row["id"],))
        return bool(rows)
    changed = False
    for extra in rows[1:]:
        conn.execute("DELETE FROM foreign_offer_export_warnings WHERE id = ?", (extra["id"],))
        changed = True
    if not rows:
        conn.execute(
            """
            INSERT INTO foreign_offer_export_warnings (
                foreign_offer_id, warning_code, warning_message, field_name, is_blocking
            )
            VALUES (?, ?, ?, 'source', ?)
            """,
            (int(offer_id), code, message, int(blocking)),
        )
        return True
    keep = rows[0]
    if (keep["warning_message"], int(keep["is_blocking"]), keep["resolved_at"]) != (message, int(blocking), None):
        conn.execute(
            "UPDATE foreign_offer_export_warnings SET warning_message = ?, is_blocking = ?, resolved_at = NULL WHERE id = ?",
            (message, int(blocking), keep["id"]),
        )
        changed = True
    return changed


def _unresolved_warnings(conn: sqlite3.Connection, offer_id: int) -> list[dict]:
    return [
        {
            "warning_code": item["warning_code"] or "",
            "warning_message": item["warning_message"] or "",
            "field_name": item["field_name"] or "",
            "is_blocking": int(item["is_blocking"] or 0),
        }
        for item in conn.execute(
            """
            SELECT warning_code, warning_message, field_name, is_blocking
            FROM foreign_offer_export_warnings
            WHERE foreign_offer_id = ? AND resolved_at IS NULL
            ORDER BY is_blocking DESC, created_at ASC, id ASC
            """,
            (int(offer_id),),
        )
    ]


def read_foreign_offer_export_state(conn: sqlite3.Connection, offer_id: int) -> dict | None:
    """The stored readiness and unresolved warnings, without recomputing anything."""
    row = conn.execute("SELECT is_export_ready FROM foreign_offers WHERE id = ?", (int(offer_id),)).fetchone()
    if row is None:
        return None
    return {"is_export_ready": bool(row["is_export_ready"]), "warnings": _unresolved_warnings(conn, offer_id)}
