"""Static design-image contracts after the WebP optimization pass.

Covers the asset renames/conversions (wojewodztwa/*.webp, homepage hero,
Cyprus Constructions partner logo) and guards against production source
pointing at a static image that no longer exists.
"""
import re
from pathlib import Path

import pytest

from tests.investmentmanager.test_integrator_export_engine_removed import (
    _create_legacy_homepage_databases,
)

REPO_ROOT = Path(__file__).resolve().parents[2]
IMAGES_DIR = REPO_ROOT / "InvestmentWebsite" / "static" / "images"
CYPRUS_LOGO_URL = "/static/images/cyprusconstructions_logo.webp"
WOJEWODZTWA_SLUGS = {
    "dolnoslaskie",
    "kujawsko-pomorskie",
    "opolskie",
    "pomorskie",
    "slaskie",
    "zachodniopomorskie",
}

_STATIC_IMAGE_REF = re.compile(
    r"""(?:/static/images/|filename=["']images/)([A-Za-z0-9_./\-]+\.(?:jpe?g|png|webp|svg|gif))"""
)
_HTML_COMMENT = re.compile(r"<!--.*?-->", re.S)


def _production_files():
    for root_name in ("InvestmentManager", "InvestmentWebsite", "blueprints", "middleware", "modules"):
        root = REPO_ROOT / root_name
        if not root.exists():
            continue
        for path in root.rglob("*"):
            if path.is_file() and path.suffix.lower() in {".py", ".js", ".html"}:
                yield path


@pytest.fixture()
def homepage_client(tmp_path, monkeypatch):
    from modules.core import storage_paths
    from modules.core.app_factory import create_app
    from modules.investment import functions as investment_functions

    monkeypatch.delenv("DATA_DIR", raising=False)
    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    _create_legacy_homepage_databases(tmp_path)
    investment_functions.get_estates_count_by_wojewodztwo.cache_clear()
    investment_functions.get_agent_card_data.cache_clear()

    app = create_app()
    app.config.update(TESTING=True)
    yield app.test_client()

    investment_functions.get_estates_count_by_wojewodztwo.cache_clear()
    investment_functions.get_agent_card_data.cache_clear()


def test_canonical_cyprus_logo_exists_and_typo_asset_is_gone():
    assert (IMAGES_DIR / "cyprusconstructions_logo.webp").is_file()
    assert not (IMAGES_DIR / "cyprusconstrutions_logo.jpeg").exists()


def test_homepage_contains_cyprus_partner_linking_to_cyprus_hub(homepage_client, app):
    resp = homepage_client.get("/")
    assert resp.status_code == 200
    html = resp.get_data(as_text=True)

    with app.test_request_context("/"):
        from flask import url_for

        cyprus_url = url_for("cyprus.cyprus_hub")

    match = re.search(r'<a href="([^"]+)" data-partner="cyprus-constructions"[^>]*>(.*?)</a>', html, re.S)
    assert match, "Cyprus partner card missing from homepage"
    assert match.group(1) == cyprus_url
    assert CYPRUS_LOGO_URL in match.group(2)


def test_cyprus_partner_target_resolves_to_registered_route(app):
    adapter = app.url_map.bind("localhost")
    endpoint, _ = adapter.match("/nieruchomosci/cypr")
    assert endpoint == "cyprus.cyprus_hub"


def test_wojewodztwa_images_are_webp_only():
    names = {p.name for p in (IMAGES_DIR / "wojewodztwa").iterdir() if p.is_file()}
    assert names == {f"{slug}.webp" for slug in WOJEWODZTWA_SLUGS}


def test_homepage_tiles_and_poland_map_use_wojewodztwa_webp(homepage_client, app):
    html = homepage_client.get("/").get_data(as_text=True)
    assert "/static/images/wojewodztwa/pomorskie.webp" in html
    assert "wojewodztwa/pomorskie.jpg" not in html

    from InvestmentWebsite.services.poland_helpers import build_poland_map

    with app.test_request_context("/"):
        poland_map = build_poland_map([{"slug": "slaskie", "name": "slaskie", "count": 1}])

    assert poland_map["region"]["bg_image"] == "/static/images/main_strona_glowna.webp"
    assert poland_map["regions"][0]["bg_image"] == "/static/images/wojewodztwa/slaskie.webp"


def test_canonical_homepage_hero_is_webp(homepage_client):
    assert (IMAGES_DIR / "main_strona_glowna.webp").is_file()
    assert not (IMAGES_DIR / "main_strona_glowna.jpg").exists()
    html = homepage_client.get("/").get_data(as_text=True)
    assert "main_strona_glowna.jpg" not in html


def test_active_production_static_image_references_exist():
    missing = []
    for path in _production_files():
        text = path.read_text(encoding="utf-8", errors="ignore")
        comments = [m.span() for m in _HTML_COMMENT.finditer(text)]
        for m in _STATIC_IMAGE_REF.finditer(text):
            name = m.group(1)
            # Offer media (<id>/...) and agent avatars are runtime data, not design assets.
            if re.match(r"^(\d+/|agent_)", name):
                continue
            if any(start <= m.start() < end for start, end in comments):
                continue
            if not (IMAGES_DIR / name).is_file():
                missing.append(f"{path.relative_to(REPO_ROOT)}: {name}")

    assert missing == []


@pytest.mark.parametrize(
    "url",
    [
        CYPRUS_LOGO_URL,
        "/static/images/wojewodztwa/zachodniopomorskie.webp",
        "/static/images/main_strona_glowna.webp",
        "/static/images/biuro_kedzierzyn.webp",
        "/static/images/uk_flag.webp",
    ],
)
def test_converted_assets_are_served_as_webp(client, url):
    resp = client.get(url)
    assert resp.status_code == 200
    assert resp.mimetype == "image/webp"
    assert resp.data[:4] == b"RIFF" and resp.data[8:12] == b"WEBP"


@pytest.mark.parametrize(
    "url, mimetype",
    [
        ("/static/images/avarten.webp", "image/webp"),
        ("/static/images/no_image.svg", "image/svg+xml"),
    ],
)
def test_static_images_have_deterministic_content_type(client, url, mimetype):
    # create_app() registers .webp itself; the host mimetypes table
    # (Python < 3.13, Windows registry) must not decide this.
    resp = client.get(url)
    assert resp.status_code == 200
    assert resp.headers["Content-Type"].startswith(mimetype)
