"""
Backend API tests for Vitaevum language features
Tests:
- Language selector works via user preferences
- AI responds in English when user's preferredLanguage is 'en'
- UI translations are supported via user preferences
"""
import pytest
import requests
import os
import time

BASE_URL = os.environ.get('REACT_APP_BACKEND_URL', 'https://comfort-ai-2.preview.emergentagent.com')

# Test credentials
TEST_USER_EMAIL = "john.test.en@example.com"
TEST_USER_PASSWORD = "test123"
ADMIN_EMAIL = "admin"
ADMIN_PASSWORD = "admin123"

class TestAuthAPI:
    """Authentication endpoint tests"""
    
    def test_login_success(self):
        """Test login returns user with preferredLanguage"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "email": TEST_USER_EMAIL,
            "password": TEST_USER_PASSWORD
        })
        assert response.status_code == 200
        data = response.json()
        assert "token" in data
        assert "user" in data
        assert data["user"]["email"] == TEST_USER_EMAIL
        # Check preferredLanguage is returned
        assert "preferredLanguage" in data["user"]
        assert data["user"]["preferredLanguage"] == "en"
    
    def test_login_returns_user_context(self):
        """Test login returns user personal context"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "email": TEST_USER_EMAIL,
            "password": TEST_USER_PASSWORD
        })
        assert response.status_code == 200
        data = response.json()
        # Verify user context fields
        assert "nickname" in data["user"]
        assert "personalContext" in data["user"]
        
    def test_admin_login(self):
        """Test admin login"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "email": ADMIN_EMAIL,
            "password": ADMIN_PASSWORD
        })
        assert response.status_code == 200
        data = response.json()
        assert "token" in data
        assert data["user"]["isAdmin"] == True

    def test_login_invalid_credentials(self):
        """Test login with wrong password"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "email": "wrong@example.com",
            "password": "wrongpass"
        })
        assert response.status_code == 401


class TestUserProfileAPI:
    """User profile and language preference tests"""
    
    @pytest.fixture
    def auth_token(self):
        """Get authentication token"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "email": TEST_USER_EMAIL,
            "password": TEST_USER_PASSWORD
        })
        return response.json()["token"]
    
    def test_get_current_user(self, auth_token):
        """Test getting current user with language preference"""
        response = requests.get(f"{BASE_URL}/api/auth/me", 
            headers={"Authorization": f"Bearer {auth_token}"})
        assert response.status_code == 200
        data = response.json()
        assert data["email"] == TEST_USER_EMAIL
        assert data["preferredLanguage"] == "en"
        assert "nickname" in data
        assert "personalContext" in data
    
    def test_update_user_language_preference(self, auth_token):
        """Test updating user language preference"""
        # Update to French
        response = requests.put(f"{BASE_URL}/api/auth/me",
            headers={"Authorization": f"Bearer {auth_token}"},
            json={"preferredLanguage": "fr"})
        assert response.status_code == 200
        data = response.json()
        assert data["preferredLanguage"] == "fr"
        
        # Revert back to English
        response = requests.put(f"{BASE_URL}/api/auth/me",
            headers={"Authorization": f"Bearer {auth_token}"},
            json={"preferredLanguage": "en"})
        assert response.status_code == 200
        data = response.json()
        assert data["preferredLanguage"] == "en"


class TestProfilesAPI:
    """Profile CRUD tests"""
    
    @pytest.fixture
    def auth_token(self):
        """Get authentication token"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "email": TEST_USER_EMAIL,
            "password": TEST_USER_PASSWORD
        })
        return response.json()["token"]
    
    def test_get_profiles(self, auth_token):
        """Test getting user profiles"""
        response = requests.get(f"{BASE_URL}/api/profiles",
            headers={"Authorization": f"Bearer {auth_token}"})
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
    
    def test_create_profile(self, auth_token):
        """Test creating a profile"""
        response = requests.post(f"{BASE_URL}/api/profiles",
            headers={"Authorization": f"Bearer {auth_token}"},
            json={
                "name": "TEST_Dad",
                "relationship": "Father",
                "personalityTraits": ["Caring", "Wise"],
                "memories": "He loved fishing on weekends",
                "favoriteExpressions": "Champ!",
                "ageRange": "senior"
            })
        assert response.status_code == 200
        data = response.json()
        assert data["name"] == "TEST_Dad"
        assert data["relationship"] == "Father"
        
        # Clean up - delete the profile
        profile_id = data["id"]
        delete_response = requests.delete(f"{BASE_URL}/api/profiles/{profile_id}",
            headers={"Authorization": f"Bearer {auth_token}"})
        assert delete_response.status_code == 200


class TestChatAPI:
    """Chat/AI response tests"""
    
    @pytest.fixture
    def auth_token(self):
        """Get authentication token"""
        response = requests.post(f"{BASE_URL}/api/auth/login", json={
            "email": TEST_USER_EMAIL,
            "password": TEST_USER_PASSWORD
        })
        return response.json()["token"]
    
    @pytest.fixture
    def profile_id(self, auth_token):
        """Create a test profile and return its ID"""
        response = requests.post(f"{BASE_URL}/api/profiles",
            headers={"Authorization": f"Bearer {auth_token}"},
            json={
                "name": "TEST_Grandpa_EN",
                "relationship": "Grandfather",
                "personalityTraits": ["Kind", "Patient", "Wise"],
                "memories": "He always told stories about the war",
                "favoriteExpressions": "Take your time",
                "ageRange": "senior"
            })
        profile = response.json()
        yield profile["id"]
        # Cleanup
        requests.delete(f"{BASE_URL}/api/profiles/{profile['id']}",
            headers={"Authorization": f"Bearer {auth_token}"})
    
    def test_get_messages(self, auth_token, profile_id):
        """Test getting chat messages"""
        response = requests.get(f"{BASE_URL}/api/chat/{profile_id}/messages",
            headers={"Authorization": f"Bearer {auth_token}"})
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
    
    def test_send_message_ai_responds_in_english(self, auth_token, profile_id):
        """Test AI responds in English when user preferredLanguage is 'en'"""
        response = requests.post(f"{BASE_URL}/api/chat/{profile_id}/message",
            headers={"Authorization": f"Bearer {auth_token}"},
            json={"content": "Hello grandpa! How are you doing today?"})
        
        assert response.status_code == 200
        data = response.json()
        assert "message" in data
        assert data["message"]["role"] == "assistant"
        assert len(data["message"]["content"]) > 0
        
        # Check the response content - should be in English (not French)
        ai_response = data["message"]["content"]
        print(f"AI Response: {ai_response}")
        
        # Simple check - shouldn't contain common French words
        french_indicators = ["bonjour", "comment ça va", "bien sûr", "d'accord", "merci", "je suis"]
        response_lower = ai_response.lower()
        
        # The response should not be entirely in French
        has_french = any(indicator in response_lower for indicator in french_indicators)
        
        # Allow some flexibility but flag if entirely French
        if has_french:
            print(f"Warning: AI response may contain French: {ai_response}")
    
    def test_ai_uses_personal_context(self, auth_token, profile_id):
        """Test that AI uses user's personal context (nickname, family info)"""
        # Send message mentioning daughter (user has personalContext about daughter Emma)
        response = requests.post(f"{BASE_URL}/api/chat/{profile_id}/message",
            headers={"Authorization": f"Bearer {auth_token}"},
            json={"content": "I'm thinking about my daughter today, grandpa."})
        
        assert response.status_code == 200
        data = response.json()
        ai_response = data["message"]["content"]
        print(f"AI Response about daughter: {ai_response}")
        
        # The AI should potentially reference Emma or the daughter
        # This is a soft check since AI responses are non-deterministic


class TestAPIHealth:
    """API health checks"""
    
    def test_api_root(self):
        """Test API root endpoint"""
        response = requests.get(f"{BASE_URL}/api/")
        assert response.status_code == 200
        data = response.json()
        assert "message" in data


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])
