"""PREPROD-4: the CRM's public link for a foreign offer.

foreign_offers.js builds it in the browser. The helper is run under node (no DOM, no
network) by cutting exactly the two functions out of the real file. The technical
foreign_offers.source_url ("<project URL>#unit-type=...") is a sync identity, not a page.
"""
import base64
import json
import pathlib
import shutil
import subprocess

import pytest


JS = pathlib.Path(__file__).resolve().parents[2] / "InvestmentManager" / "static" / "js" / "foreign_offers.js"
NODE = shutil.which("node")

pytestmark = pytest.mark.skipif(NODE is None, reason="node is not available")

HARNESS = r"""
const fs = require("fs");
const src = fs.readFileSync(process.argv[1], "utf8");
const start = src.indexOf("function foreignOffersEncodeOfferToken");
const end = src.indexOf("function foreignOffersMatchesSearch");
if (start < 0 || end < start) throw new Error("helpers not found");
eval(src.slice(start, end) + "; globalThis.build = foreignOffersBuildInvestmentOfferUrl;");
const items = JSON.parse(process.argv[2]);
console.log(JSON.stringify(items.map((item) => build(item))));
"""


def build_links(*items):
    out = subprocess.run([NODE, "-e", HARNESS, str(JS), json.dumps(list(items))], capture_output=True, text=True, check=True)
    return json.loads(out.stdout)


def token_of(url):
    return base64.urlsafe_b64encode(url.encode("utf-8")).decode("ascii").rstrip("=")


CYPRUS = "https://www.cyprusconstructions.com/pl/Aloha_homes"
PHUKET = "https://www.cyprusconstructions.com/pl/Phuket_H&W_Resort"
UNIT = "#unit-type=%5B%22aloha_homes%22%2C%22Phase%20I%22%2C%22type-a%22%5D"


def test_a_cyprus_offer_links_to_the_cyprus_project_page_not_spain():
    (link,) = build_links({"source_platform": "cyprus_constructions", "source_url": CYPRUS + UNIT})

    assert link == f"/nieruchomosci/cypr/projekt/{token_of(CYPRUS)}"
    assert "hiszpania" not in link


def test_the_token_is_the_project_url_without_the_unit_type_fragment():
    (a, b) = build_links({"source_platform": "cyprus_constructions", "source_url": CYPRUS + UNIT},
                         {"source_platform": "cyprus_constructions", "source_url": CYPRUS + "#unit-type=other"})
    assert a == b   # every unit type of a project opens the same project page (no unit-type deep link exists)


def test_phuket_with_an_ampersand_round_trips_and_resolves(client):
    (link,) = build_links({"source_platform": "cyprus_constructions", "source_url": PHUKET + UNIT})

    assert link == f"/nieruchomosci/cypr/projekt/{token_of(PHUKET)}"
    token = link.rsplit("/", 1)[1]
    assert "&" not in token and "=" not in token
    response = client.get(link)
    assert response.status_code == 200
    assert PHUKET in response.get_data(as_text=True).replace("&amp;", "&")
    from InvestmentWebsite.blueprints.cyprus.cyprus import _decode_project_token
    assert _decode_project_token(token) == PHUKET


def test_a_plain_project_url_without_a_fragment_also_works():
    (link,) = build_links({"source_platform": "cyprus_constructions", "source_url": CYPRUS})
    assert link == f"/nieruchomosci/cypr/projekt/{token_of(CYPRUS)}"


AVARTEN = "https://avarten.com/property/laya-courtyard-at-dubai-studio-city/"


def test_an_avarten_offer_links_to_the_dubai_offer_page(client):
    (link,) = build_links({"source_platform": "avarten", "source_url": AVARTEN})

    assert link == f"/nieruchomosci/dubaj/oferta/{token_of(AVARTEN)}"
    assert "hiszpania" not in link
    from InvestmentWebsite.blueprints.avarten.avarten import _decode_offer_token
    assert _decode_offer_token(link.rsplit("/", 1)[1]) == AVARTEN   # the route decodes the exact source_url


def test_tripinvest_keeps_the_spain_link_and_unknown_sources_the_historical_fallback():
    url = "https://tripinvest.pl/oferta/apartament-75156"
    links = build_links({"source_platform": "tripinvest", "source_url": url},
                        {"source_platform": "something_new", "source_url": url},
                        {"source_url": url})
    assert links == [f"/nieruchomosci/hiszpania/oferta/{token_of(url)}"] * 3


def test_each_platform_gets_its_own_route_family():
    trip, avarten, cyprus = build_links(
        {"source_platform": "tripinvest", "source_url": "https://t.example/x"},
        {"source_platform": "avarten", "source_url": AVARTEN},
        {"source_platform": "cyprus_constructions", "source_url": CYPRUS + UNIT})
    assert trip.startswith("/nieruchomosci/hiszpania/oferta/")
    assert avarten.startswith("/nieruchomosci/dubaj/oferta/")
    assert cyprus == f"/nieruchomosci/cypr/projekt/{token_of(CYPRUS)}"


def test_no_source_url_gives_no_link():
    assert build_links({"source_platform": "cyprus_constructions", "source_url": ""}, {"source_platform": "cyprus_constructions"}) == ["", ""]
