"""CRM-facing foreign source sync actions.

This module is intentionally thin: source-specific runners keep ownership of
fetch/adapt/sync semantics, while this layer provides a safe allowlist,
stable summaries for JSON responses, and per-source duplicate-run protection.
"""
from __future__ import annotations

from dataclasses import dataclass
from threading import Lock
from typing import Callable

from InvestmentManager.foreign_sync_sources.avarten_run import AvartenFetchError, run_avarten_foreign_sync
from InvestmentManager.foreign_sync_sources.cyprus_run import CyprusFetchError, run_cyprus_foreign_sync


class ForeignSyncAlreadyRunning(RuntimeError):
    """A sync for this source is already running in this process."""


class ForeignSyncFailed(RuntimeError):
    """The source sync could not complete enough to produce a result."""


@dataclass(frozen=True)
class ForeignSyncAction:
    source_platform: str
    label: str
    runner: Callable[[], object]


SOURCE_ACTIONS: dict[str, ForeignSyncAction] = {
    "avarten": ForeignSyncAction("avarten", "Dubaj", run_avarten_foreign_sync),
    "cyprus_constructions": ForeignSyncAction("cyprus_constructions", "Cypr", run_cyprus_foreign_sync),
}

_LOCKS = {source: Lock() for source in SOURCE_ACTIONS}


def _int_value(summary: dict, key: str) -> int:
    value = summary.get(key, 0)
    return value if isinstance(value, int) and not isinstance(value, bool) else 0


def _stable_summary(source_platform: str, label: str, result) -> dict:
    raw = result.summary()
    summary = {
        "source": source_platform,
        "label": label,
        "dry_run": bool(raw.get("dry_run", False)),
        "fully_successful": bool(raw.get("fully_successful", False)),
        "discovered": _int_value(raw, "units_discovered") if source_platform == "cyprus_constructions" else _int_value(raw, "discovered"),
        "new": _int_value(raw, "new"),
        "updated": _int_value(raw, "updated"),
        "unchanged": _int_value(raw, "unchanged"),
        "errors": _int_value(raw, "adapter_errors") + _int_value(raw, "sync_errors"),
        "run_id": raw.get("run_id"),
        "run_status": raw.get("run_status"),
        "development_conflicts": list(raw.get("development_conflicts") or []),
        "messages": [str(item) for item in raw.get("errors") or []],
    }
    if source_platform == "cyprus_constructions":
        summary.update(
            {
                "projects_discovered": _int_value(raw, "projects_discovered"),
                "units_discovered": _int_value(raw, "units_discovered"),
                "developments_adapted": _int_value(raw, "developments_adapted"),
                "offers_adapted": _int_value(raw, "offers_adapted"),
                "fetch_errors": _int_value(raw, "fetch_errors"),
            }
        )
        summary["errors"] += summary["fetch_errors"]
    return summary


def run_foreign_source_sync(source_platform: str) -> dict:
    action = SOURCE_ACTIONS.get(str(source_platform or "").strip())
    if action is None:
        raise KeyError(source_platform)

    lock = _LOCKS[action.source_platform]
    if not lock.acquire(blocking=False):
        raise ForeignSyncAlreadyRunning(f"Sync {action.source_platform} is already running.")
    try:
        try:
            result = action.runner()
        except (AvartenFetchError, CyprusFetchError) as exc:
            raise ForeignSyncFailed(str(exc)) from exc
        return _stable_summary(action.source_platform, action.label, result)
    finally:
        lock.release()
