"""External DATA_DIR contract tests -- Storage Path Layer / Phase 2.

Covers the full compatibility-mode matrix required by the Phase 2 spec:
  - DATA_DIR absent / empty -> legacy paths (Phase 1 behaviour, unchanged)
  - DATA_DIR set (absolute) -> external DATA_DIR/... layout
  - DATA_DIR set (relative) -> rejected with ValueError
  - CWD independence in both modes
  - resolver has no side effects (no directory creation)
  - every database/offer/agent/CRM-JSON/logs/backups resolver, in both modes

Isolation: exclusively monkeypatch.setenv("DATA_DIR", ...) (auto-reverted by
pytest at the end of each test) -- never chdir(), per the Phase 1 incident.
No test here ever writes into a real repo path: DATA_DIR always points at
tmp_path, and legacy-mode assertions in this file are read-only path-value
checks (no filesystem writes), consistent with the rest of the Phase 1
suite's isolated_storage_root pattern used elsewhere for write tests.
"""
import pytest

from modules.core import storage_paths


# ---------------------------------------------------------------------------
# Legacy mode: DATA_DIR absent / empty
# ---------------------------------------------------------------------------

class TestLegacyModeWhenDataDirAbsentOrEmpty:
    def test_data_dir_absent_returns_none(self, monkeypatch):
        monkeypatch.delenv("DATA_DIR", raising=False)
        assert storage_paths.data_dir() is None
        assert storage_paths.is_external_mode() is False

    def test_data_dir_empty_string_returns_none(self, monkeypatch):
        monkeypatch.setenv("DATA_DIR", "")
        assert storage_paths.data_dir() is None
        assert storage_paths.is_external_mode() is False

    @pytest.mark.parametrize("env_value", [None, ""])
    def test_all_resolvers_stay_on_legacy_paths(self, monkeypatch, env_value):
        if env_value is None:
            monkeypatch.delenv("DATA_DIR", raising=False)
        else:
            monkeypatch.setenv("DATA_DIR", env_value)

        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.offers_root_dir() == root / "static" / "images"
        assert storage_paths.offer_dir(42) == root / "static" / "images" / "42"
        assert storage_paths.agents_root_dir() == root / "static" / "images"
        assert storage_paths.agent_avatar_dir() == root / "static" / "images"
        assert storage_paths.crm_runtime_dir() == root / "InvestmentManager"
        assert storage_paths.alerts_dir() == root / "InvestmentManager" / "alerts"
        assert storage_paths.knowledge_center_dir() == root / "InvestmentManager" / "knowledge_center"
        assert storage_paths.schedules_dir() == root / "InvestmentManager" / "knowledge_center" / "schedules"
        assert storage_paths.scrapers_dir() == root / "InvestmentManager" / "scrapers"
        assert storage_paths.logs_dir() == root / "logs"
        # platform_logs_db_path() is NOT asserted here: it is permanently
        # overridden for the whole test session by tests/conftest.py's
        # log-write-protection fixture. Its legacy-mode contract
        # (logs/platform/platform_logs.db) is fixed by construction in
        # storage_paths.py and exercised directly in
        # tests/storage/test_platform_logs_identity.py.
        # VERSIONED_STATIC: unaffected regardless of DATA_DIR.
        assert storage_paths.images_dir() == root / "InvestmentWebsite" / "static" / "images"
        assert storage_paths.static_dir() == root / "InvestmentWebsite" / "static"


# ---------------------------------------------------------------------------
# External mode: DATA_DIR set to an absolute path
# ---------------------------------------------------------------------------

class TestExternalModeWhenDataDirSetAbsolute:
    def test_data_dir_returns_the_configured_path(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.data_dir() == tmp_path
        assert storage_paths.is_external_mode() is True

    def test_databases(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.instances_dir() == tmp_path / "databases"
        assert storage_paths.idb_db_path() == tmp_path / "databases" / "IDB.db"
        assert storage_paths.agents_db_path() == tmp_path / "databases" / "agents.db"
        assert storage_paths.foreign_offers_db_path() == tmp_path / "databases" / "foreign_offers.db"
        assert storage_paths.crm_clients_db_path() == tmp_path / "databases" / "crm_clients.db"
        # platform_logs_db_path() itself is NOT called here: the session
        # fixture in tests/conftest.py permanently replaces that exact
        # function object (by plain attribute assignment, not
        # monkeypatch.setattr, so it cannot auto-revert mid-session) to
        # guarantee no test can ever write to the real
        # logs/platform/platform_logs.db. Its Phase 2 external-mode
        # contract per storage_paths.py's source
        # (`return instances_dir() / "platform_logs.db"` when
        # is_external_mode()) is instead verified via that same expression
        # in test_platform_logs_db_path_external_mode_formula below.

    def test_platform_logs_db_path_external_mode_formula(self, tmp_path, monkeypatch):
        # See the long comment in test_databases above for why this checks
        # the formula rather than calling the (session-overridden)
        # platform_logs_db_path() directly: DATA_DIR/databases/ is where
        # instances_dir() already resolves to in external mode, and
        # platform_logs_db_path() is defined as instances_dir() /
        # "platform_logs.db" for exactly that reason (section 11).
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.instances_dir() / "platform_logs.db" == tmp_path / "databases" / "platform_logs.db"

    def test_database_backups(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.instances_backup_dir() == tmp_path / "databases" / "backups"

    def test_offers(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.offers_root_dir() == tmp_path / "offers"
        assert storage_paths.offer_dir(42) == tmp_path / "offers" / "42"
        assert storage_paths.offer_dir("42") == tmp_path / "offers" / "42"

    def test_agents(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.agents_root_dir() == tmp_path / "agents"
        assert storage_paths.agent_avatar_dir() == tmp_path / "agents"
        # Dedicated directory, no longer shared with offers/design assets.
        assert storage_paths.agent_avatar_dir() != storage_paths.offers_root_dir()
        assert storage_paths.agent_avatar_dir() != storage_paths.images_dir()

    def test_crm_json_alerts_knowledge_center_schedules(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.crm_runtime_dir() == tmp_path / "crm"
        assert storage_paths.alerts_dir() == tmp_path / "crm" / "alerts"
        assert storage_paths.knowledge_center_dir() == tmp_path / "crm" / "knowledge_center"
        assert storage_paths.knowledge_center_backups_dir() == tmp_path / "crm" / "knowledge_center" / "backups"
        assert storage_paths.knowledge_center_notes_path() == tmp_path / "crm" / "knowledge_center" / "all_notes.json"
        assert (
            storage_paths.knowledge_center_notifications_path()
            == tmp_path / "crm" / "knowledge_center" / "notifications.json"
        )
        assert storage_paths.schedules_dir() == tmp_path / "crm" / "knowledge_center" / "schedules"
        assert storage_paths.schedules_backups_dir() == tmp_path / "crm" / "knowledge_center" / "schedules" / "backups"

    def test_logs(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.logs_dir() == tmp_path / "logs"
        assert storage_paths.website_logs_dir() == tmp_path / "logs" / "website"
        assert storage_paths.error_log_path() == tmp_path / "logs" / "error.log"

    def test_scrapers(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        assert storage_paths.scrapers_dir() == tmp_path / "scrapers"
        assert storage_paths.scrapers_data_dir() == tmp_path / "scrapers" / "data"

    def test_versioned_static_assets_never_move_to_data_dir(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        # Design assets stay in the checkout even when DATA_DIR is set.
        assert storage_paths.static_dir() == storage_paths.repo_root() / "InvestmentWebsite" / "static"
        assert storage_paths.images_dir() == storage_paths.repo_root() / "InvestmentWebsite" / "static" / "images"
        assert storage_paths.static_data_dir() == storage_paths.repo_root() / "InvestmentWebsite" / "static" / "data"
        assert not str(storage_paths.images_dir()).startswith(str(tmp_path))

    def test_none_of_the_databases_point_into_the_repo_checkout(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        repo = str(storage_paths.repo_root())
        # platform_logs_db_path() deliberately excluded -- see the long
        # comment in test_databases above (session-overridden for safety).
        for db_path in (
            storage_paths.idb_db_path(),
            storage_paths.agents_db_path(),
            storage_paths.foreign_offers_db_path(),
            storage_paths.crm_clients_db_path(),
        ):
            assert not str(db_path).startswith(repo), db_path


# ---------------------------------------------------------------------------
# DATA_DIR relative -> explicit contract: rejected with ValueError.
# ---------------------------------------------------------------------------

class TestRelativeDataDirIsRejected:
    def test_relative_path_raises_value_error(self, monkeypatch):
        monkeypatch.setenv("DATA_DIR", "relative/data_dir")
        with pytest.raises(ValueError, match="absolute"):
            storage_paths.data_dir()

    def test_relative_path_raises_before_touching_disk(self, monkeypatch, tmp_path):
        # Even a syntactically relative-looking value under a real cwd must
        # not be silently resolved -- confirm no directory gets created as
        # a side effect of the failed call.
        monkeypatch.chdir(tmp_path)
        monkeypatch.setenv("DATA_DIR", "some_relative_name")
        with pytest.raises(ValueError):
            storage_paths.data_dir()
        assert not (tmp_path / "some_relative_name").exists()

    def test_dot_relative_path_also_rejected(self, monkeypatch):
        monkeypatch.setenv("DATA_DIR", "./data")
        with pytest.raises(ValueError):
            storage_paths.data_dir()


# ---------------------------------------------------------------------------
# CWD independence in external mode.
# ---------------------------------------------------------------------------

class TestExternalModeCwdIndependence:
    def test_changing_cwd_does_not_change_external_resolution(self, tmp_path, monkeypatch):
        other_cwd = tmp_path / "unrelated_cwd"
        other_cwd.mkdir()
        data_dir_path = tmp_path / "data"

        monkeypatch.setenv("DATA_DIR", str(data_dir_path))
        before = storage_paths.idb_db_path()

        monkeypatch.chdir(other_cwd)
        after = storage_paths.idb_db_path()

        assert before == after == data_dir_path / "databases" / "IDB.db"


# ---------------------------------------------------------------------------
# No side effects from the resolver itself, in either mode.
# ---------------------------------------------------------------------------

class TestResolverHasNoSideEffects:
    def test_offer_dir_does_not_create_the_folder_legacy_mode(self, tmp_path, monkeypatch):
        monkeypatch.setattr(storage_paths, "REPO_ROOT", tmp_path)
        monkeypatch.delenv("DATA_DIR", raising=False)
        result = storage_paths.offer_dir(123)
        assert not result.exists()

    def test_offer_dir_does_not_create_the_folder_external_mode(self, tmp_path, monkeypatch):
        monkeypatch.setenv("DATA_DIR", str(tmp_path))
        result = storage_paths.offer_dir(123)
        assert not result.exists()
        assert not tmp_path.exists() or list(tmp_path.iterdir()) == []

    def test_calling_every_resolver_creates_nothing_on_disk_external_mode(self, tmp_path, monkeypatch):
        data_dir_path = tmp_path / "data"
        monkeypatch.setenv("DATA_DIR", str(data_dir_path))

        storage_paths.instances_dir()
        storage_paths.instances_backup_dir()
        storage_paths.idb_db_path()
        storage_paths.offer_dir(1)
        storage_paths.agent_avatar_dir()
        storage_paths.alerts_dir()
        storage_paths.knowledge_center_dir()
        storage_paths.schedules_dir()
        storage_paths.logs_dir()
        storage_paths.platform_logs_db_path()
        storage_paths.scrapers_data_dir()

        assert not data_dir_path.exists()
