"""Wave B1: public offer cache coherence after CRM mutations.

Offer-specific read caches (image filenames/paths/counts, description, video
presence) were previously permanent lru_cache and stayed stale after a CRM
edit until process restart. B1 makes them:
  - immediately fresh in the writing worker (explicit invalidate_offer_caches
    after each successful CRM mutation), and
  - eventually fresh in other Passenger workers (bounded 30s TTL).

All runtime lives under a temporary DATA_DIR; real InvestmentData is never
touched.
"""
import io
import sqlite3
import os
from pathlib import Path
import subprocess
import sys

import pytest
from PIL import Image

from modules.investment import functions as F


def _jpg(path, color):
    path.parent.mkdir(parents=True, exist_ok=True)
    Image.new("RGB", (16, 16), color).save(path, "JPEG")


def _real_jpg_upload(color="blue", name="x.jpg"):
    buf = io.BytesIO()
    Image.new("RGB", (12, 12), color).save(buf, "JPEG")
    buf.seek(0)
    return {"image": (buf, name)}


@pytest.fixture()
def offer_runtime(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    dbs = tmp_path / "databases"
    dbs.mkdir()
    with sqlite3.connect(dbs / "IDB.db") as conn:
        conn.execute(
            "CREATE TABLE EstateData (ID INTEGER PRIMARY KEY, Status_oferty TEXT, "
            "Publikacja_na_portalu TEXT, ID_agenta INTEGER)"
        )
        conn.execute("INSERT INTO EstateData (ID, Status_oferty, ID_agenta) VALUES (7, 'aktywna', 101)")
        conn.execute("INSERT INTO EstateData (ID, Status_oferty, ID_agenta) VALUES (8, 'nieaktywna', 102)")
        conn.execute("CREATE TABLE offer_portal_sync (offer_id INTEGER, portal_key TEXT, is_published INTEGER, needs_update INTEGER)")
    with sqlite3.connect(dbs / "agents.db") as agents_conn:
        agents_conn.execute(
            "CREATE TABLE agents_v2 (id INTEGER, login TEXT, password_hash TEXT, first_name TEXT, "
            "access_level TEXT, last_name TEXT, email TEXT, phone TEXT, license TEXT, is_active INTEGER)"
        )
        agents_conn.execute("INSERT INTO agents_v2 (id, first_name, last_name, is_active) VALUES (101, 'Anna', 'Kowalska', 1)")
        agents_conn.execute("INSERT INTO agents_v2 (id, first_name, last_name, is_active) VALUES (102, 'Bartek', 'Nowak', 1)")
    o7 = tmp_path / "offers" / "7"
    _jpg(o7 / "image_7_url_0.jpg", "red")
    # Clear any state carried over from earlier tests in the process.
    F.invalidate_offer_caches()
    return tmp_path


def _login_master(client):
    with client.session_transaction() as sess:
        sess.update(user_id=1, access_level="master", first_name="B", last_name="M")


# ---------------------------------------------------------------------------
# A/B: image lifecycle -- writing worker is immediately fresh
# ---------------------------------------------------------------------------

class TestImageCacheCoherence:
    def test_upload_makes_cached_filename_list_immediately_fresh(self, client, offer_runtime):
        _login_master(client)
        assert F.list_offer_image_filenames(7) == ["image_7_url_0.jpg"]  # populate cache
        assert F.count_images(7) == 1

        resp = client.post("/crm/offers/images/7/upload", data=_real_jpg_upload(), content_type="multipart/form-data")
        assert resp.status_code == 200

        # No manual cache_clear: the route already invalidated.
        assert F.list_offer_image_filenames(7) == ["image_7_url_0.jpg", "image_7_url_1.jpg"]
        assert F.count_images(7) == 2

    def test_delete_makes_cached_list_immediately_fresh(self, client, offer_runtime):
        _login_master(client)
        client.post("/crm/offers/images/7/upload", data=_real_jpg_upload(), content_type="multipart/form-data")
        assert F.list_offer_image_filenames(7) == ["image_7_url_0.jpg", "image_7_url_1.jpg"]  # populate

        resp = client.post("/crm/offers/images/7/delete", json={"filename": "image_7_url_1.jpg"})
        assert resp.status_code == 200
        assert F.list_offer_image_filenames(7) == ["image_7_url_0.jpg"]

    def test_set_main_keeps_cache_coherent(self, client, offer_runtime):
        _login_master(client)
        client.post("/crm/offers/images/7/upload", data=_real_jpg_upload(), content_type="multipart/form-data")
        F.list_offer_image_filenames(7)  # populate a filesystem-only cache
        assert F.list_offer_image_filenames.cache_info().currsize == 1

        resp = client.post("/crm/offers/images/7/set-main", json={"filename": "image_7_url_1.jpg"})
        assert resp.status_code == 200
        # The route invalidated: the stale cache entry is gone.
        assert F.list_offer_image_filenames.cache_info().currsize == 0


# ---------------------------------------------------------------------------
# C/D: description / status through real routes
# ---------------------------------------------------------------------------

class TestOfferDataCacheCoherence:
    @pytest.mark.parametrize(
        "func_name",
        ["add_offer", "update_offer", "mark_offer_sold", "delete_offer"],
    )
    def test_schema_heavy_mutation_routes_are_wired_to_invalidation(self, func_name):
        # These routes require the full IDB schema (EstateData + Localization +
        # Sold + portal sync) to run end-to-end; their cache-invalidation wiring
        # is asserted at source level. The behavioral invalidation contract is
        # covered by the toggle and image-route tests above (real routes,
        # minimal schema).
        import inspect

        from InvestmentManager.routes import offer_catalog

        source = inspect.getsource(getattr(offer_catalog, func_name))
        assert "invalidate_offer_caches()" in source

    def test_toggle_status_invalidates_caches(self, client, offer_runtime):
        _login_master(client)
        F.count_images(7)
        assert F.count_images.cache_info().currsize >= 1
        resp = client.post("/crm/offers/toggle/7")
        assert resp.status_code == 200
        assert F.count_images.cache_info().currsize == 0

    def test_active_agents_facet_is_fresh_after_status_toggle(self, client, offer_runtime):
        # get_active_agents() reflects DISTINCT ID_agenta of active offers.
        # Offer 7 (agent 101) active, offer 8 (agent 102) inactive.
        _login_master(client)
        initial = {row[0] for row in F.get_active_agents()}
        assert initial == {101}  # populates the 120s cache; 102 not yet active

        # Real CRM mutation: toggle offer 8 -> active, so agent 102 now has an
        # active offer. Without invalidating get_active_agents this stays {101}.
        resp = client.post("/crm/offers/toggle/8")
        assert resp.status_code == 200

        after = {row[0] for row in F.get_active_agents()}
        assert after == {101, 102}  # immediately fresh in the writing worker


# ---------------------------------------------------------------------------
# Owner API
# ---------------------------------------------------------------------------

class TestInvalidateOfferCachesAPI:
    OFFER_CACHES = [
        "count_images", "get_estate_description", "video_exists",
        "get_image_path", "list_offer_image_filenames",
        "get_normalized_filter_options", "get_unique_filter_values",
        "get_catalog_price_bounds", "get_catalog_area_bounds",
        "get_active_agents", "get_estates_count_by_wojewodztwo",
    ]

    def test_clears_every_owned_offer_cache(self, offer_runtime, request_context):
        # Populate the simple per-id caches.
        F.count_images(7)
        F.list_offer_image_filenames(7)
        F.video_exists(7)
        F.get_image_path(7)
        F.get_estate_description(7)
        assert any(getattr(F, n).cache_info().currsize > 0 for n in ("count_images", "get_image_path"))

        F.invalidate_offer_caches()

        for name in self.OFFER_CACHES:
            assert getattr(F, name).cache_info().currsize == 0, name

    def test_does_not_clear_agent_caches(self, offer_runtime):
        # Agent caches are owned/cleared by agents.py, not by this API.
        from unittest.mock import patch

        cleared = []
        with patch.object(F.get_agents, "cache_clear", side_effect=lambda: cleared.append("agents")), \
             patch.object(F.get_branches, "cache_clear", side_effect=lambda: cleared.append("branches")):
            F.invalidate_offer_caches()
        assert cleared == []

    def test_does_not_touch_offerservice_foreign_cache(self, offer_runtime):
        from InvestmentWebsite.offers.service import OfferService

        svc = OfferService()
        svc._cache["catalog:tripinvest"] = {"expires_at": 9e9, "value": [1]}
        F.invalidate_offer_caches()
        assert "catalog:tripinvest" in svc._cache


# ---------------------------------------------------------------------------
# 30s TTL -- deterministic via a stubbed monotonic clock (no sleeps)
# ---------------------------------------------------------------------------

def _fresh_ttl_process(node):
    """Use a fresh real decorator closure, never rewind another test's TTL."""
    if os.environ.get("INVESTMENT_TTL_CHILD") == node:
        return False
    env = dict(os.environ, INVESTMENT_TTL_CHILD=node)
    result = subprocess.run(
        [sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider",
         "-o", "addopts=", __file__ + "::TestOfferCacheTtl::" + node],
        cwd=Path(__file__).resolve().parents[2], env=env,
        capture_output=True, text=True, timeout=60,
    )
    assert result.returncode == 0, result.stdout + result.stderr
    return True


class TestOfferCacheTtl:
    def test_offer_cache_expires_after_thirty_seconds(self, offer_runtime, monkeypatch):
        if _fresh_ttl_process("test_offer_cache_expires_after_thirty_seconds"):
            return
        clock = {"t": 1_000_000_000.0}
        monkeypatch.setattr(F.time, "monotonic", lambda: clock["t"])
        F.invalidate_offer_caches()

        o7 = offer_runtime / "offers" / "7"
        assert F.list_offer_image_filenames(7) == ["image_7_url_0.jpg"]

        # Add a file directly on disk (bypassing the route/invalidation).
        _jpg(o7 / "image_7_url_1.jpg", "green")

        # Before TTL: still cached (stale) -- proves it is genuinely cached.
        clock["t"] = 1_000_000_029.0
        assert F.list_offer_image_filenames(7) == ["image_7_url_0.jpg"]

        # After 30s: self-heals (other-worker coherence path).
        clock["t"] = 1_000_000_031.0
        assert F.list_offer_image_filenames(7) == ["image_7_url_0.jpg", "image_7_url_1.jpg"]

    def test_cache_clear_forces_immediate_refresh(self, offer_runtime, monkeypatch):
        if _fresh_ttl_process("test_cache_clear_forces_immediate_refresh"):
            return
        clock = {"t": 2_000_000_000.0}
        monkeypatch.setattr(F.time, "monotonic", lambda: clock["t"])
        F.invalidate_offer_caches()

        o7 = offer_runtime / "offers" / "7"
        assert F.count_images(7) == 1
        _jpg(o7 / "image_7_url_1.jpg", "blue")
        # Same instant, but explicit clear -> immediate refresh.
        F.invalidate_offer_caches()
        assert F.count_images(7) == 2


# ---------------------------------------------------------------------------
# Failure path -- a failed mutation must not run success-path invalidation
# ---------------------------------------------------------------------------

def test_failed_image_upload_does_not_invalidate(client, offer_runtime):
    _login_master(client)
    F.list_offer_image_filenames(7)  # populate
    before = F.list_offer_image_filenames.cache_info()

    # Missing 'image' part -> 400 before any success/invalidation.
    resp = client.post("/crm/offers/images/7/upload", data={}, content_type="multipart/form-data")
    assert resp.status_code == 400

    after = F.list_offer_image_filenames.cache_info()
    assert after.currsize == before.currsize == 1  # cache untouched
