"""INV-LC-7: an HTTP 200 page without offer content never reaches the CRM.

Real details parser and TripinvestConnector; only requests.get is replaced
(so the URL/redirect validation of fetch_html still runs). A rejected page
changes nothing: no offer, data, snapshot, sync log or update flags.
"""
import sqlite3

import pytest

import integrations.tripinvest.helpers as helpers
from InvestmentManager.foreign_offers_importer import upsert_foreign_offer_from_tripinvest
from tests.investmentmanager.test_foreign_developments import foreign_db, fresh_db  # noqa: F401
from tests.investmentmanager.test_foreign_developments_routes import _login

URL = "https://tripinvest.pl/oferta/apartament-w-torrevieja-75156"

EMPTY = ""
BLANK_HTML = "<html><head><title>TripInvest</title></head><body></body></html>"
ERROR_PAGE_200 = """
<html><body>
  <h1>Ups! Ta strona nie istnieje</h1>
  <div class="icube-ce-item-image"><img src="https://tripinvest.pl/static/logo.png"></div>
  <p>Wróć do <a href="/">strony głównej</a>.</p>
</body></html>
"""
FULL_OFFER = """
<html><body>
  <h1>Apartament w Torrevieja, Costa Blanca</h1>
  <div class="v-offer-data-box">
    <p class="text-30px">199 000€</p>
    <div class="col-6"><p class="text-13px">Powierzchnia</p><b>64 m²</b></div>
    <div class="col-6"><p class="text-13px">Liczba sypialni</p><b>2</b></div>
  </div>
  <div class="c-gallery-thumb"><div data-src="https://static.example/1.jpg"></div></div>
</body></html>
"""
PARTIAL_OFFER = """
<html><body>
  <h1>Willa w Orihuela Costa, Costa Blanca</h1>
  <div class="v-offer-data-box">
    <p class="text-30px">Cena na zapytanie</p>
    <div class="col-6"><p class="text-13px">Powierzchnia</p><b>140 m²</b></div>
  </div>
</body></html>
"""


class Page:
    def __init__(self, html, status=200):
        self.text, self.status_code, self.headers = html, status, {}

    is_redirect = False

    def raise_for_status(self):
        if self.status_code >= 400:
            raise RuntimeError(self.status_code)


@pytest.fixture()
def serve(fresh_db, monkeypatch):
    current = {"html": FULL_OFFER}
    monkeypatch.setattr(helpers.requests, "get", lambda url, **kwargs: Page(current["html"]))
    monkeypatch.setattr("integrations.tripinvest.details_crawler.time.sleep", lambda seconds: None)

    def set_html(html):
        current["html"] = html

    return set_html


def state(db):
    conn = sqlite3.connect(db)
    try:
        return {table: conn.execute(f"SELECT * FROM {table} ORDER BY 1").fetchall() for table in (
            "foreign_offers", "foreign_offer_images", "foreign_offer_raw_snapshots", "foreign_offer_sync_log",
            "foreign_offer_export_warnings", "foreign_offer_portal_sync", "foreign_offer_portal_sync_events",
            "foreign_developments")}
    finally:
        conn.close()


@pytest.mark.parametrize("html", [EMPTY, BLANK_HTML, ERROR_PAGE_200], ids=["empty", "blank_html", "error_page_200"])
def test_new_import_of_a_page_without_offer_content_is_rejected(serve, fresh_db, html):
    serve(html)
    with pytest.raises(ValueError, match="nie zawiera treści oferty"):
        upsert_foreign_offer_from_tripinvest(URL)
    assert state(fresh_db)["foreign_offers"] == []


@pytest.mark.parametrize("html", [EMPTY, ERROR_PAGE_200], ids=["empty", "error_page_200"])
def test_refresh_with_a_bad_page_changes_nothing(serve, fresh_db, html):
    upsert_foreign_offer_from_tripinvest(URL)
    conn = sqlite3.connect(fresh_db)
    conn.execute("UPDATE foreign_offer_portal_sync SET is_published = 1 WHERE portal_key = 'domiporta'")
    conn.commit()
    conn.close()
    before = state(fresh_db)

    serve(html)
    with pytest.raises(ValueError, match="nie zawiera treści oferty"):
        upsert_foreign_offer_from_tripinvest(URL)

    after = state(fresh_db)
    assert after == before  # no title "Nieruchomość", no market "unknown", no snapshot, no flags


def test_full_offer_page_is_imported(serve, fresh_db):
    result = upsert_foreign_offer_from_tripinvest(URL)

    row = state(fresh_db)["foreign_offers"][0]
    assert result["foreign_offer_id"] == row[0]
    conn = sqlite3.connect(fresh_db)
    title, price, area = conn.execute("SELECT offer_title, price_value, area_total_m2 FROM foreign_offers").fetchone()
    conn.close()
    assert (title, float(price), float(area)) == ("Apartament w Torrevieja, Costa Blanca", 199000, 64)


def test_partial_offer_without_price_is_still_imported(serve, fresh_db):
    serve(PARTIAL_OFFER)
    upsert_foreign_offer_from_tripinvest(URL)

    conn = sqlite3.connect(fresh_db)
    title, price, area = conn.execute("SELECT offer_title, price_value, area_total_m2 FROM foreign_offers").fetchone()
    conn.close()
    assert (title, price, float(area)) == ("Willa w Orihuela Costa, Costa Blanca", None, 140)


def test_ssrf_guard_still_runs_before_any_request(fresh_db, monkeypatch):
    requested = []
    monkeypatch.setattr(helpers.requests, "get", lambda url, **kwargs: requested.append(url) or Page(FULL_OFFER))
    with pytest.raises(ValueError):
        upsert_foreign_offer_from_tripinvest("http://127.0.0.1/oferta/x")
    assert requested == []


# Entry points ------------------------------------------------------------------------


def test_import_route_rejects_a_bad_page_and_writes_nothing(client, serve, fresh_db):
    _login(client)
    serve(ERROR_PAGE_200)
    with pytest.raises(ValueError, match="nie zawiera treści oferty"):
        client.post("/crm/foreign-offers/import", json={"url": URL})
    assert state(fresh_db)["foreign_offers"] == []


def test_refresh_routes_report_a_bad_page_and_keep_the_offer(client, serve, fresh_db):
    _login(client)
    offer_id = client.post("/crm/foreign-offers/import", json={"url": URL}).get_json()["item"]["foreign_offer_id"]
    before = state(fresh_db)
    serve(EMPTY)

    with pytest.raises(ValueError, match="nie zawiera treści oferty"):
        client.post(f"/crm/foreign-offers/refresh/{offer_id}")
    refresh_all = client.post("/crm/foreign-offers/refresh-all").get_json()

    assert refresh_all["ok"] is False and refresh_all["error_count"] == 1
    assert "nie zawiera treści oferty" in refresh_all["errors"][0]["error"]
    assert state(fresh_db) == before
