﻿import hashlib
import json
import logging
import re
from typing import Any

from InvestmentManager.foreign_offers_store import (
    ensure_foreign_offer_sync_defaults,
    ensure_foreign_offers_schema,
    mark_foreign_offer_requires_update,
    open_foreign_offers_connection,
)
from InvestmentManager.foreign_sync import apply_plan, load_existing_offer
from InvestmentManager.foreign_sync_merge import (
    Observed,
    SyncContractError,
    SyncOffer,
    canonical_value,
    merge_offer,
    parse_observed,
)
from InvestmentManager.foreign_offer_validation import (
    VALIDATOR_WARNING_CODES,
    refresh_foreign_offer_export_state,
)
from integrations.tripinvest.connector import TripinvestConnector

_TRIPINVEST_DEVELOPMENT_SOURCE = "tripinvest"
_TRIPINVEST_SOURCE = "tripinvest"

logger = logging.getLogger(__name__)


def _json_dumps(payload: Any) -> str:
    return json.dumps(payload, ensure_ascii=False, sort_keys=True)


def _payload_hash(payload: Any) -> str:
    return hashlib.sha256(_json_dumps(payload).encode("utf-8")).hexdigest()


def _split_tripinvest_location(location_text: str | None) -> tuple[str, str]:
    text = str(location_text or "").strip()
    if not text:
        return "", ""
    parts = [part.strip() for part in text.split(",", 1)]
    if len(parts) == 1:
        return "", parts[0]
    return parts[0], parts[1]


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


def _canonical_tripinvest_development_title(title: str | None) -> str | None:
    canonical = re.sub(r"\s+", " ", str(title or "")).strip()
    return canonical or None


def _tripinvest_development_source_key(canonical_title: str) -> str:
    return f"title:{canonical_title}"


def _ensure_tripinvest_title_development(conn, title: str | None) -> int | None:
    """Find or create the source-owned TripInvest title development.

    Same-name manual/legacy developments are adopted by adding TripInvest
    source identity. Same-name developments already owned by another source are
    left untouched, so the offer remains unassigned instead of stealing them.
    """
    canonical_title = _canonical_tripinvest_development_title(title)
    if canonical_title is None:
        return None

    source_key = _tripinvest_development_source_key(canonical_title)
    row = conn.execute(
        """
        SELECT id
        FROM foreign_developments
        WHERE source_platform = ? AND source_key = ?
        """,
        (_TRIPINVEST_DEVELOPMENT_SOURCE, source_key),
    ).fetchone()
    if row is not None:
        return int(row["id"])

    clash = conn.execute(
        """
        SELECT id, source_platform, source_key
        FROM foreign_developments
        WHERE name = ? COLLATE NOCASE
        """,
        (canonical_title,),
    ).fetchone()
    if clash is not None:
        if clash["source_platform"] is None and clash["source_key"] is None:
            conn.execute(
                """
                UPDATE foreign_developments
                SET source_platform = ?,
                    source_key = ?,
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = ?
                """,
                (_TRIPINVEST_DEVELOPMENT_SOURCE, source_key, int(clash["id"])),
            )
            return int(clash["id"])
        return None

    cursor = conn.execute(
        """
        INSERT INTO foreign_developments (name, source_platform, source_key)
        VALUES (?, ?, ?)
        """,
        (canonical_title, _TRIPINVEST_DEVELOPMENT_SOURCE, source_key),
    )
    return int(cursor.lastrowid)


def _assign_tripinvest_title_development_if_missing(conn, foreign_offer_id: int, title: str | None) -> int | None:
    current = conn.execute(
        "SELECT development_id FROM foreign_offers WHERE id = ?",
        (int(foreign_offer_id),),
    ).fetchone()
    if current is None or current["development_id"] is not None:
        return None

    development_id = _ensure_tripinvest_title_development(conn, title)
    if development_id is None:
        return None

    conn.execute(
        "UPDATE foreign_offers SET development_id = ? WHERE id = ?",
        (development_id, int(foreign_offer_id)),
    )
    return development_id


def _infer_rooms_count(metrics: dict[str, Any] | None) -> int | None:
    metrics = metrics or {}

    rooms = metrics.get("rooms")
    if rooms not in (None, ""):
        try:
            return int(rooms)
        except (TypeError, ValueError):
            pass

    bedrooms = metrics.get("bedrooms")
    if bedrooms in (None, ""):
        return None
    try:
        return int(bedrooms) + 1
    except (TypeError, ValueError):
        return None


def _infer_category_id(
    title: str | None,
    property_type_source: str | None = None,
    features: list[str] | None = None,
    description: str | None = None,
) -> str:
    property_type_text = str(property_type_source or "").strip().lower()
    title_text = str(title or "").strip().lower()
    description_text = str(description or "").strip().lower()
    features_text = " ".join(str(feature or "").strip().lower() for feature in (features or []))

    apartment_tokens = ("apartament", "mieszkanie", "apartment", "penthouse", "studio", "duplex")
    house_tokens = ("dom", "willa", "villa", "house", "bungalow", "szeregowiec", "bliźniak", "blizniak")
    plot_tokens = ("działka", "dzialka", "grunt", "plot", "parcel")
    commercial_tokens = ("lokal", "commercial", "biznes", "office", "hotel", "retail", "shop", "restaur")

    def has_any(text: str, tokens: tuple[str, ...]) -> bool:
        return any(token in text for token in tokens)

    # Priorytet 1: jawny typ źródłowy
    if has_any(property_type_text, house_tokens):
        return "192"
    if has_any(property_type_text, apartment_tokens):
        return "191"
    if has_any(property_type_text, plot_tokens):
        return "193"
    if has_any(property_type_text, commercial_tokens):
        return "196"

    # Priorytet 2: tytuł oferty
    if has_any(title_text, house_tokens):
        return "192"
    if has_any(title_text, apartment_tokens):
        return "191"
    if has_any(title_text, plot_tokens):
        return "193"
    if has_any(title_text, commercial_tokens):
        return "196"

    # Priorytet 3: cechy
    if has_any(features_text, house_tokens):
        return "192"
    if has_any(features_text, apartment_tokens):
        return "191"
    if has_any(features_text, plot_tokens):
        return "193"
    if has_any(features_text, commercial_tokens):
        return "196"

    # Priorytet 4: opis jako najsłabszy sygnał
    if has_any(description_text, house_tokens):
        return "192"
    if has_any(description_text, apartment_tokens):
        return "191"
    if has_any(description_text, plot_tokens):
        return "193"
    if has_any(description_text, commercial_tokens):
        return "196"

    return ""


def _clean_images(images: list[str] | None) -> list[str]:
    cleaned: list[str] = []
    for image_url in images or []:
        url = str(image_url or "").strip()
        if not url or "placeholder.svg" in url.lower():
            continue
        if url not in cleaned:
            cleaned.append(url)
    return cleaned


def _extract_warning_rows(normalized_offer: dict, source_region_name: str) -> list[tuple[str, str, str, int]]:
    """TripInvest-specific advisory warnings only (import heuristics the validator cannot see).

    Missing images/city/category/price/area/... are judged from the final DB row by the
    shared validator (foreign_offer_validation), never here.
    """
    warnings: list[tuple[str, str, str, int]] = []
    metrics = normalized_offer.get("metrics") or {}
    raw_payload = ((normalized_offer.get("raw") or {}).get("payload") or {})

    if source_region_name:
        warnings.append((
            "location_region_from_marketing_area",
            "Region pochodzi z marketingowego pola location i wymaga dalszej weryfikacji.",
            "source_region_name",
            0,
        ))
    if metrics.get("bedrooms") and not metrics.get("rooms"):
        warnings.append((
            "rooms_count_inferred_from_bedrooms",
            "Liczba pokoi została wyliczona roboczo jako liczba sypialni + 1 i wymaga weryfikacji.",
            "rooms_count",
            0,
        ))
    if raw_payload.get("features"):
        warnings.append((
            "unmapped_features_present",
            "Oferta zawiera cechy źródłowe, które wymagają dalszego mapowania do Domiporta.",
            "features",
            0,
        ))
    return warnings


def _tripinvest_sync_offer(url: str, normalized_offer: dict) -> tuple[SyncOffer, dict[str, Any]]:
    """The managed fields, gallery and features of one TripInvest offer, as the merge sees them.

    Used for the incoming payload and, for legacy rows, to rebuild the last
    imported source values from the latest raw snapshot -- one derivation for
    both, so they compare like with like. A value that does not normalize is
    dropped (= no information) instead of failing the whole import.

    floor is deliberately not merged (FLOOR-1 contract): it is source-owned, a
    refresh may clear it, a floor-only change is not a source change, and the
    CRM value lives in floor_override. It is written directly with the metadata.
    """
    raw_payload = ((normalized_offer.get("raw") or {}).get("payload") or {})
    raw_map = raw_payload.get("map") or {}
    listing = normalized_offer.get("listing") or {}
    pricing = normalized_offer.get("pricing") or {}
    metrics = normalized_offer.get("metrics") or {}
    source = normalized_offer.get("source") or {}

    source_region_name, source_city_name = _split_tripinvest_location(
        (listing.get("location") or {}).get("address_label")
    )
    category_id = _infer_category_id(
        listing.get("title"),
        listing.get("property_type"),
        raw_payload.get("features") or [],
        listing.get("description_text"),
    )
    candidates = {
        "source_country_code": "ES",
        "source_country_name": "Spain",
        "source_region_name": source_region_name,
        "source_city_name": source_city_name,
        "source_location_text": (listing.get("location") or {}).get("address_label"),
        "offer_title": listing.get("title"),
        "offer_description": listing.get("description_text"),
        "price_value": pricing.get("amount"),
        "price_currency": pricing.get("currency"),
        "area_total_m2": metrics.get("area_m2"),
        "rooms_count": _infer_rooms_count(metrics),
        "bedrooms_count": metrics.get("bedrooms"),
        "bathrooms_count": metrics.get("bathrooms"),
        "latitude": raw_map.get("map_lat"),
        "longitude": raw_map.get("map_lng"),
        "property_type_source": listing.get("property_type"),
        "offer_type_normalized": listing.get("offer_type"),
        "market_type_normalized": _normalize_market_type(listing.get("market_type")),
        "category_id_domiporta": category_id,
    }
    fields: dict[str, Any] = {}
    for name, value in candidates.items():
        try:
            canonical_value(name, value)
        except SyncContractError:
            logger.warning("TripInvest %s: unusable %s value %r ignored.", url, name, value)
            continue
        fields[name] = value

    features = [str(item).strip() for item in raw_payload.get("features") or [] if item is not None]
    sync_offer = SyncOffer(
        _TRIPINVEST_SOURCE,
        # Required by SyncOffer; the column keeps the raw external id (written below).
        str(source.get("external_id") or url),
        url,
        fields=fields,
        images=_clean_images((normalized_offer.get("media") or {}).get("gallery") or []),
        features=features,
    )
    derived = {
        "source_offer_ref": source.get("external_id"),
        "source_market_type": listing.get("market_type"),
        "map_place": raw_map.get("map_place"),
        "map_accuracy": raw_map.get("map_accuracy"),
        "floor": metrics.get("floor"),
        "title": listing.get("title"),
        "category_id_domiporta": category_id,
        "source_region_name": source_region_name,
        "source_city_name": source_city_name,
    }
    return sync_offer, derived


def _legacy_observed(conn, connector, foreign_offer_id: int, url: str) -> Observed | None:
    """Last imported source values of an offer written before source_values_json existed.

    The old importer overwrote every source field on each import, so the latest
    raw snapshot re-derived with _tripinvest_sync_offer is what the columns held
    after that import: a current value that differs from it was edited in the
    CRM afterwards. None when there is no usable snapshot (the merge then
    treats every differing value as unknown provenance and keeps it).
    """
    snapshot = conn.execute(
        """
        SELECT payload_json
        FROM foreign_offer_raw_snapshots
        WHERE foreign_offer_id = ?
        ORDER BY id DESC
        LIMIT 1
        """,
        (int(foreign_offer_id),),
    ).fetchone()
    if snapshot is None:
        return None
    try:
        payload = json.loads(snapshot["payload_json"])
        normalized = connector.normalize_offer({"kind": "offer_details", "offer": payload, "url": url})
        baseline, _derived = _tripinvest_sync_offer(url, normalized)
    except Exception as exc:
        logger.warning("TripInvest offer %s: unusable raw snapshot (%s); merging conservatively.", foreign_offer_id, exc)
        return None
    return Observed(fields=baseline.fields, images=baseline.images, features=baseline.features)


def _ensure_offer_content(normalized_offer: dict, url: str) -> None:
    """Rejects an HTTP 200 page that is not a TripInvest offer (INV-LC-7).

    The parser never fails on an unexpected page (an empty body, an error page,
    a listing): it returns None everywhere and the connector fills the title
    with "Nieruchomość" and the market with "unknown". A page counts as an offer
    only with its own heading (the raw parsed title, not the connector default)
    and at least one value from the offer data box: price, area, bedrooms or
    bathrooms. Images are not evidence: the parser also collects generic CMS
    images. Partial offers (e.g. no price) still pass.
    """
    raw_payload = ((normalized_offer.get("raw") or {}).get("payload") or {})
    title = str(raw_payload.get("title") or "").strip()
    pricing = normalized_offer.get("pricing") or {}
    metrics = normalized_offer.get("metrics") or {}
    offer_box_values = (pricing.get("amount"), metrics.get("area_m2"), metrics.get("bedrooms"), metrics.get("bathrooms"))
    if not title or all(value is None for value in offer_box_values):
        raise ValueError(
            f"Strona TripInvest {url} nie zawiera treści oferty (brak tytułu lub danych oferty); nic nie zostało zmienione."
        )


def upsert_foreign_offer_from_tripinvest(url: str) -> dict[str, Any]:
    """Import (create) or refresh one TripInvest offer through the generic three-way merge.

    Sync-managed fields follow foreign_sync_merge: a value edited in the CRM is
    preserved, an untouched one follows the source, and the source values are
    recorded in source_values_json as the reference for the next refresh. Only
    a real change of exported data marks a published offer for re-export.
    """
    url = str(url).strip()
    connector = TripinvestConnector()
    raw_offer = connector.fetch_offer({"url": url})
    if not raw_offer:
        raise ValueError("Nie udało się pobrać oferty Tripinvest.")

    normalized_offer = connector.normalize_offer(raw_offer)
    _ensure_offer_content(normalized_offer, url)  # before any write: a bad page changes nothing
    raw_payload = ((normalized_offer.get("raw") or {}).get("payload") or {})
    payload_hash = _payload_hash(raw_payload)
    sync_offer, derived = _tripinvest_sync_offer(url, normalized_offer)
    warning_rows = _extract_warning_rows(normalized_offer, derived["source_region_name"])

    conn = open_foreign_offers_connection()
    try:
        ensure_foreign_offers_schema(conn)
        conn.commit()
        conn.execute("BEGIN IMMEDIATE")

        row = conn.execute(
            "SELECT * FROM foreign_offers WHERE source_platform = ? AND source_url = ?",
            (_TRIPINVEST_SOURCE, url),
        ).fetchone()
        existing = None
        observed = Observed()
        if row is not None:
            existing = load_existing_offer(conn, row)
            observed = parse_observed(row["source_values_json"])
            if observed == Observed():  # no history (NULL, "" or "{}"), not corrupt: a legacy row
                observed = _legacy_observed(conn, connector, int(row["id"]), url) or observed

        plan = merge_offer(existing, observed, sync_offer)
        # Writes managed fields, gallery/features, source_values_json, hash, sync log,
        # readiness on a business change, and needs_update for published offers.
        foreign_offer_id = apply_plan(conn, plan, sync_offer, row, None)

        # Source-owned values outside the merge (not CRM-editable): always the source's.
        conn.execute(
            """
            UPDATE foreign_offers
            SET source_offer_ref = ?, source_market_type = ?, map_place = ?, map_accuracy = ?, floor = ?,
                last_sync_run_id = ?
            WHERE id = ?
            """,
            (
                derived["source_offer_ref"],
                derived["source_market_type"],
                derived["map_place"],
                derived["map_accuracy"],
                derived["floor"],
                # A manual import is not part of a sync run: keep the run that last saw the offer.
                row["last_sync_run_id"] if row is not None else None,
                foreign_offer_id,
            ),
        )
        ensure_foreign_offer_sync_defaults(conn, foreign_offer_id)
        assigned_development_id = _assign_tripinvest_title_development_if_missing(
            conn, foreign_offer_id, derived["title"]
        )
        development_newly_assigned = row is not None and assigned_development_id is not None
        if development_newly_assigned and plan.action != "updated":
            # id_inwestycji is exported: a new assignment is a real change.
            mark_foreign_offer_requires_update(conn, foreign_offer_id, "foreign_offer_source_changed", ["development_id"])

        conn.execute(
            """
            INSERT INTO foreign_offer_raw_snapshots (foreign_offer_id, payload_json, payload_hash)
            VALUES (?, ?, ?)
            """,
            (foreign_offer_id, _json_dumps(raw_payload), payload_hash),
        )

        # Only the importer's own rows are rebuilt; the validator owns the rest.
        conn.execute(
            f"""
            DELETE FROM foreign_offer_export_warnings
            WHERE foreign_offer_id = ?
              AND warning_code NOT IN ({", ".join("?" for _ in VALIDATOR_WARNING_CODES)})
            """,
            (foreign_offer_id, *VALIDATOR_WARNING_CODES),
        )
        for warning_code, warning_message, field_name, is_blocking in warning_rows:
            conn.execute(
                """
                INSERT INTO foreign_offer_export_warnings (
                    foreign_offer_id, warning_code, warning_message, field_name, is_blocking
                )
                VALUES (?, ?, ?, ?, ?)
                """,
                (foreign_offer_id, warning_code, warning_message, field_name, int(is_blocking)),
            )

        # The final row (merged values, gallery, development) is judged in this transaction.
        export_state = refresh_foreign_offer_export_state(conn, foreign_offer_id)
        conn.commit()
    except BaseException:
        conn.rollback()
        raise
    finally:
        conn.close()

    return {
        "foreign_offer_id": foreign_offer_id,
        "source_platform": _TRIPINVEST_SOURCE,
        "source_url": url,
        "change_detected": plan.action == "updated" or development_newly_assigned,
        "is_export_ready": export_state["is_export_ready"],
        "warning_count": len(export_state["warnings"]),
        "images_count": len(sync_offer.images or ()),
        "category_id_domiporta": derived["category_id_domiporta"],
        "source_region_name": derived["source_region_name"],
        "source_city_name": derived["source_city_name"],
    }
