"""
Integration tests for SentenceStore service.

These tests interact with real Supabase if env vars are present.
Skip gracefully if SUPABASE_URL / SUPABASE_SERVICE_KEY not set.
"""

import os
import pytest
import uuid
from datetime import datetime, timezone


# Skip all tests if Supabase not configured
pytestmark = pytest.mark.skipif(
    not (os.environ.get('SUPABASE_URL') and 
         (os.environ.get('SUPABASE_SERVICE_KEY') or os.environ.get('SUPABASE_KEY'))),
    reason="Supabase credentials not configured (SUPABASE_URL + SUPABASE_SERVICE_KEY required)"
)


class TestSentenceStoreIntegration:
    """Integration tests with real Supabase."""
    
    @pytest.fixture
    def store(self):
        """Get a fresh SentenceStore instance."""
        from veena3modal.services.sentence_store import SentenceStore
        return SentenceStore()
    
    def test_store_is_configured(self, store):
        """SentenceStore should be configured when env vars present."""
        assert store.is_configured() is True
    
    @pytest.mark.asyncio
    async def test_store_simple_record(self, store):
        """Store a simple record and verify it was inserted."""
        request_id = f"test-{uuid.uuid4()}"
        
        result = await store.store(
            request_id=request_id,
            text="Integration test: Hello world!",
            speaker="reet",
            stream=False,
            format="wav",
        )
        
        # Should succeed
        assert result is True
    
    @pytest.mark.asyncio
    async def test_store_with_all_fields(self, store):
        """Store a record with all optional fields."""
        request_id = f"test-full-{uuid.uuid4()}"
        
        result = await store.store(
            request_id=request_id,
            text="Full field test with temperature and seed.",
            speaker="lipakshi",
            stream=True,
            format="wav",
            temperature=0.9,
            top_k=100,
            top_p=0.95,
            max_tokens=2048,
            repetition_penalty=1.1,
            seed=12345,
            text_chunked=True,
            ttfb_ms=250,
            audio_duration_seconds=3.5,
        )
        
        assert result is True
    
    @pytest.mark.asyncio
    async def test_store_unicode_text(self, store):
        """Store Hindi/Unicode text."""
        request_id = f"test-hindi-{uuid.uuid4()}"
        
        result = await store.store(
            request_id=request_id,
            text="नमस्ते! यह एक परीक्षण है। हिंदी में टेक्स्ट-टू-स्पीच।",
            speaker="mitra",
            stream=True,
        )
        
        assert result is True
    
    @pytest.mark.asyncio
    async def test_store_long_text(self, store):
        """Store long text (up to 50K chars)."""
        request_id = f"test-long-{uuid.uuid4()}"
        
        # Create moderately long text (1000 chars to avoid hitting DB limits)
        long_text = "This is a test sentence. " * 40  # ~1000 chars
        
        result = await store.store(
            request_id=request_id,
            text=long_text,
            speaker="reet",
            text_chunked=True,
        )
        
        assert result is True
    
    @pytest.mark.asyncio
    async def test_fire_and_forget(self, store):
        """Test non-blocking fire-and-forget storage."""
        request_id = f"test-fandf-{uuid.uuid4()}"
        
        task = store.store_fire_and_forget(
            request_id=request_id,
            text="Fire and forget test",
            speaker="lipakshi",
        )
        
        # Should return a task
        assert task is not None
        
        # Wait for completion
        await task
        
        # Task should complete without error
        assert task.done()
        assert task.exception() is None


class TestSentenceStoreTableValidation:
    """Test table existence and schema validation."""
    
    @pytest.fixture
    def store(self):
        """Get a fresh SentenceStore instance."""
        from veena3modal.services.sentence_store import SentenceStore
        return SentenceStore()
    
    def test_table_exists(self, store):
        """Verify tts_requests table exists in Supabase."""
        if not store.is_configured():
            pytest.skip("Supabase not configured")
        
        try:
            # Try to select from table
            result = store.client.table('tts_requests').select('request_id').limit(1).execute()
            # If we got here without exception, table exists
            assert True
        except Exception as e:
            # Table might not exist yet - that's ok for initial setup
            pytest.skip(f"tts_requests table not found: {e}")

