"""Contract tests for the THREE independent agent-avatar implementations
found by the storage audit:

  1. InvestmentManager/routes/dashboard.py::upload_avatar (writer) and
     _build_dashboard_context (reader #1: url_for, always assumes .jpg,
     gates on os.path.exists).
  2. InvestmentManager/routes/offer_catalog.py::_resolve_agent_avatar_url
     (reader #2: hand-built URL string, iterates jpg/jpeg/png/webp).
  3. templates/components/agent_card.html (reader #3: always requests .jpg
     first via url_for, then a client-side JS onerror cascade through
     .jpeg/.png/.webp/no_image.svg).

These three do NOT agree with each other (e.g. only #2 will ever find a
non-.jpg avatar server-side; #1 and #3 always assume .jpg exists). This test
file documents each contract independently -- it does not reconcile them,
per the audit's explicit instruction not to fix this yet.

Isolation: dashboard.py's avatar paths are bare relative strings (no
patchable constant), so these tests use isolated_storage_root exactly like
test_offer_image_mutations.py.
"""
import io

from tests.storage.conftest import login_as_crm_user


class TestUploadAvatar:
    def test_upload_writes_to_static_images_agent_id_dot_jpg(self, client, isolated_storage_root):
        # Precondition matching real production: static/images/ already
        # exists (see test_upload_fails_silently_when_static_images_dir_missing
        # below for what happens when it does not).
        (isolated_storage_root / "static" / "images").mkdir(parents=True)
        login_as_crm_user(client, user_id=42)
        resp = client.post(
            "/crm/upload_avatar",
            data={"avatar": (io.BytesIO(b"avatar-bytes"), "selfie.png")},
            content_type="multipart/form-data",
            follow_redirects=False,
        )
        assert resp.status_code in (302, 200)

        avatar_path = isolated_storage_root / "static" / "images" / "agent_42.jpg"
        assert avatar_path.exists()
        assert avatar_path.read_bytes() == b"avatar-bytes"

    def test_upload_always_names_file_dot_jpg_regardless_of_source_extension(self, client, isolated_storage_root):
        # Documents a real inconsistency: the uploaded file's actual format
        # (here a PNG's bytes) is saved under a .jpg filename with no
        # conversion or extension detection.
        (isolated_storage_root / "static" / "images").mkdir(parents=True)
        login_as_crm_user(client, user_id=43)
        client.post(
            "/crm/upload_avatar",
            data={"avatar": (io.BytesIO(b"\x89PNG-not-really-a-jpeg"), "photo.png")},
            content_type="multipart/form-data",
        )
        avatar_dir = isolated_storage_root / "static" / "images"
        assert (avatar_dir / "agent_43.jpg").exists()
        assert not (avatar_dir / "agent_43.png").exists()

    def test_upload_fails_silently_when_static_images_dir_missing(self, client, isolated_storage_root):
        # KNOWN ISSUE (discovered by this test): unlike
        # offer_catalog.py::upload_offer_image, dashboard.py::upload_avatar
        # never calls os.makedirs() before avatar.save(filepath). If
        # static/images/ does not already exist, FileStorage.save() raises
        # FileNotFoundError, which the route swallows into a flash() message
        # and a redirect -- the HTTP response looks like success (redirect),
        # but no file is ever written. This only "works" in production
        # because static/images/ already exists as a huge pre-existing
        # folder; a fresh DATA_DIR without it pre-created would silently
        # break every avatar upload.
        login_as_crm_user(client, user_id=45)
        resp = client.post(
            "/crm/upload_avatar",
            data={"avatar": (io.BytesIO(b"x"), "selfie.jpg")},
            content_type="multipart/form-data",
            follow_redirects=False,
        )
        assert resp.status_code in (302, 200)
        assert not (isolated_storage_root / "static" / "images" / "agent_45.jpg").exists()

    def test_no_file_field_is_a_noop(self, client, isolated_storage_root):
        login_as_crm_user(client, user_id=44)
        resp = client.post("/crm/upload_avatar", data={}, content_type="multipart/form-data")
        assert resp.status_code in (302, 200)
        assert not (isolated_storage_root / "static" / "images" / "agent_44.jpg").exists()


class TestBuildDashboardContextAvatarUrl:
    """dashboard.py::_build_dashboard_context — reader implementation #1."""

    def test_avatar_url_none_when_file_missing(self, client, isolated_storage_root):
        login_as_crm_user(client, user_id=51)
        resp = client.get("/crm/dashboard")
        assert resp.status_code == 200
        # No direct way to inspect the template context from the outside;
        # assert indirectly via the underlying helper instead.
        from InvestmentManager.routes.dashboard import _build_dashboard_context

        with client.session_transaction() as sess:
            sess["user_id"] = 51
        with client.application.test_request_context("/crm/dashboard"):
            from flask import session as flask_session

            flask_session["user_id"] = 51
            ctx = _build_dashboard_context()
        assert ctx["avatar_url"] is None

    def test_avatar_url_present_only_when_jpg_exists(self, isolated_storage_root, app):
        avatar_dir = isolated_storage_root / "static" / "images"
        avatar_dir.mkdir(parents=True)
        (avatar_dir / "agent_52.jpg").write_bytes(b"x")

        from InvestmentManager.routes.dashboard import _build_dashboard_context

        with app.test_request_context("/crm/dashboard"):
            from flask import session as flask_session

            flask_session["user_id"] = 52
            ctx = _build_dashboard_context()
        assert ctx["avatar_url"] is not None
        assert ctx["avatar_url"].endswith("/static/images/agent_52.jpg")

    def test_avatar_url_none_when_only_a_non_jpg_extension_exists(self, isolated_storage_root, app):
        # Documents the inconsistency with _resolve_agent_avatar_url below:
        # this reader ONLY ever checks the .jpg filename.
        avatar_dir = isolated_storage_root / "static" / "images"
        avatar_dir.mkdir(parents=True)
        (avatar_dir / "agent_53.png").write_bytes(b"x")

        from InvestmentManager.routes.dashboard import _build_dashboard_context

        with app.test_request_context("/crm/dashboard"):
            from flask import session as flask_session

            flask_session["user_id"] = 53
            ctx = _build_dashboard_context()
        assert ctx["avatar_url"] is None


class TestResolveAgentAvatarUrl:
    """offer_catalog.py::_resolve_agent_avatar_url — reader implementation
    #2. Unlike #1, this one checks jpg/jpeg/png/webp in that order and
    builds the URL by hand instead of via url_for().
    """

    def test_fallback_icon_when_agent_id_is_none(self, isolated_storage_root, app):
        from InvestmentManager.routes.offer_catalog import _resolve_agent_avatar_url

        with app.test_request_context("/"):
            url = _resolve_agent_avatar_url(None)
        assert url.endswith("/static/images/icon.png")

    def test_fallback_icon_when_no_avatar_file_exists(self, isolated_storage_root, app):
        from InvestmentManager.routes.offer_catalog import _resolve_agent_avatar_url

        with app.test_request_context("/"):
            url = _resolve_agent_avatar_url(61)
        assert url.endswith("/static/images/icon.png")

    def test_finds_jpg(self, isolated_storage_root, app):
        avatar_dir = isolated_storage_root / "static" / "images"
        avatar_dir.mkdir(parents=True)
        (avatar_dir / "agent_62.jpg").write_bytes(b"x")

        from InvestmentManager.routes.offer_catalog import _resolve_agent_avatar_url

        with app.test_request_context("/"):
            url = _resolve_agent_avatar_url(62)
        assert url.endswith("/static/images/agent_62.jpg")

    def test_finds_non_jpg_extension_unlike_build_dashboard_context(self, isolated_storage_root, app):
        # This is the concrete divergence between reader #1 and reader #2:
        # a PNG-only avatar is invisible to _build_dashboard_context but
        # visible here.
        avatar_dir = isolated_storage_root / "static" / "images"
        avatar_dir.mkdir(parents=True)
        (avatar_dir / "agent_63.webp").write_bytes(b"x")

        from InvestmentManager.routes.offer_catalog import _resolve_agent_avatar_url

        with app.test_request_context("/"):
            url = _resolve_agent_avatar_url(63)
        assert url.endswith("/static/images/agent_63.webp")

    def test_extension_priority_order_is_jpg_jpeg_png_webp(self, isolated_storage_root, app):
        avatar_dir = isolated_storage_root / "static" / "images"
        avatar_dir.mkdir(parents=True)
        (avatar_dir / "agent_64.png").write_bytes(b"x")
        (avatar_dir / "agent_64.webp").write_bytes(b"y")

        from InvestmentManager.routes.offer_catalog import _resolve_agent_avatar_url

        with app.test_request_context("/"):
            url = _resolve_agent_avatar_url(64)
        assert url.endswith("/static/images/agent_64.png")


class TestAgentCardTemplateFallback:
    """templates/components/agent_card.html — reader implementation #3.
    Server-side it always requests <agent_id>.jpg via url_for(); the
    jpeg/png/webp/no_image.svg cascade only happens client-side (JS
    onerror), so it cannot be exercised without a browser. This test
    documents the server-rendered contract only.
    """

    def test_initial_src_is_always_dot_jpg_via_url_for(self, app):
        with app.test_request_context("/"):
            from flask import render_template

            html = render_template(
                "components/agent_card.html",
                agent_id=71,
                name="Jan",
                surname="Kowalski",
                roles="",
                branch="",
                license="",
                phone="123456789",
                email="",
            )
        assert 'src="/static/images/agent_71.jpg"' in html
        # The onerror cascade's final fallback references no_image.svg.
        assert "no_image.svg" in html

    def test_no_agent_id_renders_no_image_svg_directly(self, 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 "/static/images/no_image.svg" in html
