"""Tests for MCP server tool functions."""

import json

from takeseek.server import save_frame_descriptions, _get_db, _db_instance


class TestSaveFrameDescriptions:
    """Test the save_frame_descriptions tool (DB round-trip)."""

    def test_save_and_retrieve(self, sample_clip):
        db, clip_id = sample_clip

        # Patch the module-level _get_db to return our test db
        import takeseek.server as srv
        original = srv._db_instance
        srv._db_instance = db

        try:
            descriptions = json.dumps([
                {"timestamp": 0.0, "description": "A person walking in a park"},
                {"timestamp": 30.0, "description": "A close-up of flowers"},
            ])

            result = json.loads(save_frame_descriptions(clip_id, descriptions))

            assert result["ok"] is True
            assert result["clip_id"] == clip_id
            assert result["saved"] == 2
            assert result["index_status"] == "complete"

            # Verify data persisted in DB
            stored = db.get_frame_descriptions(clip_id)
            assert len(stored) == 2
            assert stored[0]["timestamp"] == 0.0
            assert "walking" in stored[0]["description"]
            assert stored[1]["timestamp"] == 30.0

            # Verify clip status updated
            clip = db.get_clip_by_id(clip_id)
            assert clip["index_status"] == "complete"
        finally:
            srv._db_instance = original

    def test_invalid_json(self, sample_clip):
        db, clip_id = sample_clip

        import takeseek.server as srv
        original = srv._db_instance
        srv._db_instance = db

        try:
            result = json.loads(save_frame_descriptions(clip_id, "not valid json"))
            assert "error" in result
            assert "Invalid JSON" in result["error"]
        finally:
            srv._db_instance = original

    def test_missing_fields(self, sample_clip):
        db, clip_id = sample_clip

        import takeseek.server as srv
        original = srv._db_instance
        srv._db_instance = db

        try:
            result = json.loads(save_frame_descriptions(clip_id, '[{"timestamp": 0.0}]'))
            assert "error" in result
            assert "description" in result["error"]
        finally:
            srv._db_instance = original

    def test_clip_not_found(self, sample_clip):
        db, _ = sample_clip

        import takeseek.server as srv
        original = srv._db_instance
        srv._db_instance = db

        try:
            result = json.loads(save_frame_descriptions(99999, "[]"))
            assert "error" in result
            assert "not found" in result["error"]
        finally:
            srv._db_instance = original

    def test_idempotent_overwrite(self, sample_clip):
        """Saving descriptions twice replaces the first set."""
        db, clip_id = sample_clip

        import takeseek.server as srv
        original = srv._db_instance
        srv._db_instance = db

        try:
            first = json.dumps([{"timestamp": 0.0, "description": "First pass"}])
            save_frame_descriptions(clip_id, first)

            second = json.dumps([
                {"timestamp": 0.0, "description": "Second pass"},
                {"timestamp": 15.0, "description": "New frame"},
            ])
            save_frame_descriptions(clip_id, second)

            stored = db.get_frame_descriptions(clip_id)
            assert len(stored) == 2
            assert stored[0]["description"] == "Second pass"
        finally:
            srv._db_instance = original
