"""Offline contracts for the relocated Homelanzarote integration."""
import importlib
import os
from pathlib import Path
import subprocess
import sys
from types import SimpleNamespace

import pytest

from integrations.homelanzarote import scraper


ROOT = Path(__file__).resolve().parents[2]
BASE = "https://www.homelanzarote.es"
CARD = """<div class="bx_resumen_prop_grid">
  <div class="prop_tipo">House</div><h3 class="prop_localiz"><span>Test City</span></h3>
  <div class="info_precio"><span class="importe">200,000 EUR</span></div>
  <a class="enlace_imagen_propiedad" href="/en/fixture"><img src="/fixture.jpg"></a>
  <div class="referencia"><a>TEST-1</a></div><span class="ctlto">Sale</span>
  <span class="iconos_carac"><span class="icinfo"><img title="Size">100 m2</span></span>
</div>"""


def test_connector_and_legacy_import_share_the_canonical_functions():
    legacy = importlib.import_module("modules.homelanzarote.homelanzarote_scraper")
    from InvestmentWebsite.offers.connectors import lanzarote_connector as connector

    assert legacy is scraper
    assert connector.scrape_category is scraper.scrape_category
    assert connector.scrape_offer_details is scraper.scrape_offer_details
    assert scraper.logger.name == "modules.homelanzarote.homelanzarote_scraper"


@pytest.mark.parametrize("all_pages", [False, True])
def test_catalog_payload_pagination_headers_and_timeout(monkeypatch, all_pages):
    calls, sleeps = [], []
    next_page = '<p id="paginacion_form_busc_av"><a class="bot_pagin" href="/en/houses?page=2">Next</a></p>'

    def get(url, **kwargs):
        calls.append((url, kwargs))
        html = CARD + (next_page if len(calls) == 1 else "")
        return SimpleNamespace(status_code=200, content=html.encode())

    monkeypatch.setattr(scraper.requests, "get", get)
    monkeypatch.setattr(scraper.time, "sleep", sleeps.append)
    expected = {"title": "House", "location": "Test City", "price": "200,000 EUR",
                "url": "/en/fixture", "image": BASE + "/fixture.jpg", "ref": "TEST-1",
                "label": "Sale", "size": "100 m2"}
    assert scraper.scrape_category("houses", all_pages=all_pages) == [expected] * (2 if all_pages else 1)
    assert [url for url, _ in calls] == [BASE + "/en/houses"] + ([BASE + "/en/houses?page=2"] if all_pages else [])
    assert all(kwargs == {"headers": scraper.HEADERS, "timeout": 15} for _, kwargs in calls)
    assert sleeps == ([1] if all_pages else [])


def test_category_language_and_invalid_category(monkeypatch):
    calls = []
    monkeypatch.setattr(scraper, "scrape_offers", lambda url, **kwargs: calls.append((url, kwargs)) or [])
    assert scraper.scrape_category("houses", all_pages=False, lang="es") == []
    assert calls == [(BASE + "/es/houses", {"all_pages": False})]
    with pytest.raises(ValueError, match="Nieprawidlowa kategoria"):
        scraper.scrape_category("not-a-category")
    assert len(calls) == 1


def test_catalog_http_failure_preserves_empty_result(monkeypatch):
    monkeypatch.setattr(scraper.requests, "get", lambda *a, **k: SimpleNamespace(status_code=503))
    assert scraper.scrape_offers(BASE + "/en/houses") == []


def test_details_payload_and_language(monkeypatch):
    calls = []
    html = """<h3>Fixture title</h3><div class="info_precio"><span class="importe">250 EUR</span></div>
    <div class="referencia"><a class="codigo-tag-referencia">TEST-2</a></div><span class="ctlto">Sale</span>
    <div class="localizacion"><span>Test City</span><span>Test Area</span></div>
    <div class="foton"><img src="/detail.jpg"></div>
    <div class="descripcion"><span class="breve"><a>Short title</a></span><span class="larga">Description</span></div>
    <span class="iconos_carac"><span class="icinfo"><img title="bedroom">3</span></span>
    <div class="caracteristicas"><div class="car"><span class="car_cap">Year:</span><span class="car_val">2020</span></div></div>"""

    def get(url, **kwargs):
        calls.append((url, kwargs))
        return SimpleNamespace(status_code=200, content=html.encode())

    monkeypatch.setattr(scraper.requests, "get", get)
    assert scraper.scrape_offer_details(BASE + "/en/fixture", lang="es") == {
        "url": BASE + "/es/fixture", "title": "Fixture title", "price": "250 EUR",
        "location": "Test City, Test Area", "ref": "TEST-2", "label": "Sale",
        "image": BASE + "/detail.jpg", "features": {"bedrooms": "3"},
        "details": {"Year": "2020"}, "short_title": "Short title", "description": "Description",
    }
    assert calls == [(BASE + "/es/fixture", {"headers": scraper.HEADERS, "timeout": 15})]


@pytest.mark.parametrize("failure", ["http", "request"])
def test_detail_errors_are_preserved(monkeypatch, failure):
    def get(*args, **kwargs):
        if failure == "request":
            raise RuntimeError("fixture-error")
        return SimpleNamespace(status_code=503)

    monkeypatch.setattr(scraper.requests, "get", get)
    with pytest.raises(Exception, match="Request failed: fixture-error" if failure == "request" else "Bad status code: 503"):
        scraper.scrape_offer_details(BASE + "/en/fixture")


@pytest.mark.parametrize("entry", [
    "modules.homelanzarote.homelanzarote_scraper", "integrations.homelanzarote.scraper",
    "modules/homelanzarote/homelanzarote_scraper.py", "integrations/homelanzarote/scraper.py",
])
def test_module_and_file_execution_do_not_start_scraping(entry, tmp_path):
    code = """
import runpy,socket,sys
from pathlib import Path
def deny(*args,**kwargs):raise AssertionError('Network forbidden')
socket.create_connection=deny;socket.socket.connect=deny;socket.socket.connect_ex=deny
root=Path(sys.argv[1]);entry=sys.argv[2]
if entry.endswith('.py'):
    ns=runpy.run_path(str(root/entry),run_name='__main__')
else:
    sys.path.insert(0,str(root));ns=runpy.run_module(entry,run_name='__main__')
assert callable(ns.get('scrape_category')) or entry.startswith('modules')
assert 'requests' in sys.modules
assert 'modules.core.app_factory' not in sys.modules
assert 'InvestmentManager.scheduled_jobs' not in sys.modules
print('OK')
"""
    env = os.environ.copy()
    env.pop("PYTHONPATH", None)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    before = set(tmp_path.iterdir())
    result = subprocess.run([sys.executable, "-B", "-c", code, str(ROOT), entry],
                            cwd=tmp_path, env=env, capture_output=True, text=True, timeout=30)
    assert result.returncode == 0, result.stderr
    assert result.stdout.strip() == "OK"
    assert set(tmp_path.iterdir()) == before
