"""SQLite path-resolution contract tests.

Confirms, for each of the 4 non-log SQLite databases the storage audit
found, exactly how its path is computed today (via the central
modules/core/storage_paths.py resolver, Storage Path Layer / Phase 1),
whether it auto-creates, and that these tests never touch the real files.
See test_platform_logs_identity.py for the 5th database (platform_logs.db).

Isolation: every consumer here calls storage_paths functions fresh at the
point of use (not a cached import-time constant), so monkeypatching
storage_paths.REPO_ROOT via the isolated_storage_root fixture redirects all
of them at once. monkeypatch.chdir() has NO effect any more -- see the
conftest.py module docstring for why.
"""
import sqlite3


class TestIdbAndAgentsDbPaths:
    """modules/connector.py::connection() -- resolves via
    storage_paths.idb_db_path() / storage_paths.agents_db_path(), no local
    caching, so isolated_storage_root (storage_paths.REPO_ROOT redirection)
    isolates it correctly.
    """

    def test_default_target_opens_instances_idb_db(self, isolated_storage_root):
        # Precondition matching real production: instances/ already exists
        # (see test_missing_instances_dir_raises_operational_error below for
        # what happens when it does not -- connection() itself does no
        # mkdir, unlike e.g. foreign_offers_store.py).
        (isolated_storage_root / "instances").mkdir()
        from modules.connector import connection

        conn = connection()
        try:
            conn.execute("CREATE TABLE probe (x INTEGER)")
            conn.commit()
        finally:
            conn.close()

        expected = isolated_storage_root / "instances" / "IDB.db"
        assert expected.is_file()

    def test_agents_target_opens_instances_agents_db(self, isolated_storage_root):
        (isolated_storage_root / "instances").mkdir()
        from modules.connector import connection

        conn = connection("agents")
        try:
            conn.execute("CREATE TABLE probe (x INTEGER)")
            conn.commit()
        finally:
            conn.close()

        expected = isolated_storage_root / "instances" / "agents.db"
        assert expected.is_file()
        assert not (isolated_storage_root / "instances" / "IDB.db").exists()

    def test_missing_instances_dir_raises_operational_error(self, isolated_storage_root):
        # KNOWN ISSUE (unchanged by the Phase 1 path refactor, deliberately
        # preserved): unlike InvestmentManager/foreign_offers_store.py and
        # crm_clients_store.py (both call
        # `.parent.mkdir(parents=True, exist_ok=True)` before connecting),
        # modules/connector.py::connection() does no mkdir at all.
        # sqlite3.connect() can create the *file*, but not a missing parent
        # directory. On a fresh DATA_DIR/checkout where 'instances/' has not
        # been created ahead of time, EVERY call to connection() (i.e.
        # almost every DB read/write in the whole app) raises
        # sqlite3.OperationalError instead of auto-provisioning storage.
        from modules.connector import connection

        assert not (isolated_storage_root / "instances").exists()
        try:
            connection()
            raised = False
        except sqlite3.OperationalError:
            raised = True
        assert raised is True


class TestForeignOffersDbPath:
    """InvestmentManager/foreign_offers_store.py -- resolves via
    storage_paths.foreign_offers_db_path() at call time."""

    def test_path_resolves_under_isolated_root_and_schema_auto_creates(self, isolated_storage_root):
        import InvestmentManager.foreign_offers_store as store
        from modules.core import storage_paths

        result_path = store.initialize_foreign_offers_db()

        assert result_path == storage_paths.foreign_offers_db_path()
        assert result_path == isolated_storage_root / "instances" / "foreign_offers.db"
        assert result_path.is_file()

        with sqlite3.connect(str(result_path)) as conn:
            tables = {
                row[0]
                for row in conn.execute(
                    "SELECT name FROM sqlite_master WHERE type='table'"
                ).fetchall()
            }
        assert "foreign_offers" in tables
        assert "foreign_offer_portal_sync" in tables

    def test_list_foreign_offers_on_empty_isolated_db_returns_empty_list(self, isolated_storage_root):
        import InvestmentManager.foreign_offers_store as store

        assert store.list_foreign_offers() == []


class TestCrmClientsDbPath:
    """InvestmentManager/crm_clients_store.py -- resolves via
    storage_paths.crm_clients_db_path() at call time."""

    def test_path_resolves_under_isolated_root_and_schema_auto_creates(self, isolated_storage_root):
        import InvestmentManager.crm_clients_store as store
        from modules.core import storage_paths

        result_path = store.initialize_crm_clients_db()

        assert result_path == storage_paths.crm_clients_db_path()
        assert result_path == isolated_storage_root / "instances" / "crm_clients.db"
        assert result_path.is_file()

        with sqlite3.connect(str(result_path)) as conn:
            tables = {
                row[0]
                for row in conn.execute(
                    "SELECT name FROM sqlite_master WHERE type='table'"
                ).fetchall()
            }
        assert "crm_clients" in tables
        assert "crm_client_meetings" in tables

    def test_create_and_get_client_round_trip_on_isolated_db(self, isolated_storage_root):
        import InvestmentManager.crm_clients_store as store

        created, duplicates = store.create_client(
            {"first_name": "Jan", "last_name": "Kowalski"},
            owner_agent_id=1,
            created_by_user_id=1,
        )
        assert duplicates == []
        assert created["first_name"] == "Jan"

        fetched = store.get_client(created["id"])
        assert fetched["last_name"] == "Kowalski"


class TestStorageDbPathResolversDirect:
    """Direct contract tests for modules/core/storage_paths.py's own DB
    path functions, independent of any consumer."""

    def test_all_db_paths_are_absolute(self):
        from modules.core import storage_paths

        for fn in (
            storage_paths.idb_db_path,
            storage_paths.agents_db_path,
            storage_paths.foreign_offers_db_path,
            storage_paths.crm_clients_db_path,
            storage_paths.platform_logs_db_path,
        ):
            assert fn().is_absolute(), fn.__name__

    def test_db_paths_redirect_under_isolated_root(self, isolated_storage_root):
        from modules.core import storage_paths

        assert storage_paths.idb_db_path() == isolated_storage_root / "instances" / "IDB.db"
        assert storage_paths.agents_db_path() == isolated_storage_root / "instances" / "agents.db"
        assert (
            storage_paths.foreign_offers_db_path()
            == isolated_storage_root / "instances" / "foreign_offers.db"
        )
        assert (
            storage_paths.crm_clients_db_path()
            == isolated_storage_root / "instances" / "crm_clients.db"
        )

    def test_repo_root_is_independent_of_cwd(self, tmp_path, monkeypatch):
        # Changing the process CWD must not change what repo_root() (and
        # everything derived from it) resolves to -- this is the whole
        # point of the Phase 1 refactor.
        from modules.core import storage_paths

        before = storage_paths.repo_root()
        monkeypatch.chdir(tmp_path)
        after = storage_paths.repo_root()
        assert before == after
        assert storage_paths.idb_db_path() == before / "instances" / "IDB.db"
