"""Filesystem read-contract tests for modules/investment/functions.py.

Covers: list_offer_image_filenames, get_image_path, count_images,
video_exists, get_estate_description. These are the functions the PUBLIC
website relies on to resolve an offer's photos/video/description from
static/images/<id>/ — the exact contract a DATA_DIR migration must preserve.

Isolation (Storage Path Layer / Phase 2 update): modules/investment/functions.py
no longer caches a module-level IMAGES_DIR string -- every function calls
storage_paths.offer_dir(record_id) fresh, so it now redirects correctly
via DATA_DIR too. Legacy-mode isolation for these tests therefore
monkeypatches storage_paths.REPO_ROOT (the Phase 1 pattern), same as
tests/storage/conftest.py's isolated_storage_root fixture. All four
functions under test are @lru_cache'd, so caches are cleared before/after
every test and each test uses its own numeric id to avoid cross-test cache
pollution.
"""
import pytest

from modules.core import storage_paths
from modules.investment import functions as investment_functions


@pytest.fixture(autouse=True)
def isolated_images_dir(tmp_path, monkeypatch):
    monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
    isolated_root = tmp_path / "static" / "images"
    isolated_root.mkdir(parents=True)
    for fn in (
        investment_functions.list_offer_image_filenames,
        investment_functions.get_image_path,
        investment_functions.count_images,
        investment_functions.video_exists,
        investment_functions.get_estate_description,
    ):
        fn.cache_clear()
    yield isolated_root
    for fn in (
        investment_functions.list_offer_image_filenames,
        investment_functions.get_image_path,
        investment_functions.count_images,
        investment_functions.video_exists,
        investment_functions.get_estate_description,
    ):
        fn.cache_clear()


def _write_image(tmp_path, record_id, filename, content=b"fake-image"):
    offer_dir = tmp_path / str(record_id)
    offer_dir.mkdir(parents=True, exist_ok=True)
    (offer_dir / filename).write_bytes(content)
    return offer_dir


# ---------------------------------------------------------------------------
# list_offer_image_filenames
# ---------------------------------------------------------------------------

class TestListOfferImageFilenames:
    def test_no_folder_returns_empty_list(self, isolated_images_dir):
        assert investment_functions.list_offer_image_filenames(101) == []

    def test_empty_folder_returns_empty_list(self, isolated_images_dir):
        (isolated_images_dir / "102").mkdir()
        assert investment_functions.list_offer_image_filenames(102) == []

    def test_single_image(self, isolated_images_dir):
        _write_image(isolated_images_dir, 103, "image_103_url_0.jpg")
        assert investment_functions.list_offer_image_filenames(103) == ["image_103_url_0.jpg"]

    def test_multiple_images_sorted_numerically_not_lexicographically(self, isolated_images_dir):
        _write_image(isolated_images_dir, 104, "image_104_url_2.jpg")
        _write_image(isolated_images_dir, 104, "image_104_url_10.jpg")
        _write_image(isolated_images_dir, 104, "image_104_url_1.jpg")
        assert investment_functions.list_offer_image_filenames(104) == [
            "image_104_url_1.jpg",
            "image_104_url_2.jpg",
            "image_104_url_10.jpg",
        ]

    def test_all_allowed_extensions_accepted(self, isolated_images_dir):
        for idx, ext in enumerate((".jpg", ".jpeg", ".png", ".webp")):
            _write_image(isolated_images_dir, 105, f"image_105_url_{idx}{ext}")
        result = investment_functions.list_offer_image_filenames(105)
        assert len(result) == 4

    def test_disallowed_extension_ignored(self, isolated_images_dir):
        _write_image(isolated_images_dir, 106, "image_106_url_0.gif")
        assert investment_functions.list_offer_image_filenames(106) == []

    def test_non_image_files_ignored(self, isolated_images_dir):
        offer_dir = _write_image(isolated_images_dir, 107, "image_107_url_0.jpg")
        (offer_dir / "description_107.md").write_text("hello")
        (offer_dir / "notes.md").write_text("hi")
        (offer_dir / "video_107.mp4").write_bytes(b"x")
        assert investment_functions.list_offer_image_filenames(107) == ["image_107_url_0.jpg"]

    def test_filename_not_matching_prefix_ignored(self, isolated_images_dir):
        offer_dir = _write_image(isolated_images_dir, 108, "image_108_url_0.jpg")
        (offer_dir / "random.jpg").write_bytes(b"x")
        assert investment_functions.list_offer_image_filenames(108) == ["image_108_url_0.jpg"]

    def test_unparseable_index_sorts_last(self, isolated_images_dir):
        # _extract_offer_image_index() falls back to 10**9 on parse failure,
        # so a malformed suffix sorts after every well-formed one.
        _write_image(isolated_images_dir, 109, "image_109_url_abc.jpg")
        _write_image(isolated_images_dir, 109, "image_109_url_0.jpg")
        assert investment_functions.list_offer_image_filenames(109) == [
            "image_109_url_0.jpg",
            "image_109_url_abc.jpg",
        ]

    def test_result_is_cached_across_filesystem_changes(self, isolated_images_dir):
        # Documents current behaviour: lru_cache means a file added after the
        # first call is NOT picked up until cache_clear().
        assert investment_functions.list_offer_image_filenames(110) == []
        _write_image(isolated_images_dir, 110, "image_110_url_0.jpg")
        assert investment_functions.list_offer_image_filenames(110) == []


# ---------------------------------------------------------------------------
# get_image_path (needs a request context for url_for())
# ---------------------------------------------------------------------------

class TestGetImagePath:
    def test_fallback_to_no_image_svg_when_no_photos(self, isolated_images_dir, request_context):
        path = investment_functions.get_image_path(201)
        assert path.endswith("/static/images/no_image.svg")

    def test_returns_first_photo_url(self, isolated_images_dir, request_context):
        _write_image(isolated_images_dir, 202, "image_202_url_0.jpg")
        path = investment_functions.get_image_path(202)
        assert path.endswith("/static/images/202/image_202_url_0.jpg")

    def test_picks_lowest_index_among_multiple_photos(self, isolated_images_dir, request_context):
        _write_image(isolated_images_dir, 203, "image_203_url_5.jpg")
        _write_image(isolated_images_dir, 203, "image_203_url_1.jpg")
        path = investment_functions.get_image_path(203)
        assert path.endswith("/static/images/203/image_203_url_1.jpg")


# ---------------------------------------------------------------------------
# count_images
# ---------------------------------------------------------------------------

class TestCountImages:
    def test_zero_when_no_folder(self, isolated_images_dir):
        assert investment_functions.count_images(301) == 0

    def test_counts_only_matching_images(self, isolated_images_dir):
        offer_dir = _write_image(isolated_images_dir, 302, "image_302_url_0.jpg")
        _write_image(isolated_images_dir, 302, "image_302_url_1.png")
        (offer_dir / "description_302.md").write_text("x")
        assert investment_functions.count_images(302) == 2


# ---------------------------------------------------------------------------
# video_exists
# ---------------------------------------------------------------------------

class TestVideoExists:
    def test_false_when_no_folder(self, isolated_images_dir):
        assert investment_functions.video_exists(401) is False

    def test_false_when_folder_has_no_video(self, isolated_images_dir):
        _write_image(isolated_images_dir, 402, "image_402_url_0.jpg")
        assert investment_functions.video_exists(402) is False

    def test_true_for_mp4(self, isolated_images_dir):
        offer_dir = isolated_images_dir / "403"
        offer_dir.mkdir()
        (offer_dir / "video_403.mp4").write_bytes(b"x")
        assert investment_functions.video_exists(403) is True

    def test_true_for_webm(self, isolated_images_dir):
        offer_dir = isolated_images_dir / "404"
        offer_dir.mkdir()
        (offer_dir / "video_404.webm").write_bytes(b"x")
        assert investment_functions.video_exists(404) is True


# ---------------------------------------------------------------------------
# get_estate_description
# ---------------------------------------------------------------------------

class TestGetEstateDescription:
    def test_empty_string_when_missing(self, isolated_images_dir):
        assert investment_functions.get_estate_description(501) == ""

    def test_renders_markdown_to_html(self, isolated_images_dir):
        offer_dir = isolated_images_dir / "502"
        offer_dir.mkdir()
        (offer_dir / "description_502.md").write_text("**bold** text", encoding="utf-8")
        html = investment_functions.get_estate_description(502)
        assert "<strong>bold</strong>" in html
