"""
Tests Bedrock avec mocking - Pas besoin d'AWS réel
"""

import pytest
from unittest.mock import MagicMock, patch
from kosty.services.bedrock_audit import BedrockAuditService
from kosty.services.sagemaker_audit import SageMakerAuditService


class TestBedrockAuditWithMocks:
    """Tests avec mocking des appels AWS"""
    
    def test_cost_audit_high_costs(self, mock_boto3_session):
        """Test détection de coûts élevés"""
        service = BedrockAuditService()
        
        results = service.cost_audit(mock_boto3_session, 'us-east-1', days=30)
        
        # Devrait détecter les coûts élevés (mock retourne ~$98)
        assert len(results) > 0
        
        # Vérifier le format du résultat
        issue = results[0]
        assert issue['service'] == 'Bedrock'
        assert issue['region'] == 'us-east-1'
        assert issue['type'] == 'cost'
        assert 'total_cost' in issue['details']
    
    def test_get_bedrock_costs(self, mock_boto3_session):
        """Test récupération des coûts"""
        service = BedrockAuditService()
        
        # Créer un mock client CE
        ce_client = mock_boto3_session.client('ce', region_name='us-east-1')
        
        result = service._get_bedrock_costs(ce_client, days=30, region='us-east-1')
        
        assert 'total_cost' in result
        assert 'period_days' in result
        assert result['period_days'] == 30
        assert result['total_cost'] > 0
    
    def test_security_audit_logging_disabled(self):
        """Test détection logging désactivé"""
        service = BedrockAuditService()
        
        # Mock session avec logging désactivé
        mock_session = MagicMock()
        mock_bedrock = MagicMock()
        
        from tests.fixtures.sample_responses import BEDROCK_LOGGING_CONFIG_DISABLED
        mock_bedrock.get_model_invocation_logging_configuration.return_value = BEDROCK_LOGGING_CONFIG_DISABLED
        
        mock_session.client.return_value = mock_bedrock
        
        results = service.security_audit(mock_session, 'us-east-1')
        
        # Devrait détecter que logging n'est pas activé
        assert len(results) > 0
        assert any('logging' in issue['issue'].lower() for issue in results)
    
    def test_create_issue_format(self, mock_boto3_session):
        """Test format de création d'issue"""
        service = BedrockAuditService()
        
        issue = service._create_issue(
            session=mock_boto3_session,
            region='us-east-1',
            resource_name='Test Resource',
            resource_id='test-id',
            issue='Test issue',
            type='cost',
            severity='HIGH',
            risk='Test risk',
            details={'key': 'value'}
        )
        
        # Vérifier tous les champs requis
        assert issue['service'] == 'Bedrock'
        assert issue['account_id'] == '123456789012'
        assert issue['region'] == 'us-east-1'
        assert issue['resource_name'] == 'Test Resource'
        assert issue['resource_id'] == 'test-id'
        assert issue['issue'] == 'Test issue'
        assert issue['type'] == 'cost'
        assert issue['severity'] == 'HIGH'
        assert issue['risk'] == 'Test risk'
        assert issue['details'] == {'key': 'value'}
        assert 'arn' in issue


class TestSageMakerAuditWithMocks:
    """Tests SageMaker avec mocking"""
    
    def test_detect_idle_endpoints(self, mock_boto3_session):
        """Test détection endpoints idle"""
        service = SageMakerAuditService()
        
        results = service.cost_audit(mock_boto3_session, 'us-east-1', days=7)
        
        # Devrait détecter au moins l'endpoint idle
        idle_issues = [r for r in results if 'idle' in r['issue'].lower()]
        assert len(idle_issues) > 0
        
        # Vérifier les détails
        issue = idle_issues[0]
        assert issue['service'] == 'SageMaker'
        assert 'monthly_cost' in issue['details']
        assert 'invocations' in issue['details']
    
    def test_get_invocation_count(self, mock_boto3_session):
        """Test récupération du nombre d'invocations"""
        service = SageMakerAuditService()
        
        # Test avec endpoint actif
        count = service._get_invocation_count(
            mock_boto3_session,
            'us-east-1',
            'test-endpoint-1',
            7
        )
        assert count == 5000
        
        # Test avec endpoint idle
        count = service._get_invocation_count(
            mock_boto3_session,
            'us-east-1',
            'idle-endpoint-2',
            7
        )
        assert count == 50