"""Direct contract tests for modules/core/storage_paths.py itself --
independent of any consumer module.

Storage Path Layer / Phase 1: this locks in that every resolver (a) points
at exactly the same physical location the old, scattered hardcoded strings
used to (repo_root-relative, matching the pre-refactor layout one-for-one),
(b) returns an absolute path, and (c) is immune to the process's current
working directory.
"""
from pathlib import Path

from modules.core import storage_paths


def test_repo_root_matches_base_dir_from_config():
    from modules.core.config import BASE_DIR

    assert storage_paths.repo_root() == Path(BASE_DIR)


def test_repo_root_is_absolute():
    assert storage_paths.repo_root().is_absolute()


def test_changing_cwd_does_not_change_repo_root(tmp_path, monkeypatch):
    before = storage_paths.repo_root()
    monkeypatch.chdir(tmp_path)
    after = storage_paths.repo_root()
    assert before == after
    assert after.is_absolute()


class TestAllResolversAreAbsoluteAndDeriveFromRepoRoot:
    """Every single path function must be absolute and must live under
    repo_root() -- this is the actual guarantee the whole module exists to
    provide."""

    def _all_zero_arg_resolvers(self):
        import inspect

        for name in dir(storage_paths):
            if name.startswith("_") or name in ("REPO_ROOT",):
                continue
            obj = getattr(storage_paths, name)
            if inspect.isfunction(obj):
                try:
                    sig = inspect.signature(obj)
                except (TypeError, ValueError):
                    continue
                if all(p.default is not inspect.Parameter.empty or p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD) for p in sig.parameters.values()):
                    yield name, obj

    def test_every_zero_arg_resolver_returns_an_absolute_path_under_repo_root(self):
        # platform_logs_dir/platform_logs_db_path are deliberately,
        # permanently overridden for the whole test session by
        # tests/conftest.py's log-write-protection fixture (so no test can
        # ever write to the real logs/platform/platform_logs.db) -- see
        # test_platform_logs_identity.py for their structural contract
        # instead.
        session_overridden = {"platform_logs_dir", "platform_logs_db_path"}
        # data_dir() legitimately returns None in legacy mode (its contract
        # is Path | None, exercised separately in Phase 2 tests) and
        # is_external_mode() returns bool, not Path -- both out of scope
        # for this "every plain path resolver" scan.
        non_path_resolvers = {"data_dir", "is_external_mode"}
        resolvers = list(self._all_zero_arg_resolvers())
        assert len(resolvers) >= 15, "expected most of the module's public API to be zero-arg resolvers"

        for name, fn in resolvers:
            if name in session_overridden or name in non_path_resolvers:
                continue
            result = fn()
            if name == "repo_root":
                continue
            assert isinstance(result, Path), name
            assert result.is_absolute(), name
            assert str(result).startswith(str(storage_paths.repo_root())), name


class TestPhysicalLocationsMatchThePreRefactorLayout:
    """Phase 1's hard requirement: exactly the same physical locations as
    before, nothing moved."""

    def test_instances_databases(self):
        root = storage_paths.repo_root()
        assert storage_paths.instances_dir() == root / "instances"
        assert storage_paths.instances_backup_dir() == root / "instances" / "backup"
        assert storage_paths.idb_db_path() == root / "instances" / "IDB.db"
        assert storage_paths.agents_db_path() == root / "instances" / "agents.db"
        assert storage_paths.foreign_offers_db_path() == root / "instances" / "foreign_offers.db"
        assert storage_paths.crm_clients_db_path() == root / "instances" / "crm_clients.db"

    def test_offer_storage_and_agent_avatars(self):
        root = storage_paths.repo_root()
        assert storage_paths.static_dir() == root / "InvestmentWebsite" / "static"
        assert storage_paths.images_dir() == root / "InvestmentWebsite" / "static" / "images"
        assert storage_paths.offer_dir(123) == root / "static" / "images" / "123"
        assert storage_paths.offer_dir("456") == root / "static" / "images" / "456"
        # Agent avatars live in the same physical directory as offer photos
        # today -- not a subfolder.
        assert storage_paths.agent_avatar_dir() == root / "static" / "images"

    def test_static_data(self):
        root = storage_paths.repo_root()
        assert storage_paths.static_data_dir() == root / "InvestmentWebsite" / "static" / "data"

    def test_logs_and_platform_log_db_single_source(self):
        # platform_logs_dir()/platform_logs_db_path() are not asserted here
        # against repo_root() -- they are permanently redirected for the
        # whole test session by tests/conftest.py's log-write-protection
        # fixture. Their real-layout contract (relative to logs/) is fixed
        # by construction in storage_paths.py itself (platform_logs_dir()
        # is defined as logs_dir() / "platform") and exercised for real via
        # test_platform_logs_identity.py.
        root = storage_paths.repo_root()
        assert storage_paths.logs_dir() == root / "logs"
        assert storage_paths.website_logs_dir() == root / "logs" / "website"
        assert storage_paths.error_log_path() == root / "logs" / "error.log"

    def test_alerts_knowledge_center_and_schedules(self):
        root = storage_paths.repo_root()
        im = root / "InvestmentManager"
        assert storage_paths.investmentmanager_dir() == im
        assert storage_paths.alerts_dir() == im / "alerts"
        assert storage_paths.knowledge_center_dir() == im / "knowledge_center"
        assert storage_paths.knowledge_center_backups_dir() == im / "knowledge_center" / "backups"
        assert storage_paths.knowledge_center_notes_path() == im / "knowledge_center" / "all_notes.json"
        assert (
            storage_paths.knowledge_center_notifications_path()
            == im / "knowledge_center" / "notifications.json"
        )
        assert storage_paths.knowledge_center_manual_leads_path() == im / "knowledge_center" / "manual_leads.json"
        assert storage_paths.schedules_dir() == im / "knowledge_center" / "schedules"
        assert storage_paths.schedules_backups_dir() == im / "knowledge_center" / "schedules" / "backups"

    def test_scrapers_data(self):
        root = storage_paths.repo_root()
        im = root / "InvestmentManager"
        assert storage_paths.scrapers_dir() == im / "scrapers"
        assert storage_paths.scrapers_data_dir() == im / "scrapers" / "data"


class TestOfferDirAcceptsIntOrStr:
    def test_int_offer_id(self):
        assert storage_paths.offer_dir(42).name == "42"

    def test_string_offer_id(self):
        assert storage_paths.offer_dir("42").name == "42"


def test_module_has_no_import_time_side_effects(tmp_path):
    # Reload the module against a throwaway REPO_ROOT candidate and confirm
    # nothing was created on disk merely by importing/using it read-only.
    import importlib

    from modules.core import storage_paths as sp

    original_root = sp.REPO_ROOT
    try:
        sp.REPO_ROOT = tmp_path
        # Calling every resolver must not create anything.
        sp.instances_dir()
        sp.images_dir()
        sp.offer_dir(1)
        sp.platform_logs_db_path()
        sp.alerts_dir()
        sp.knowledge_center_dir()
        assert list(tmp_path.iterdir()) == []
    finally:
        sp.REPO_ROOT = original_root
