"""
ShelfAI test suite.

Tests core functionality: shelf operations, index parsing,
transcript parsing, session management, and CLI commands.
"""



class TestMemoryLimits:
    """Tests for memory entry counting."""

    def test_count_entries(self, shelf_dir):
        from shelfai.core.safety import count_memory_entries

        test_file = shelf_dir / "memory" / "agent" / "test_count.md"
        test_file.write_text(
            "# Test\n\n## 2026-03-14\n- Entry one\n- Entry two\n\n## 2026-03-13\n- Entry three\n"
        )
        assert count_memory_entries(test_file) == 3

    def test_count_empty_file(self, shelf_dir):
        from shelfai.core.safety import count_memory_entries

        test_file = shelf_dir / "memory" / "agent" / "empty.md"
        test_file.write_text("# Empty\n")
        assert count_memory_entries(test_file) == 0

    def test_count_missing_file(self, tmp_path):
        from shelfai.core.safety import count_memory_entries

        assert count_memory_entries(tmp_path / "nope.md") == 0

    def test_count_skips_frontmatter(self, shelf_dir):
        from shelfai.core.safety import count_memory_entries

        test_file = shelf_dir / "memory" / "agent" / "fm_test.md"
        test_file.write_text(
            "---\ntitle: Test\n- not-an-entry\ntags: [a, b]\n---\n\n# Lessons\n\n- Real entry\n"
        )
        assert count_memory_entries(test_file) == 1

    def test_count_skips_nested_bullets(self, shelf_dir):
        from shelfai.core.safety import count_memory_entries

        test_file = shelf_dir / "memory" / "agent" / "nested_test.md"
        test_file.write_text(
            "# Lessons\n\n"
            "- Top level entry one\n"
            "  - Nested sub-detail\n"
            "  - Another nested\n"
            "- Top level entry two\n"
        )
        # Only the two top-level entries count (starting at column 0)
        assert count_memory_entries(test_file) == 2


# ──────────────────────────────────────────────
# Test: Session Manager — Failure Modes
# ──────────────────────────────────────────────


class FailingProvider:
    """Mock provider that raises exceptions."""

    def complete(self, system, user, max_tokens=4096):
        raise ConnectionError("API is down")


class GarbageProvider:
    """Mock provider that returns non-JSON garbage."""

    def __init__(self):
        self.calls = []

    def complete(self, system, user, max_tokens=4096):
        self.calls.append(True)
        return "Sorry, I can't help with that. Here's some thoughts:\n\nThe data looks..."


