"""Canonical no-image fallback contract."""
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[2]
CANONICAL_FALLBACK_URL = "/static/images/no_image.svg"


def _production_files():
    roots = [
        "InvestmentManager",
        "InvestmentWebsite",
        "blueprints",
        "middleware",
        "modules",
    ]
    for root_name in roots:
        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


def test_canonical_no_image_svg_exists_in_repo_static_images():
    path = REPO_ROOT / "InvestmentWebsite" / "static" / "images" / "no_image.svg"
    assert path.is_file()
    assert path.read_text(encoding="utf-8").lstrip().startswith("<svg")


def test_canonical_no_image_svg_is_served_by_flask(client):
    response = client.get(CANONICAL_FALLBACK_URL)
    assert response.status_code == 200
    assert response.mimetype == "image/svg+xml"
    assert b"<svg" in response.data[:200]


def test_no_production_source_references_no_image_png():
    offenders = []
    for path in _production_files():
        text = path.read_text(encoding="utf-8", errors="ignore")
        if "no_image.png" in text:
            offenders.append(str(path.relative_to(REPO_ROOT)))

    assert offenders == []


def test_offer_fallback_resolves_to_canonical_svg(tmp_path, monkeypatch, request_context):
    from modules.core import storage_paths
    from modules.investment import functions as investment_functions

    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    (tmp_path / "static" / "images").mkdir(parents=True)
    investment_functions.list_offer_image_filenames.cache_clear()
    investment_functions.get_image_path.cache_clear()

    try:
        url = investment_functions.get_image_path(88888)
    finally:
        investment_functions.list_offer_image_filenames.cache_clear()
        investment_functions.get_image_path.cache_clear()

    assert url.endswith(CANONICAL_FALLBACK_URL)


def test_agent_card_template_uses_canonical_svg(app):
    with app.test_request_context("/"):
        from flask import render_template

        html = render_template(
            "components/agent_card.html",
            agent_id=None,
            name="Zespol",
            surname="Investment",
            roles="",
            branch="",
            license="",
            phone="123456789",
            email="",
        )

    assert CANONICAL_FALLBACK_URL in html
