"""FOREIGN-SYNC-UI-1: CRM actions for Avarten and Cyprus source syncs."""
import pathlib

import pytest

import InvestmentManager.routes.foreign_offers as foreign_offer_routes
from InvestmentManager.foreign_sync_actions import (
    ForeignSyncAction,
    ForeignSyncAlreadyRunning,
    ForeignSyncFailed,
    SOURCE_ACTIONS,
    run_foreign_source_sync,
)
from tests.investmentmanager.test_foreign_developments_routes import _login, foreign_db  # noqa: F401


class FakeSyncResult:
    def __init__(self, **values):
        self._values = values

    def summary(self):
        return {
            "dry_run": False,
            "fully_successful": True,
            "discovered": 7,
            "new": 1,
            "updated": 2,
            "unchanged": 4,
            "adapter_errors": 0,
            "sync_errors": 0,
            "development_conflicts": [],
            "run_id": 11,
            "run_status": "completed",
            "errors": [],
            **self._values,
        }


def test_admin_can_trigger_avarten_sync(client, foreign_db, monkeypatch):
    _login(client, "admin")
    calls = []

    def fake(source):
        calls.append(source)
        return FakeSyncResult().summary() | {"source": source, "label": "Dubaj", "errors": 0, "messages": []}

    monkeypatch.setattr(foreign_offer_routes, "run_foreign_source_sync", fake)

    response = client.post("/crm/foreign-offers/sync/avarten")

    assert response.status_code == 200
    payload = response.get_json()
    assert payload["ok"] is True
    assert payload["summary"] == {
        "source": "avarten",
        "label": "Dubaj",
        "dry_run": False,
        "fully_successful": True,
        "discovered": 7,
        "new": 1,
        "updated": 2,
        "unchanged": 4,
        "adapter_errors": 0,
        "sync_errors": 0,
        "development_conflicts": [],
        "run_id": 11,
        "run_status": "completed",
        "errors": 0,
        "messages": [],
    }
    assert calls == ["avarten"]


def test_admin_can_trigger_cyprus_sync_without_invoking_avarten(client, foreign_db, monkeypatch):
    _login(client, "master")
    calls = []

    def fake(source):
        calls.append(source)
        return {
            "source": source,
            "label": "Cypr",
            "dry_run": False,
            "fully_successful": True,
            "discovered": 34,
            "projects_discovered": 8,
            "units_discovered": 34,
            "developments_adapted": 8,
            "offers_adapted": 34,
            "new": 0,
            "updated": 0,
            "unchanged": 34,
            "errors": 0,
            "fetch_errors": 0,
            "run_id": 12,
            "run_status": "completed",
            "development_conflicts": [],
            "messages": [],
        }

    monkeypatch.setattr(foreign_offer_routes, "run_foreign_source_sync", fake)

    response = client.post("/crm/foreign-offers/sync/cyprus_constructions")

    assert response.status_code == 200
    assert response.get_json()["summary"]["label"] == "Cypr"
    assert response.get_json()["summary"]["projects_discovered"] == 8
    assert calls == ["cyprus_constructions"]


@pytest.mark.parametrize("source", ["avarten", "cyprus_constructions"])
def test_non_admin_cannot_trigger_sync(client, foreign_db, source, monkeypatch):
    calls = []
    monkeypatch.setattr(foreign_offer_routes, "run_foreign_source_sync", lambda source: calls.append(source))

    assert client.post(f"/crm/foreign-offers/sync/{source}").status_code == 403
    _login(client, "agent")
    assert client.post(f"/crm/foreign-offers/sync/{source}").status_code == 403
    assert calls == []


def test_unknown_source_is_not_dispatched(client, foreign_db, monkeypatch):
    _login(client)
    calls = []
    monkeypatch.setattr(foreign_offer_routes, "run_foreign_source_sync", lambda source: calls.append(source))

    response = client.post("/crm/foreign-offers/sync/not_a_source")

    assert response.status_code == 404
    assert calls == []


def test_sync_failure_returns_non_success_response(client, foreign_db, monkeypatch):
    _login(client)
    monkeypatch.setattr(
        foreign_offer_routes,
        "run_foreign_source_sync",
        lambda source: (_ for _ in ()).throw(ForeignSyncFailed("catalog down")),
    )

    response = client.post("/crm/foreign-offers/sync/avarten")

    assert response.status_code == 502
    assert response.get_json() == {"ok": False, "error": "catalog down"}


def test_same_source_duplicate_execution_is_guarded(client, foreign_db, monkeypatch):
    _login(client)
    monkeypatch.setattr(
        foreign_offer_routes,
        "run_foreign_source_sync",
        lambda source: (_ for _ in ()).throw(ForeignSyncAlreadyRunning("busy")),
    )

    response = client.post("/crm/foreign-offers/sync/avarten")

    assert response.status_code == 409
    assert response.get_json()["ok"] is False


def test_failed_run_status_returns_non_success_response(client, foreign_db, monkeypatch):
    _login(client)
    summary = FakeSyncResult(fully_successful=False, run_status="failed").summary()
    summary.update({"source": "avarten", "label": "Dubaj", "errors": 2, "messages": ["bad"]})
    monkeypatch.setattr(foreign_offer_routes, "run_foreign_source_sync", lambda source: summary)

    response = client.post("/crm/foreign-offers/sync/avarten")

    assert response.status_code == 500
    assert response.get_json()["ok"] is False


def test_service_summary_uses_allowlisted_runner_and_stable_labels(monkeypatch):
    calls = []

    def runner():
        calls.append("avarten")
        return FakeSyncResult()

    monkeypatch.setitem(SOURCE_ACTIONS, "avarten", ForeignSyncAction("avarten", "Dubaj", runner))

    summary = run_foreign_source_sync("avarten")

    assert calls == ["avarten"]
    assert summary["source"] == "avarten"
    assert summary["label"] == "Dubaj"
    assert (summary["discovered"], summary["new"], summary["updated"], summary["unchanged"], summary["errors"]) == (7, 1, 2, 4, 0)


def test_service_lock_allows_other_source_but_blocks_same_source(monkeypatch):
    from InvestmentManager import foreign_sync_actions

    foreign_sync_actions._LOCKS["avarten"].acquire()
    try:
        with pytest.raises(ForeignSyncAlreadyRunning):
            run_foreign_source_sync("avarten")
    finally:
        foreign_sync_actions._LOCKS["avarten"].release()

    calls = []
    monkeypatch.setitem(
        SOURCE_ACTIONS,
        "cyprus_constructions",
        ForeignSyncAction("cyprus_constructions", "Cypr", lambda: calls.append("cyprus") or FakeSyncResult(
            projects_discovered=1,
            units_discovered=2,
            developments_adapted=1,
            offers_adapted=2,
            fetch_errors=0,
        )),
    )

    assert run_foreign_source_sync("cyprus_constructions")["source"] == "cyprus_constructions"
    assert calls == ["cyprus"]


def test_foreign_offers_page_exposes_source_sync_actions(client, foreign_db):
    _login(client)

    html = client.get("/crm/foreign-offers").get_data(as_text=True)

    assert 'data-foreign-sync-source="avarten"' in html
    assert 'data-foreign-sync-source="cyprus_constructions"' in html
    assert "Synchronizuj Dubaj" in html
    assert "Synchronizuj Cypr" in html


def test_foreign_offers_page_exposes_operational_filters(client, foreign_db):
    _login(client)

    html = client.get("/crm/foreign-offers").get_data(as_text=True)

    assert 'id="foreign-offers-filter-source"' in html
    assert '<option value="tripinvest">Hiszpania</option>' in html
    assert '<option value="avarten">Dubaj</option>' in html
    assert '<option value="cyprus_constructions">Cypr</option>' in html
    assert 'id="foreign-offers-filter-market"' in html
    assert '<option value="missing">Brak rynku</option>' in html
    assert 'id="foreign-offers-filter-development"' in html
    assert 'id="foreign-offers-filter-readiness"' in html
    assert '<option value="needs_completion">Wymagają uzupełnienia</option>' in html
    assert 'id="foreign-offers-clear-filters-btn"' in html
    assert 'id="foreign-offers-count"' in html


def test_frontend_sync_contract_is_wired_to_refresh_the_list_after_success():
    js = pathlib.Path(__file__).resolve().parents[2] / "InvestmentManager" / "static" / "js" / "foreign_offers.js"
    source = js.read_text(encoding="utf-8")

    assert "foreignOffersRunSourceSync" in source
    assert "/crm/foreign-offers/sync/" in source
    assert "data-foreign-sync-source" in source
    sync_call = source.index("/crm/foreign-offers/sync/")
    refresh_call = source.index("foreignOffersReloadList({ keepState: true })", sync_call)
    assert refresh_call > sync_call


def test_frontend_filter_contract_uses_list_query_and_reset_page():
    js = pathlib.Path(__file__).resolve().parents[2] / "InvestmentManager" / "static" / "js" / "foreign_offers.js"
    source = js.read_text(encoding="utf-8")

    assert "foreignOffersBuildListUrl" in source
    assert 'params.set("page", String(foreignOffersPage))' in source
    assert "foreignOffersReloadList({ resetPage: true })" in source
    assert "filter_options?.developments" in source
    assert "Brak ofert spełniających wybrane filtry." in source
    sync_call = source.index("/crm/foreign-offers/sync/")
    refresh_call = source.index("foreignOffersReloadList({ keepState: true })", sync_call)
    assert refresh_call > sync_call
