"""CYPRUS-SYNC-1: the project name/address the source publishes as schema.org JSON-LD."""
import json

from integrations.cyprus_constructions import cyprus_project_details as cpd


def page(*blocks):
    return "<html><head>" + "".join(f'<script type="application/ld+json">{b}</script>' for b in blocks) + "</head></html>"


LISTING = json.dumps({
    "@context": "https://schema.org", "@type": "RealEstateListing", "name": "  Aloha   Homes ",
    "address": {"@type": "PostalAddress", "addressLocality": "Esentepe", "addressRegion": "Kyrenia"},
})


def test_reads_name_and_address_and_collapses_whitespace():
    assert cpd.extract_json_ld_listing(page(LISTING)) == {
        "name": "Aloha Homes", "address_locality": "Esentepe", "address_region": "Kyrenia"}


def test_only_present_keys_are_returned_and_no_country_is_invented():
    found = cpd.extract_json_ld_listing(page(json.dumps({"@type": "RealEstateListing", "name": "X"})))
    assert found == {"name": "X"}


def test_type_may_be_a_list_and_other_blocks_and_bad_json_are_skipped():
    listing = json.dumps({"@type": ["Product", "RealEstateListing"], "name": "Pearl Island Homes"})
    other = json.dumps({"@type": "Organization", "name": "Cyprus Constructions"})
    assert cpd.extract_json_ld_listing(page("{not json", other, listing)) == {"name": "Pearl Island Homes"}


def test_no_listing_gives_none():
    assert cpd.extract_json_ld_listing(page(json.dumps({"@type": "Organization", "name": "x"}))) is None
    assert cpd.extract_json_ld_listing("") is None


def test_extract_project_exposes_it_as_project_json_ld(monkeypatch):
    from tests.cyprus_constructions.test_unit_type_identity import PHUKET

    monkeypatch.setattr(cpd, "get_text", lambda session, url: page(LISTING))
    monkeypatch.setattr(cpd, "find_initial_script_urls", lambda html, url: [])
    monkeypatch.setattr(cpd, "discover_project_bundle", lambda *a, **k: ("https://cc.test/D.js", PHUKET))
    monkeypatch.setattr(cpd, "extract_page_sections", lambda *a, **k: ({}, {}))

    project = cpd.extract_project(object(), "https://www.cyprusconstructions.com/pl/Phuket_H&W_Resort")

    assert project["project"]["json_ld"]["name"] == "Aloha Homes"


def test_clear_text_cache_empties_the_page_cache():
    cpd._TEXT_CACHE["k"] = "v"
    cpd.clear_text_cache()
    assert cpd._TEXT_CACHE == {}
