"""Tests for integrations/cyprus_constructions/live_client.py.

Context: this integration used to dynamically load two scraper scripts
(cyprus_all_projects.py, cyprus_project_details.py) from a sibling folder
outside the InvestmentWebsite repo (optionally overridden by the
CYPRUS_CONSTRUCTIONS_DIR env var). That made the Cyprus feature incomplete
after a plain `git clone` of this repo. The scrapers now live inside
integrations/cyprus_constructions/ and are imported as ordinary Python
submodules of this package.

These tests document/verify:
  - both scraper modules are real files inside this repo's
    integrations/cyprus_constructions/ package (not loaded from anywhere else),
  - importing the integration performs no network I/O,
  - CYPRUS_CONSTRUCTIONS_DIR has no effect any more (not required, not read),
  - fetch_projects()/fetch_project_details() delegate to the local modules
    and preserve prior caching/error behaviour, all with faked scraper
    functions so no real request to cyprusconstructions.com is ever made.
"""
import importlib
import inspect
from pathlib import Path

import pytest

from integrations.cyprus_constructions import cyprus_all_projects, cyprus_project_details, live_client

THIS_PACKAGE_DIR = Path(__file__).resolve().parents[1].parent / "integrations" / "cyprus_constructions"


@pytest.fixture(autouse=True)
def clear_payload_cache():
    live_client._PAYLOAD_CACHE.clear()
    yield
    live_client._PAYLOAD_CACHE.clear()


# ---------------------------------------------------------------------------
# Both scraper models are loaded exclusively from inside this repo.
# ---------------------------------------------------------------------------

def test_cyprus_all_projects_module_file_lives_inside_this_repo():
    module_path = Path(inspect.getfile(cyprus_all_projects)).resolve()
    assert module_path.parent == THIS_PACKAGE_DIR
    assert module_path.name == "cyprus_all_projects.py"


def test_cyprus_project_details_module_file_lives_inside_this_repo():
    module_path = Path(inspect.getfile(cyprus_project_details)).resolve()
    assert module_path.parent == THIS_PACKAGE_DIR
    assert module_path.name == "cyprus_project_details.py"


def test_both_scraper_modules_expose_the_functions_live_client_relies_on():
    assert hasattr(cyprus_all_projects, "scrape_all_projects")
    assert hasattr(cyprus_project_details, "make_session")
    assert hasattr(cyprus_project_details, "extract_project")


def test_sibling_folder_lookup_mechanism_no_longer_exists():
    # These used to exist on live_client and implemented the sibling-folder
    # search / dynamic file loading. Their absence is the actual guarantee
    # that nothing outside the repo is consulted any more.
    for removed_name in (
        "get_model_dir",
        "_default_model_dir",
        "_load_module",
        "_all_projects_module",
        "_project_details_module",
    ):
        assert not hasattr(live_client, removed_name), removed_name


def test_cyprus_constructions_dir_env_var_has_no_effect(tmp_path, monkeypatch):
    # Point it at a directory that does not contain the scrapers at all.
    # If this env var still mattered, fetch_projects() would now fail to
    # locate scrape_all_projects(); it must not, because it isn't consulted.
    monkeypatch.setenv("CYPRUS_CONSTRUCTIONS_DIR", str(tmp_path / "does-not-exist"))

    calls = []

    def fake_scrape_all_projects(url):
        calls.append(url)
        return {"projects": [], "source": {"all_projects_url": url}}

    monkeypatch.setattr(cyprus_all_projects, "scrape_all_projects", fake_scrape_all_projects)

    result = live_client.fetch_projects("https://example.invalid/all-projects")
    assert calls == ["https://example.invalid/all-projects"]
    assert result["projects"] == []


# ---------------------------------------------------------------------------
# No network I/O at import time.
# ---------------------------------------------------------------------------

def test_reimporting_scraper_modules_performs_no_http(monkeypatch):
    def _forbidden_get(*args, **kwargs):
        raise AssertionError("HTTP request attempted during module import")

    import requests

    monkeypatch.setattr(requests.Session, "get", _forbidden_get)
    monkeypatch.setattr(requests, "get", _forbidden_get)

    # Reload rather than re-import: a fresh Python interpreter would run the
    # module body once; reload re-executes it against the patched requests,
    # which is exactly what we want to characterise here.
    importlib.reload(cyprus_all_projects)
    importlib.reload(cyprus_project_details)
    importlib.reload(live_client)


# ---------------------------------------------------------------------------
# fetch_projects() / fetch_project_details(): behaviour preserved, no real
# HTTP (the underlying scraper calls are faked).
# ---------------------------------------------------------------------------

def test_fetch_projects_delegates_to_local_cyprus_all_projects(monkeypatch):
    captured = {}

    def fake_scrape_all_projects(url):
        captured["url"] = url
        return {"source": {"all_projects_url": url}, "projects": [{"id": 1}]}

    monkeypatch.setattr(cyprus_all_projects, "scrape_all_projects", fake_scrape_all_projects)

    result = live_client.fetch_projects("https://example.invalid/all-projects")
    assert captured["url"] == "https://example.invalid/all-projects"
    assert result["projects"] == [{"id": 1}]


def test_fetch_projects_uses_default_url_when_none_given(monkeypatch):
    captured = {}
    monkeypatch.setattr(
        cyprus_all_projects,
        "scrape_all_projects",
        lambda url: captured.setdefault("url", url) or {"projects": []},
    )
    live_client.fetch_projects()
    assert captured["url"] == live_client.DEFAULT_ALL_PROJECTS_URL


def test_fetch_projects_caches_result_and_does_not_rescrape(monkeypatch):
    calls = []
    monkeypatch.setattr(
        cyprus_all_projects,
        "scrape_all_projects",
        lambda url: calls.append(url) or {"projects": [], "call": len(calls)},
    )

    first = live_client.fetch_projects("https://example.invalid/all-projects")
    second = live_client.fetch_projects("https://example.invalid/all-projects")

    assert len(calls) == 1
    assert first == second


def test_fetch_projects_force_refresh_bypasses_cache(monkeypatch):
    calls = []
    monkeypatch.setattr(
        cyprus_all_projects,
        "scrape_all_projects",
        lambda url: calls.append(url) or {"projects": [], "call": len(calls)},
    )

    live_client.fetch_projects("https://example.invalid/all-projects")
    live_client.fetch_projects("https://example.invalid/all-projects", force_refresh=True)

    assert len(calls) == 2


def test_fetch_project_details_delegates_to_local_cyprus_project_details(monkeypatch):
    sentinel_session = object()
    captured = {}

    monkeypatch.setattr(cyprus_project_details, "make_session", lambda: sentinel_session)

    def fake_extract_project(session, project_url):
        captured["session"] = session
        captured["project_url"] = project_url
        return {"project": {"name": "Test Project"}, "unit_types": []}

    monkeypatch.setattr(cyprus_project_details, "extract_project", fake_extract_project)

    result = live_client.fetch_project_details("https://example.invalid/pl/Test_homes")
    assert captured["session"] is sentinel_session
    assert captured["project_url"] == "https://example.invalid/pl/Test_homes"
    assert result["project"]["name"] == "Test Project"


def test_fetch_project_details_without_url_raises_without_touching_network(monkeypatch):
    def _forbidden(*args, **kwargs):
        raise AssertionError("scraper should not be called without a project_url")

    monkeypatch.setattr(cyprus_project_details, "make_session", _forbidden)
    monkeypatch.setattr(cyprus_project_details, "extract_project", _forbidden)

    with pytest.raises(live_client.CyprusConstructionsError, match="Brak URL projektu"):
        live_client.fetch_project_details("")


def test_fetch_project_details_caches_result(monkeypatch):
    calls = []
    monkeypatch.setattr(cyprus_project_details, "make_session", lambda: object())
    monkeypatch.setattr(
        cyprus_project_details,
        "extract_project",
        lambda session, url: calls.append(url) or {"project": {"name": "X"}, "call": len(calls)},
    )

    first = live_client.fetch_project_details("https://example.invalid/pl/X_homes")
    second = live_client.fetch_project_details("https://example.invalid/pl/X_homes")

    assert len(calls) == 1
    assert first == second


def test_cache_disabled_when_ttl_is_zero(monkeypatch):
    monkeypatch.setenv("CYPRUS_CONSTRUCTIONS_CACHE_TTL", "0")
    calls = []
    monkeypatch.setattr(
        cyprus_all_projects,
        "scrape_all_projects",
        lambda url: calls.append(url) or {"projects": [], "call": len(calls)},
    )

    live_client.fetch_projects("https://example.invalid/all-projects")
    live_client.fetch_projects("https://example.invalid/all-projects")

    assert len(calls) == 2
