"""Contract tests for modules/connector.py::backup_idb_database and its
retention helper _cleanup_idb_backups.

B3: the backup is a transactionally consistent SQLite snapshot produced by
Connection.backup() (not a filesystem copy), so these tests use real SQLite
databases and assert *semantic* equivalence (schema + rows + quick_check),
never byte-for-byte equality. Isolated via isolated_storage_root, which
redirects storage_paths.REPO_ROOT to a tmp dir.
"""
import os
import sqlite3
import time

import pytest

from modules.connector import _cleanup_idb_backups, backup_idb_database


def _make_real_idb(isolated_storage_root, *, mode="DELETE", rows=(("initial",),), keep_open=False):
    """Create a real SQLite IDB.db under instances/ and return (path, conn).

    When keep_open=True the returned connection stays open so a WAL scenario's
    committed state is not auto-checkpointed away before the backup runs.
    """
    instances_dir = isolated_storage_root / "instances"
    instances_dir.mkdir(exist_ok=True)
    idb_path = instances_dir / "IDB.db"

    conn = sqlite3.connect(idb_path)
    conn.execute(f"PRAGMA journal_mode={mode}")
    conn.execute("CREATE TABLE EstateData (ID INTEGER PRIMARY KEY, v TEXT)")
    conn.executemany("INSERT INTO EstateData (v) VALUES (?)", rows)
    conn.commit()
    if keep_open:
        return idb_path, conn
    conn.close()
    return idb_path, None


def _read_values(db_path):
    conn = sqlite3.connect(db_path)
    try:
        return [r[0] for r in conn.execute("SELECT v FROM EstateData ORDER BY ID")]
    finally:
        conn.close()


def _quick_check(db_path):
    conn = sqlite3.connect(db_path)
    try:
        return conn.execute("PRAGMA quick_check").fetchone()[0]
    finally:
        conn.close()


class TestBackupCreation:
    def test_returns_none_when_source_db_missing(self, isolated_storage_root):
        assert not (isolated_storage_root / "instances" / "IDB.db").exists()
        assert backup_idb_database() is None

    def test_does_not_create_backup_dir_when_source_missing(self, isolated_storage_root):
        backup_idb_database()
        assert not (isolated_storage_root / "instances" / "backup").exists()

    def test_creates_backup_with_expected_naming_pattern(self, isolated_storage_root, monkeypatch):
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        _make_real_idb(isolated_storage_root)

        result_path = backup_idb_database()

        assert result_path is not None
        backup_dir = isolated_storage_root / "instances" / "backup"
        backups = list(backup_dir.glob("IDB_*.db"))
        assert len(backups) == 1
        stem = backups[0].stem  # IDB_YYYYMMDD_HHMMSS_ffffff
        timestamp_part = stem.removeprefix("IDB_")
        # YYYYMMDD_HHMMSS_ffffff = 8 + 1 + 6 + 1 + 6 = 22 chars
        assert len(timestamp_part) == 22
        assert timestamp_part[8] == "_" and timestamp_part[15] == "_"
        # No temp file left behind.
        assert list(backup_dir.glob("*.tmp")) == []

    def test_returned_path_is_a_string_to_completed_backup(self, isolated_storage_root, monkeypatch):
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        _make_real_idb(isolated_storage_root)
        result_path = backup_idb_database()
        assert isinstance(result_path, str)
        assert os.path.isfile(result_path) and result_path.endswith(".db")

    def test_rollback_journal_backup_has_schema_data_and_quick_check_ok(self, isolated_storage_root, monkeypatch):
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        _make_real_idb(isolated_storage_root, mode="DELETE", rows=(("a",), ("b",)))

        result_path = backup_idb_database()

        assert _quick_check(result_path) == "ok"
        assert _read_values(result_path) == ["a", "b"]

    def test_source_unchanged_and_still_usable_after_backup(self, isolated_storage_root, monkeypatch):
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        idb_path, _ = _make_real_idb(isolated_storage_root, rows=(("keep",),))

        backup_idb_database()

        # Source still has exactly its original data and accepts new writes.
        assert _read_values(idb_path) == ["keep"]
        conn = sqlite3.connect(idb_path)
        try:
            conn.execute("INSERT INTO EstateData (v) VALUES ('added')")
            conn.commit()
            assert conn.execute("SELECT COUNT(*) FROM EstateData").fetchone()[0] == 2
        finally:
            conn.close()


class TestWalDifferential:
    """The primary B3 regression: committed data living in the WAL must be in
    the backup. A shutil.copy2 of the main file only (pre-B3) would omit it."""

    def test_wal_committed_state_is_present_in_backup(self, isolated_storage_root, monkeypatch):
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        # keep_open: source connection stays open so WAL is not checkpointed
        # into the main file before the backup runs.
        idb_path, conn = _make_real_idb(
            isolated_storage_root, mode="WAL", rows=(("wal_committed",),), keep_open=True
        )
        try:
            # A -wal sidecar must exist and hold the committed state.
            assert (isolated_storage_root / "instances" / "IDB.db-wal").exists()

            result_path = backup_idb_database()

            assert _quick_check(result_path) == "ok"
            assert _read_values(result_path) == ["wal_committed"]
        finally:
            conn.close()


class TestSameSecondCollision:
    def test_two_backups_in_same_second_do_not_collide(self, isolated_storage_root, monkeypatch):
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        _make_real_idb(isolated_storage_root, rows=(("v",),))

        # Freeze the whole-second timestamp; microseconds still differ, so the
        # two filenames must differ deterministically without a real delay.
        import modules.connector as connector

        class _FrozenDatetime:
            _counter = 0

            @classmethod
            def now(cls):
                # Same second, distinct microseconds on each call.
                from datetime import datetime as _dt

                cls._counter += 1
                return _dt(2026, 1, 2, 3, 4, 5, cls._counter)

        monkeypatch.setattr(connector, "datetime", _FrozenDatetime)

        p1 = backup_idb_database()
        p2 = backup_idb_database()

        assert p1 != p2
        assert os.path.isfile(p1) and os.path.isfile(p2)
        assert _quick_check(p1) == "ok" and _quick_check(p2) == "ok"


class TestFailureAtomicity:
    def test_failure_after_temp_creation_publishes_nothing_and_cleans_temp(self, isolated_storage_root, monkeypatch):
        # Inject a failure at the publish step (os.replace), which runs after
        # the temp destination has been created and the snapshot written --
        # sqlite3.Connection is immutable so its .backup can't be patched;
        # os.replace is the deterministic post-temp failure point.
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        _make_real_idb(isolated_storage_root)
        backup_dir = isolated_storage_root / "instances" / "backup"
        backup_dir.mkdir(parents=True, exist_ok=True)
        survivor = backup_dir / "IDB_20260101_000000_000000.db"
        sqlite3.connect(survivor).close()

        import modules.connector as connector
        monkeypatch.setattr(connector.os, "replace",
                            lambda *a, **k: (_ for _ in ()).throw(OSError("sentinel publish failure")))

        with pytest.raises(OSError, match="sentinel publish failure"):
            backup_idb_database()

        # No stray temp, no new completed backup, survivor intact.
        assert list(backup_dir.glob("*.tmp")) == []
        completed = sorted(p.name for p in backup_dir.glob("IDB_*.db"))
        assert completed == ["IDB_20260101_000000_000000.db"]

    def test_failure_does_not_run_retention_cleanup(self, isolated_storage_root, monkeypatch):
        monkeypatch.delenv("IDB_BACKUP_KEEP_LAST", raising=False)
        _make_real_idb(isolated_storage_root)
        backup_dir = isolated_storage_root / "instances" / "backup"
        backup_dir.mkdir(parents=True, exist_ok=True)
        for i in range(3):
            p = backup_dir / f"IDB_2026010{i}_000000_000000.db"
            sqlite3.connect(p).close()

        called = {"cleanup": False}
        import modules.connector as connector
        monkeypatch.setattr(connector, "_cleanup_idb_backups",
                            lambda *a, **k: called.__setitem__("cleanup", True))
        monkeypatch.setattr(connector.os, "replace",
                            lambda *a, **k: (_ for _ in ()).throw(OSError("fail")))

        with pytest.raises(OSError):
            backup_idb_database()

        assert called["cleanup"] is False
        assert len(list(backup_dir.glob("IDB_*.db"))) == 3  # untouched


class TestCallerBestEffort:
    def test_trigger_idb_backup_swallows_failure_and_continues(self, isolated_storage_root, monkeypatch, app):
        from InvestmentManager.routes import offer_catalog

        monkeypatch.setattr(offer_catalog, "backup_idb_database",
                            lambda: (_ for _ in ()).throw(RuntimeError("boom")))
        warnings = []
        with app.app_context():
            monkeypatch.setattr(
                offer_catalog.current_app.logger, "warning",
                lambda *a, **k: warnings.append(a),
            )
            # Must not raise -- best-effort.
            offer_catalog.trigger_idb_backup()
        assert warnings, "expected a warning to be logged on backup failure"


class TestBackupRetentionCleanup:
    def test_cleanup_keeps_only_the_newest_keep_last_backups(self, tmp_path):
        backup_dir = tmp_path / "backup"
        backup_dir.mkdir()
        for i in range(5):
            p = backup_dir / f"IDB_2026010{i}_000000_000000.db"
            p.write_bytes(b"x")
            os.utime(p, (time.time() + i, time.time() + i))

        _cleanup_idb_backups(backup_dir, keep_last=2)

        remaining = sorted(p.name for p in backup_dir.glob("IDB_*.db"))
        assert remaining == ["IDB_20260103_000000_000000.db", "IDB_20260104_000000_000000.db"]

    def test_cleanup_keep_last_below_one_is_clamped_to_one(self, tmp_path):
        backup_dir = tmp_path / "backup"
        backup_dir.mkdir()
        for i in range(3):
            p = backup_dir / f"IDB_2026010{i}_000000_000000.db"
            p.write_bytes(b"x")
            os.utime(p, (time.time() + i, time.time() + i))

        _cleanup_idb_backups(backup_dir, keep_last=0)
        assert len(list(backup_dir.glob("IDB_*.db"))) == 1

    def test_cleanup_ignores_non_matching_and_temp_files(self, tmp_path):
        backup_dir = tmp_path / "backup"
        backup_dir.mkdir()
        (backup_dir / "unrelated.txt").write_text("keep me")
        (backup_dir / "IDB_20260101_000000_000000.db.tmp").write_bytes(b"partial")
        (backup_dir / "IDB_20260101_000000_000000.db").write_bytes(b"x")

        _cleanup_idb_backups(backup_dir, keep_last=0)

        assert (backup_dir / "unrelated.txt").exists()
        # The temp file does not match the IDB_*.db glob, so it is untouched.
        assert (backup_dir / "IDB_20260101_000000_000000.db.tmp").exists()

    def test_full_backup_flow_respects_env_configured_keep_last(self, isolated_storage_root, monkeypatch):
        monkeypatch.setenv("IDB_BACKUP_KEEP_LAST", "2")
        _make_real_idb(isolated_storage_root)
        backup_dir = isolated_storage_root / "instances" / "backup"

        for _ in range(4):
            backup_idb_database()
            time.sleep(0.001)

        remaining = list(backup_dir.glob("IDB_*.db"))
        assert len(remaining) <= 2
        for b in remaining:
            assert _quick_check(b) == "ok"
