"""Unit tests for LegacyToMilvusAdapter."""

import pytest
from uuid import uuid4
from unittest.mock import Mock, patch, AsyncMock

from src.adapters.legacy_to_milvus_adapter import LegacyToMilvusAdapter


class TestLegacyToMilvusAdapter:
    """Tests for LegacyToMilvusAdapter class."""

    def test_adapter_can_be_imported(self):
        """Test that adapter can be imported."""
        assert LegacyToMilvusAdapter is not None

    def test_adapter_initializes_with_embedding_service(self):
        """Test that adapter initializes with EmbeddingService."""
        with patch('src.adapters.legacy_to_milvus_adapter.EmbeddingService'):
            adapter = LegacyToMilvusAdapter()
            assert hasattr(adapter, 'embedding_service')

    def test_text_element_conversion(self):
        """Test conversion of Text element type."""
        adapter = LegacyToMilvusAdapter()

        chunk = {
            'element_type': 'Text',
            'text': 'Sample text content',
            'keywords_text': '',
            'created_at': '2025-01-01',
            'metadata': {
                'sheet_name': 'Sheet1',
                'sheet_number': 1,
            }
        }

        document_id = uuid4()
        filename = 'test.xlsx'

        record = adapter._convert_chunk_to_record(chunk, document_id, filename)

        assert record['content']['text'] == 'Sample text content'
        assert record['content']['sheet_name'] == 'Sheet1'
        assert record['_source']['sheet'] == 'Sheet1'
        assert record['_legacy_metadata']['element_type'] == 'Text'

    def test_image_element_conversion(self):
        """Test conversion of Image element type."""
        adapter = LegacyToMilvusAdapter()

        chunk = {
            'element_type': 'Image',
            'text': 'Chart showing sales data',
            'keywords_text': '',
            'created_at': '2025-01-01',
            'metadata': {
                'sheet_name': 'Sheet1',
                'image_format': 'PNG',
                'width': 800,
                'height': 600,
                'position_key': 'Sheet1_A1',
                'cell_reference': 'A1',
            }
        }

        document_id = uuid4()
        filename = 'test.xlsx'

        record = adapter._convert_chunk_to_record(chunk, document_id, filename)

        assert record['content']['description'] == 'Chart showing sales data'
        assert record['content']['image_format'] == 'PNG'
        assert record['content']['width'] == 800
        assert record['content']['height'] == 600

    def test_row_number_extraction_from_cell_ref(self):
        """Test row number extraction from various cell reference formats."""
        adapter = LegacyToMilvusAdapter()

        # Test Image with cell reference
        metadata = {
            'position': {
                'from_cell': 'B25',
                'to_cell': 'D30'
            }
        }

        row = adapter._extract_row_number(metadata, 'Image')
        assert row == 25

        # Test Comment with explicit row
        metadata = {
            'row': 42,
            'cell_address': 'C42'
        }

        row = adapter._extract_row_number(metadata, 'Comment')
        assert row == 42

    def test_col_range_extraction(self):
        """Test column range extraction."""
        adapter = LegacyToMilvusAdapter()

        # Test with from and to cells
        metadata = {
            'position': {
                'from_cell': 'A1',
                'to_cell': 'C5'
            }
        }

        col_range = adapter._extract_col_range(metadata, 'Image')
        assert col_range == 'A1:C5'

        # Test with only from cell
        metadata = {
            'position': {
                'from_cell': 'B10'
            }
        }

        col_range = adapter._extract_col_range(metadata, 'Shape')
        assert col_range == 'B10'

    def test_embedding_text_preparation(self):
        """Test embedding text preparation."""
        adapter = LegacyToMilvusAdapter()

        chunk = {
            'text': 'This is the chunk text',
            'keywords_text': 'keyword1, keyword2'
        }

        text = adapter._prepare_embedding_text(chunk)
        assert text == 'This is the chunk text'

    def test_record_to_text_conversion(self):
        """Test converting record to text representation."""
        adapter = LegacyToMilvusAdapter()

        record = {
            'content': {
                'text': 'Sample content',
                'sheet_name': 'Sheet1',
                'sheet_number': 1
            }
        }

        text = adapter._record_to_text(record)
        assert 'text: Sample content' in text
        assert 'sheet_name: Sheet1' in text

    def test_text_truncation_for_milvus(self):
        """Test that text content is truncated for Milvus VARCHAR limit."""
        adapter = LegacyToMilvusAdapter()

        # Create record with very long text
        long_text = 'x' * 10000
        record = {
            'content': {'text': long_text},
            '_source': {'sheet': 'Sheet1', 'row': 1},
            '_legacy_metadata': {'element_type': 'Text'}
        }

        document_id = uuid4()
        embeddings = [[0.1] * 3072]  # Mock embedding

        entities = adapter.convert_to_milvus_entities(
            [record], embeddings, document_id, 'test.xlsx'
        )

        assert len(entities) == 1
        assert len(entities[0]['text_content']) <= 8000
        assert entities[0]['text_content'].endswith('...')

    @pytest.mark.asyncio
    async def test_adapt_chunks_integration(self):
        """Test full adapt_chunks workflow."""
        with patch('src.adapters.legacy_to_milvus_adapter.EmbeddingService') as MockEmbedding:
            # Mock embedding service
            mock_service = AsyncMock()
            mock_service.embed_batch = AsyncMock(return_value=[[0.1] * 3072, [0.2] * 3072])
            MockEmbedding.return_value = mock_service

            adapter = LegacyToMilvusAdapter()

            chunks = [
                {
                    'element_type': 'Text',
                    'text': 'Text chunk 1',
                    'keywords_text': '',
                    'created_at': '2025-01-01',
                    'metadata': {'sheet_name': 'Sheet1', 'sheet_number': 1}
                },
                {
                    'element_type': 'Image',
                    'text': 'Image description',
                    'keywords_text': '',
                    'created_at': '2025-01-01',
                    'metadata': {'sheet_name': 'Sheet1', 'image_format': 'PNG'}
                }
            ]

            result = await adapter.adapt_chunks(chunks, uuid4(), 'test.xlsx')

            assert 'records' in result
            assert 'embeddings' in result
            assert 'record_count' in result
            assert result['record_count'] == 2
            assert len(result['records']) == 2
            assert len(result['embeddings']) == 2
