from pathlib import Path

import pytest


ROOT = Path(__file__).resolve().parents[2]
WEBSITE = ROOT / "InvestmentWebsite"
STATIC = WEBSITE / "static"
FORBIDDEN_PUBLIC_ORIGINS = (
    "fonts.googleapis.com",
    "fonts.gstatic.com",
    "cdn.jsdelivr.net",
    "unpkg.com",
)


def _public_source_files():
    yield from (WEBSITE / "templates").rglob("*.html")
    for extension in ("*.js", "*.css"):
        for path in STATIC.rglob(extension):
            if "vendor" not in path.relative_to(STATIC).parts:
                yield path


def test_public_source_has_no_google_fonts_jsdelivr_or_unpkg_dependencies():
    offenders = []
    for path in _public_source_files():
        source = path.read_text(encoding="utf-8-sig")
        matches = [origin for origin in FORBIDDEN_PUBLIC_ORIGINS if origin in source]
        if matches:
            offenders.append((path.relative_to(ROOT).as_posix(), matches))

    assert offenders == []


def test_local_font_contract_contains_every_used_weight_and_subset():
    css_path = STATIC / "css" / "fonts.css"
    css = css_path.read_text(encoding="utf-8")

    assert css.count("@font-face") == 10
    for weight in (200, 400, 600, 700, 900):
        assert css.count(f"font-weight: {weight};") == 2
        for subset in ("latin", "latin-ext"):
            filename = f"titillium-web-{weight}-{subset}.woff2"
            font = STATIC / "fonts" / "titillium-web" / "v19" / filename
            assert font.read_bytes().startswith(b"wOF2")
            assert filename in css
    assert (STATIC / "fonts" / "titillium-web" / "v19" / "OFL.txt").is_file()


def test_local_library_contract_is_versioned_complete_and_licensed():
    alpine = STATIC / "vendor" / "alpinejs" / "3.17.5"
    leaflet = STATIC / "vendor" / "leaflet" / "1.9.4"

    assert (alpine / "alpine.min.js").stat().st_size > 50_000
    assert "3.17.5" in (alpine / "alpine.min.js").read_text(encoding="utf-8")
    assert (alpine / "LICENSE.md").is_file()
    assert "Leaflet 1.9.4" in (leaflet / "leaflet.js").read_text(encoding="utf-8")[:200]
    assert (leaflet / "leaflet.css").stat().st_size > 10_000
    assert (leaflet / "leaflet.js.map").stat().st_size > 200_000
    assert (leaflet / "LICENSE.txt").is_file()
    for filename in (
        "layers.png",
        "layers-2x.png",
        "marker-icon.png",
        "marker-icon-2x.png",
        "marker-shadow.png",
    ):
        assert (leaflet / "images" / filename).read_bytes().startswith(b"\x89PNG\r\n\x1a\n")


@pytest.mark.parametrize(
    ("url", "content_type"),
    [
        ("/static/css/fonts.css", "text/css"),
        ("/static/fonts/titillium-web/v19/titillium-web-400-latin.woff2", "font/woff2"),
        ("/static/vendor/alpinejs/3.17.5/alpine.min.js", "javascript"),
        ("/static/vendor/leaflet/1.9.4/leaflet.css", "text/css"),
        ("/static/vendor/leaflet/1.9.4/leaflet.js", "javascript"),
        ("/static/vendor/leaflet/1.9.4/images/marker-icon.png", "image/png"),
    ],
)
def test_self_hosted_assets_are_served_with_expected_content_type(app, url, content_type):
    response = app.test_client().get(url)

    assert response.status_code == 200
    assert content_type in response.content_type


def test_public_page_uses_local_font_once_without_creating_a_session(app):
    response = app.test_client().get("/nieruchomosci/cypr")
    html = response.get_data(as_text=True)

    assert response.status_code == 200
    assert html.count('/static/css/fonts.css') == 1
    assert not any(origin in html for origin in FORBIDDEN_PUBLIC_ORIGINS)
    assert not any(value.lower().startswith("session=") for value in response.headers.getlist("Set-Cookie"))


def test_templates_and_dynamic_loader_reference_only_local_versioned_libraries():
    expected = {
        "templates/o_nas.html": "vendor/alpinejs/3.17.5/alpine.min.js",
        "templates/franczyza.html": "vendor/alpinejs/3.17.5/alpine.min.js",
        "templates/hiszpania.html": "vendor/leaflet/1.9.4/leaflet.js",
        "templates/hiszpania_region.html": "vendor/leaflet/1.9.4/leaflet.js",
        "templates/dubaj.html": "vendor/leaflet/1.9.4/leaflet.js",
        "templates/cyprus/cyprus_project.html": "vendor/leaflet/1.9.4/leaflet.js",
        "static/js/investment/poland.js": "/static/vendor/leaflet/1.9.4/leaflet.js",
    }
    for relative, reference in expected.items():
        source = (WEBSITE / relative).read_text(encoding="utf-8-sig")
        assert reference in source, relative
