"""Generic foreign source synchronization service (SYNC-2B).

Receives already-normalized SyncDevelopment / SyncOffer objects (no scraping,
no network and nothing source-specific here), resolves identities, merges each
offer with the pure three-way merge in foreign_sync_merge, and applies the
plan. Each development and each offer is written in its own short
BEGIN IMMEDIATE transaction (read + merge + write are atomic, and a failing
record rolls back only itself). Nothing here deactivates or removes offers:
"seen" is recorded and is_active is never touched; offers absent from complete
runs are only flagged (flag_missing_offers, called by the runners).

Export readiness is judged by the source-independent validator
(foreign_offer_validation), called after a create or a business change in the
same transaction. Merge semantics do not depend on it.
"""
from __future__ import annotations

import json
import logging
import sqlite3
from dataclasses import dataclass, field
from typing import Iterable

from InvestmentManager.foreign_offer_validation import (
    SOURCE_AVAILABILITY_UNCLEAR,
    SOURCE_MISSING,
    SOURCE_SOLD_OUT,
    refresh_foreign_offer_export_state,
    set_source_warning,
)
from InvestmentManager.foreign_offers_store import (
    AmbiguousSourceIdentityError,
    SYNC_RUN_STATUS_COMPLETED,
    SYNC_RUN_STATUS_RUNNING,
    ensure_foreign_offer_sync_defaults,
    ensure_foreign_offers_schema,
    finish_foreign_sync_run,
    get_foreign_sync_run,
    mark_foreign_offer_requires_update,
    open_foreign_offers_connection,
)
from InvestmentManager.foreign_sync_merge import (
    DEV_STATUS_CREATED,
    DEV_STATUS_EXISTING,
    DEV_STATUS_NAME_CONFLICT,
    DEV_STATUS_UNRESOLVED,
    DEV_STATUS_WOULD_CREATE,
    SYNC_MANAGED_FIELDS,
    DevelopmentResolution,
    ExistingOffer,
    MergePlan,
    Observed,
    SyncContractError,
    SyncDevelopment,
    SyncOffer,
    merge_offer,
    parse_observed,
    source_payload_hash,
)

logger = logging.getLogger(__name__)

_SUMMARY_VALUE_LIMIT = 80
_RUN_ERROR_MESSAGE_LIMIT = 500


# ---------------------------------------------------------------------------
# Report
# ---------------------------------------------------------------------------


@dataclass
class DevelopmentOutcome:
    source_key: str
    # existing | created | would_create | name_conflict | error
    status: str
    development_id: int | None = None
    name: str | None = None
    conflict_with: dict | None = None
    error: str | None = None


@dataclass
class OfferOutcome:
    source_offer_ref: str
    # created | updated | unchanged | error
    action: str
    foreign_offer_id: int | None = None
    plan: MergePlan | None = None
    error: str | None = None


@dataclass
class SyncReport:
    source_platform: str
    run_id: int | None
    dry_run: bool
    discovered_count: int = 0
    new_count: int = 0
    updated_count: int = 0
    unchanged_count: int = 0
    missing_count: int = 0  # set by the runner from flag_missing_offers, never by sync_records
    error_count: int = 0
    developments: list[DevelopmentOutcome] = field(default_factory=list)
    offers: list[OfferOutcome] = field(default_factory=list)

    @property
    def development_conflicts(self) -> list[DevelopmentOutcome]:
        return [d for d in self.developments if d.status == DEV_STATUS_NAME_CONFLICT]

    @property
    def errors(self) -> list[str]:
        return [f"{o.source_offer_ref}: {o.error}" for o in self.offers if o.action == "error"] + [
            f"development {d.source_key}: {d.error}" for d in self.developments if d.status == "error"
        ]

    def run_counts(self) -> dict:
        return {
            "discovered_count": self.discovered_count,
            "new_count": self.new_count,
            "updated_count": self.updated_count,
            "unchanged_count": self.unchanged_count,
            "missing_count": self.missing_count,
            "error_count": self.error_count,
        }


# ---------------------------------------------------------------------------
# Development
# ---------------------------------------------------------------------------


def ensure_development(conn: sqlite3.Connection, development: SyncDevelopment, *, dry_run: bool = False) -> DevelopmentOutcome:
    """Finds the development by source identity, or creates it.

    The name is only used when creating. An existing development keeps its
    (CRM-owned) name. A name held by another development (foreign_developments.name
    is UNIQUE NOCASE) is a conflict: nothing is created, adopted or renamed.
    """
    if not dry_run:
        conn.execute("BEGIN IMMEDIATE")
    try:
        row = conn.execute(
            "SELECT id, name FROM foreign_developments WHERE source_platform = ? AND source_key = ?",
            (development.source_platform, development.source_key),
        ).fetchone()
        if row is not None:
            if not dry_run:
                conn.rollback()
            return DevelopmentOutcome(development.source_key, DEV_STATUS_EXISTING, int(row["id"]), row["name"])

        clash = conn.execute(
            """
            SELECT id, name, source_platform, source_key
            FROM foreign_developments
            WHERE name = ? COLLATE NOCASE
            """,
            (development.name,),
        ).fetchone()
        if clash is not None:
            if not dry_run:
                conn.rollback()
            return DevelopmentOutcome(
                development.source_key,
                DEV_STATUS_NAME_CONFLICT,
                None,
                development.name,
                conflict_with={
                    "id": int(clash["id"]),
                    "name": clash["name"],
                    "source_platform": clash["source_platform"],
                    "source_key": clash["source_key"],
                },
            )

        if dry_run:
            return DevelopmentOutcome(development.source_key, DEV_STATUS_WOULD_CREATE, None, development.name)

        cursor = conn.execute(
            "INSERT INTO foreign_developments (name, source_platform, source_key) VALUES (?, ?, ?)",
            (development.name, development.source_platform, development.source_key),
        )
        conn.commit()
        return DevelopmentOutcome(development.source_key, DEV_STATUS_CREATED, int(cursor.lastrowid), development.name)
    except Exception as exc:
        if not dry_run:
            conn.rollback()
        logger.warning("Development %s failed: %s", development.source_key, exc)
        return DevelopmentOutcome(development.source_key, "error", None, development.name, error=str(exc))


def _resolution_for(conn, offer: SyncOffer, outcomes: dict[str, DevelopmentOutcome]) -> DevelopmentResolution | None:
    if offer.development is None:
        return None
    outcome = outcomes.get(offer.development.source_key)
    if outcome is None:
        row = conn.execute(
            "SELECT id FROM foreign_developments WHERE source_platform = ? AND source_key = ?",
            (offer.development.source_platform, offer.development.source_key),
        ).fetchone()
        if row is None:
            return DevelopmentResolution(DEV_STATUS_UNRESOLVED)
        return DevelopmentResolution(DEV_STATUS_EXISTING, int(row["id"]))
    if outcome.status in (DEV_STATUS_EXISTING, DEV_STATUS_CREATED, DEV_STATUS_WOULD_CREATE, DEV_STATUS_NAME_CONFLICT):
        return DevelopmentResolution(outcome.status, outcome.development_id)
    return DevelopmentResolution(DEV_STATUS_UNRESOLVED)


# ---------------------------------------------------------------------------
# Offer
# ---------------------------------------------------------------------------


def _load_existing(conn, offer: SyncOffer):
    rows = conn.execute(
        """
        SELECT * FROM foreign_offers
        WHERE source_platform = ? AND source_offer_ref = ?
        ORDER BY id
        LIMIT 2
        """,
        (offer.source_platform, offer.source_offer_ref),
    ).fetchall()
    if not rows:
        return None, None
    if len(rows) > 1:
        raise AmbiguousSourceIdentityError(
            f"More than one foreign offer has source identity ({offer.source_platform}, {offer.source_offer_ref})."
        )
    row = rows[0]
    return row, load_existing_offer(conn, row)


def load_existing_offer(conn, row) -> ExistingOffer:
    """The merge input for a foreign_offers row (however the caller found it)."""
    offer_id = int(row["id"])
    images = tuple(
        item["image_url"]
        for item in conn.execute(
            "SELECT image_url FROM foreign_offer_images WHERE foreign_offer_id = ? ORDER BY sort_order, id",
            (offer_id,),
        )
    )
    features = tuple(
        item["feature_text"]
        for item in conn.execute(
            "SELECT feature_text FROM foreign_offer_features_raw WHERE foreign_offer_id = ? ORDER BY id",
            (offer_id,),
        )
    )
    return ExistingOffer(
        fields={name: row[name] for name in SYNC_MANAGED_FIELDS},
        images=images,
        features=features,
        development_id=row["development_id"],
    )


def _short(value) -> str:
    text = str(value)
    return text if len(text) <= _SUMMARY_VALUE_LIMIT else text[: _SUMMARY_VALUE_LIMIT - 1] + "…"


def _log_summary(plan: MergePlan) -> str:
    return json.dumps(
        {
            "action": plan.action,
            "applied": list(plan.applied_fields),
            "preserved": [
                {"field": p.field, "reason": p.reason, "current": _short(p.current), "incoming": _short(p.incoming)}
                for p in plan.preserved
            ],
            "images": plan.images.action,
            "features": plan.features.action,
            "development": plan.development.action,
            "observed_corrupt": plan.observed_corrupt,
        },
        ensure_ascii=False,
        sort_keys=True,
    )


def _replace_gallery(conn, offer_id: int, urls: tuple[str, ...]) -> None:
    conn.execute("DELETE FROM foreign_offer_images WHERE foreign_offer_id = ?", (offer_id,))
    for sort_order, url in enumerate(urls):
        conn.execute(
            "INSERT INTO foreign_offer_images (foreign_offer_id, image_url, sort_order, is_primary) VALUES (?, ?, ?, ?)",
            (offer_id, url, sort_order, 1 if sort_order == 0 else 0),
        )


def _replace_features(conn, offer_id: int, features: tuple[str, ...]) -> None:
    conn.execute("DELETE FROM foreign_offer_features_raw WHERE foreign_offer_id = ?", (offer_id,))
    for text in features:
        conn.execute(
            "INSERT INTO foreign_offer_features_raw (foreign_offer_id, feature_text, normalized_key) VALUES (?, ?, NULL)",
            (offer_id, text),
        )


def apply_plan(conn: sqlite3.Connection, plan: MergePlan, offer: SyncOffer, row, run_id: int) -> int:
    """Writes a merge plan. The caller owns the transaction. Returns the offer id.

    Column names come from the SYNC_MANAGED_FIELDS allowlist, never from input.
    """
    new_hash = source_payload_hash(offer)
    observed_json = plan.observed_after.to_json()
    assigns = plan.development.action == "assign"

    if plan.action == "created":
        columns = {
            "source_platform": offer.source_platform,
            "source_offer_ref": offer.source_offer_ref,
            "source_url": offer.source_url,
            **plan.create_columns,
            "source_values_json": observed_json,
            "source_payload_hash": new_hash,
            "last_sync_run_id": run_id,
        }
        if assigns:
            columns["development_id"] = plan.development.development_id
        names = ", ".join(columns)
        marks = ", ".join("?" for _ in columns)
        cursor = conn.execute(
            f"""
            INSERT INTO foreign_offers ({names}, last_source_sync_at, last_source_change_at)
            VALUES ({marks}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
            """,
            tuple(columns.values()),
        )
        offer_id = int(cursor.lastrowid)
        ensure_foreign_offer_sync_defaults(conn, offer_id)
        hash_before = None
    else:
        offer_id = int(row["id"])
        sets = {change.field: change.after for change in plan.applied}
        if assigns:
            sets["development_id"] = plan.development.development_id
        if row["source_values_json"] != observed_json:
            sets["source_values_json"] = observed_json
        sets["source_payload_hash"] = new_hash
        sets["last_sync_run_id"] = run_id
        assignments = ", ".join(f"{name} = ?" for name in sets)
        change_marker = ", last_source_change_at = CURRENT_TIMESTAMP" if row["source_payload_hash"] != new_hash else ""
        conn.execute(
            f"UPDATE foreign_offers SET {assignments}, last_source_sync_at = CURRENT_TIMESTAMP{change_marker} WHERE id = ?",
            (*sets.values(), offer_id),
        )
        hash_before = row["source_payload_hash"]

    if plan.images.action in ("create", "replace"):
        _replace_gallery(conn, offer_id, plan.images.value)
    if plan.features.action in ("create", "replace"):
        _replace_features(conn, offer_id, plan.features.value)

    if plan.action == "created" or plan.business_changed:
        # Judge the final state after the merge (manual values included), in the
        # same transaction. Bookkeeping-only syncs leave readiness alone.
        refresh_foreign_offer_export_state(conn, offer_id)

    if plan.action == "updated":
        changed = list(plan.applied_fields)
        if plan.images.action == "replace":
            changed.append("images")
        if plan.features.action == "replace":
            changed.append("features")
        if assigns:
            changed.append("development_id")
        # Existing semantics (TripInvest importer): only published offers get flagged.
        mark_foreign_offer_requires_update(conn, offer_id, "foreign_offer_source_changed", changed)

    conn.execute(
        """
        INSERT INTO foreign_offer_sync_log (
            foreign_offer_id, sync_status, change_detected, summary, raw_hash_before, raw_hash_after,
            started_at, finished_at, sync_run_id
        )
        VALUES (?, 'success', ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)
        """,
        (
            offer_id,
            1 if plan.action in ("created", "updated") else 0,
            _log_summary(plan),
            hash_before,
            new_hash,
            run_id,
        ),
    )
    return offer_id


def apply_source_availability(conn: sqlite3.Connection, offer_id: int, availability) -> None:
    """Source availability -> warnings, in the caller's transaction (INV-LC-5).

    sold_out   blocking source_sold_out (the offer is not export-ready)
    available  clears source_sold_out and source_availability_unclear
    unclear    advisory source_availability_unclear; a confirmed sold out stays
               until the source positively reports availability again
    None       the source said nothing: nothing changes
    Never touches is_active, managed fields, prices or manual CRM values.
    """
    if availability is None:
        return
    changed = False
    if availability.state == "sold_out":
        changed |= set_source_warning(
            conn, offer_id, SOURCE_SOLD_OUT,
            f"Źródło podaje, że typ lokalu jest wyprzedany (Sold Out): {availability.detail}. "
            "Publikacja i aktualizacja są zablokowane, dopóki źródło nie potwierdzi dostępności.",
            blocking=True,
        )
        changed |= set_source_warning(conn, offer_id, SOURCE_AVAILABILITY_UNCLEAR, None, blocking=False)
    elif availability.state == "available":
        changed |= set_source_warning(conn, offer_id, SOURCE_SOLD_OUT, None, blocking=True)
        changed |= set_source_warning(conn, offer_id, SOURCE_AVAILABILITY_UNCLEAR, None, blocking=False)
    else:
        changed |= set_source_warning(
            conn, offer_id, SOURCE_AVAILABILITY_UNCLEAR,
            f"Źródło podaje niejednoznaczne informacje o dostępności: {availability.detail}. Do oceny.",
            blocking=False,
        )
    if changed:
        refresh_foreign_offer_export_state(conn, offer_id)


def _process_offer(
    conn: sqlite3.Connection,
    offer: SyncOffer,
    development_outcomes: dict[str, DevelopmentOutcome],
    run_id: int | None,
    dry_run: bool,
) -> OfferOutcome:
    if not dry_run:
        conn.execute("BEGIN IMMEDIATE")
    try:
        row, existing = _load_existing(conn, offer)
        observed = parse_observed(row["source_values_json"]) if row is not None else Observed()
        if observed.corrupt:
            logger.warning(
                "Unreadable source_values_json for %s/%s; merging conservatively.",
                offer.source_platform, offer.source_offer_ref,
            )
        resolution = _resolution_for(conn, offer, development_outcomes)
        plan = merge_offer(existing, observed, offer, resolution)

        if dry_run:
            return OfferOutcome(offer.source_offer_ref, plan.action, int(row["id"]) if row is not None else None, plan)

        offer_id = apply_plan(conn, plan, offer, row, run_id)
        apply_source_availability(conn, offer_id, offer.availability)
        # The offer is in the source again (any run is positive evidence).
        if set_source_warning(conn, offer_id, SOURCE_MISSING, None, blocking=False):
            refresh_foreign_offer_export_state(conn, offer_id)
        conn.commit()
        return OfferOutcome(offer.source_offer_ref, plan.action, offer_id, plan)
    except Exception as exc:
        if not dry_run:
            conn.rollback()
        logger.warning("Offer %s/%s failed: %s", offer.source_platform, offer.source_offer_ref, exc)
        return OfferOutcome(offer.source_offer_ref, "error", error=str(exc))


# ---------------------------------------------------------------------------
# Missing offers (INV-LC-6)
# ---------------------------------------------------------------------------


def _is_complete_run_sql() -> str:
    # A fully successful catalog run: completed and nothing failed (project /
    # catalog fetch, adapter or per-offer sync errors all count in error_count).
    return "status = 'completed' AND error_count = 0"


def flag_missing_offers(source_platform: str, run_id: int) -> int:
    """Flags the source's offers absent from this run and the previous complete run.

    Call it only for a fully successful run (the runner checks that before it
    closes the run, see the runners). The previous complete run R_prev is the
    latest earlier run of the source with status 'completed' and error_count 0;
    failed, partial and running runs neither count nor reset anything. An offer
    is missing when it was seen in neither run: its last_sync_run_id (set by
    every run that processed it) is older than R_prev (or NULL). Such offers get
    the advisory source_missing warning; nothing else changes (is_active, data,
    portals). Returns the number of offers currently flagged, i.e. this run's
    missing_count; 0 when there is no previous complete run to compare with.
    """
    conn = open_foreign_offers_connection()
    try:
        ensure_foreign_offers_schema(conn)
        conn.commit()
        conn.execute("BEGIN IMMEDIATE")
        previous = conn.execute(
            f"""
            SELECT id FROM foreign_sync_runs
            WHERE source_platform = ? AND id < ? AND {_is_complete_run_sql()}
            ORDER BY id DESC LIMIT 1
            """,
            (source_platform, int(run_id)),
        ).fetchone()
        if previous is None:
            conn.rollback()
            return 0
        missing_ids = [
            int(row["id"])
            for row in conn.execute(
                """
                SELECT id FROM foreign_offers
                WHERE source_platform = ? AND COALESCE(last_sync_run_id, 0) < ?
                ORDER BY id
                """,
                (source_platform, int(previous["id"])),
            )
        ]
        for offer_id in missing_ids:
            message = (
                f"Oferty nie ma w dwóch kolejnych pełnych synchronizacjach źródła "
                f"(runy {int(previous['id'])} i {int(run_id)}). Do decyzji: wycofanie lub weryfikacja."
            )
            if set_source_warning(conn, offer_id, SOURCE_MISSING, message, blocking=False):
                refresh_foreign_offer_export_state(conn, offer_id)
        conn.commit()
        return len(missing_ids)
    except BaseException:
        conn.rollback()
        raise
    finally:
        conn.close()


# ---------------------------------------------------------------------------
# Service
# ---------------------------------------------------------------------------


def _validate_run(source_platform: str, run_id: int | None, *, dry_run: bool) -> None:
    if run_id is None:
        if dry_run:
            return
        raise ValueError("run_id is required unless dry_run=True.")
    run = get_foreign_sync_run(run_id)
    if run is None:
        raise ValueError(f"Sync run {run_id} does not exist.")
    if run["source_platform"] != source_platform:
        raise ValueError(
            f"Sync run {run_id} belongs to {run['source_platform']!r}, not {source_platform!r}."
        )
    if not dry_run and run["status"] != SYNC_RUN_STATUS_RUNNING:
        raise ValueError(f"Sync run {run_id} is not running.")


def sync_records(
    source_platform: str,
    developments: Iterable[SyncDevelopment],
    offers: Iterable[SyncOffer],
    *,
    run_id: int | None = None,
    dry_run: bool = False,
    finish_run: bool = True,
) -> SyncReport:
    """Merges normalized records of one source into foreign_developments/foreign_offers.

    The caller creates the run (lifecycle belongs to the runner) and passes
    its id; it must belong to source_platform and still be 'running'. With
    finish_run (default) and not dry_run, the run is closed as 'completed'
    with the counts; errors of single records are counted, not fatal. An
    unexpected exception leaves the run 'running' for the runner to fail.

    dry_run resolves identities and merges exactly the same way but writes no
    data (and creates no ids); a development that would be created is reported
    as 'would_create'. (The idempotent schema check still runs.)
    """
    platform = str(source_platform or "").strip()
    if not platform:
        raise ValueError("source_platform is required.")
    developments = list(developments)
    offers = list(offers)
    for item in (*developments, *offers):
        if item.source_platform != platform:
            raise SyncContractError(
                f"{type(item).__name__} of {item.source_platform!r} passed to a {platform!r} sync."
            )
    _validate_run(platform, run_id, dry_run=dry_run)

    report = SyncReport(platform, run_id, dry_run, discovered_count=len(offers))
    conn = open_foreign_offers_connection()
    try:
        ensure_foreign_offers_schema(conn)
        conn.commit()

        outcomes: dict[str, DevelopmentOutcome] = {}
        for development in developments:
            if development.source_key in outcomes:
                continue  # first occurrence wins
            outcome = ensure_development(conn, development, dry_run=dry_run)
            outcomes[development.source_key] = outcome
            report.developments.append(outcome)

        seen_refs: set[str] = set()
        for offer in offers:
            if offer.source_offer_ref in seen_refs:
                result = OfferOutcome(offer.source_offer_ref, "error", error="duplicate source_offer_ref in this batch")
            else:
                seen_refs.add(offer.source_offer_ref)
                result = _process_offer(conn, offer, outcomes, run_id, dry_run)
            report.offers.append(result)
            if result.action == "created":
                report.new_count += 1
            elif result.action == "updated":
                report.updated_count += 1
            elif result.action == "unchanged":
                report.unchanged_count += 1
            else:
                report.error_count += 1
    finally:
        conn.close()

    if finish_run and not dry_run:
        errors = report.errors
        message = "; ".join(errors[:3])[:_RUN_ERROR_MESSAGE_LIMIT] if errors else None
        finish_foreign_sync_run(
            run_id, SYNC_RUN_STATUS_COMPLETED, error_message=message, **report.run_counts()
        )
    return report
