"""
Production-ready patterns and advanced usage examples
"""
from typing import List, Dict, Any

import sys
import os
# Add parent directory to path to import aisert
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from aisert import Aisert, AisertConfig, AisertError

# Example 1: Testing Framework Integration
def test_llm_response_quality():
    """Integration with testing frameworks like pytest"""
    def validate_llm_output(response: str, expected_keywords: List[str]) -> bool:
        try:
            result = (
                Aisert(response)
                .assert_contains(expected_keywords, strict=True)
                .assert_tokens(500, strict=True)
                .collect()
            )
            return result.status
        except AisertError:
            return False
    
    # Usage in tests
    assert validate_llm_output("Python is great for data science", ["Python", "data"])
    print("✅ Test framework integration works")

# Example 2: CI/CD Pipeline Validation
def cicd_validation_pipeline():
    """Validate LLM responses in CI/CD pipelines"""
    responses_to_validate = [
        "Generated documentation for the API endpoint",
        "Code review comments generated by AI",
        "Automated test descriptions"
    ]
    
    config = AisertConfig(
        token_model="gpt-3.5-turbo",
        model_provider="openai"
    )
    
    failed_validations = []
    
    for i, response in enumerate(responses_to_validate):
        try:
            result = (
                Aisert(response, config)
                .assert_tokens(200, strict=False)
                .assert_contains(["generated", "AI", "automated"], strict=False)
                .collect()
            )
            if not result.status:
                failed_validations.append(f"Response {i+1}")
        except Exception as e:
            failed_validations.append(f"Response {i+1}: {e}")
    
    if failed_validations:
        print(f"❌ CI/CD Pipeline failed: {failed_validations}")
    else:
        print("✅ CI/CD Pipeline validation passed")

# Example 3: A/B Testing LLM Responses
def ab_test_llm_responses():
    """Compare different LLM responses for quality"""
    response_a = "Our product helps businesses streamline operations and increase efficiency."
    response_b = "This solution optimizes workflows and boosts productivity for companies."
    
    def score_response(response: str) -> Dict[str, Any]:
        result = (
            Aisert(response)
            .assert_contains(["business", "efficiency", "productivity"], strict=False)
            .assert_tokens(100, strict=False)
            .assert_semantic_matches("business productivity solution", 0.6, strict=False)
            .collect()
        )
        
        return {
            "response": response,
            "overall_score": result.status,
            "details": result.rules
        }
    
    score_a = score_response(response_a)
    score_b = score_response(response_b)
    
    print(f"Response A Score: {score_a['overall_score']}")
    print(f"Response B Score: {score_b['overall_score']}")

# Example 4: Content Quality Monitoring
class ContentQualityMonitor:
    """Monitor LLM-generated content quality in production"""
    
    def __init__(self):
        self.config = AisertConfig(
            token_model="gpt-3.5-turbo",
            model_provider="openai"
        )
        self.quality_metrics = {
            "total_responses": 0,
            "passed_validation": 0,
            "failed_validation": 0
        }
    
    def validate_content(self, content: str, requirements: Dict[str, Any]) -> bool:
        """Validate content against dynamic requirements"""
        self.quality_metrics["total_responses"] += 1
        
        try:
            aisert = Aisert(content, self.config)
            
            # Dynamic validation based on requirements
            if "keywords" in requirements:
                aisert.assert_contains(requirements["keywords"], strict=False)
            
            if "max_tokens" in requirements:
                aisert.assert_tokens(requirements["max_tokens"], strict=False)
            
            if "semantic_match" in requirements:
                aisert.assert_semantic_matches(
                    requirements["semantic_match"]["text"],
                    requirements["semantic_match"]["threshold"],
                    strict=False
                )
            
            result = aisert.collect()
            
            if result.status:
                self.quality_metrics["passed_validation"] += 1
                return True
            else:
                self.quality_metrics["failed_validation"] += 1
                return False
                
        except Exception as e:
            self.quality_metrics["failed_validation"] += 1
            print(f"Validation error: {e}")
            return False
    
    def get_quality_report(self) -> Dict[str, Any]:
        """Get quality metrics report"""
        total = self.quality_metrics["total_responses"]
        if total == 0:
            return {"quality_score": 0, "metrics": self.quality_metrics}
        
        quality_score = self.quality_metrics["passed_validation"] / total
        return {
            "quality_score": quality_score,
            "metrics": self.quality_metrics
        }

# Example 5: Custom Validation Rules
def custom_validation_example():
    """Demonstrate extensible validation patterns"""
    
    def validate_customer_service_response(response: str) -> bool:
        """Custom validation for customer service responses"""
        requirements = {
            "keywords": ["thank", "help", "assist"],
            "max_tokens": 150,
            "semantic_match": {
                "text": "helpful customer service response",
                "threshold": 0.7
            }
        }
        
        monitor = ContentQualityMonitor()
        return monitor.validate_content(response, requirements)
    
    # Test responses
    good_response = "Thank you for contacting us. I'm here to help and assist you with your inquiry."
    bad_response = "I don't know. Figure it out yourself."
    
    print(f"Good response valid: {validate_customer_service_response(good_response)}")
    print(f"Bad response valid: {validate_customer_service_response(bad_response)}")

# Example 6: Performance Monitoring
def performance_monitoring():
    """Monitor validation performance in production"""
    import time
    
    # More realistic test data with varying content
    responses = [
        "This is a comprehensive customer service response that includes helpful information and detailed explanations for the user's inquiry.",
        "Our AI-powered system has successfully processed your request and generated appropriate documentation for your needs.",
        "The automated testing framework validates code quality and ensures robust performance across different environments and scenarios.",
        "Machine learning algorithms analyze patterns in user behavior to provide personalized recommendations and improve overall experience.",
        "Quality assurance processes include multiple validation steps to ensure accuracy, reliability, and compliance with industry standards."
    ] * 6  # 30 responses total
    
    config = AisertConfig(
        token_model="gpt-3.5-turbo",
        model_provider="openai",
        sentence_transformer_model="all-MiniLM-L6-v1"
    )
    
    print(f"Testing performance with {len(responses)} responses...")
    start_time = time.time()
    
    validation_results = []
    for i, response in enumerate(responses, 1):
        # More comprehensive validation to show realistic timing
        result = (
            Aisert(response, config)
            .assert_contains(["the", "and", "for"], strict=False)  # Common words
            .assert_not_contains(["error", "failed", "broken"], strict=False)  # Negative terms
            .assert_tokens(max_tokens=200, strict=False)  # Token limit
            .collect()
        )
        validation_results.append(result.status)
        
        # Progress indicator for longer runs
        if i % 10 == 0:
            print(f"  Processed {i}/{len(responses)} responses...")
    
    end_time = time.time()
    total_time = end_time - start_time
    avg_time = total_time / len(responses)
    
    # Calculate success rate
    success_rate = sum(validation_results) / len(validation_results) * 100
    
    print(f"\n📊 Performance Results:")
    print(f"  Total time: {total_time:.2f} seconds")
    print(f"  Average per validation: {avg_time*1000:.1f} ms")
    print(f"  Throughput: {len(responses)/total_time:.1f} validations/second")
    print(f"  Success rate: {success_rate:.1f}%")
    
    # Performance thresholds for monitoring
    if avg_time > 0.1:  # 100ms threshold
        print(f"  ⚠️  Warning: Average response time ({avg_time*1000:.1f}ms) exceeds 100ms threshold")
    else:
        print(f"  ✅ Performance within acceptable limits")

def enterprise_configuration_management():
    """
    Enterprise-grade configuration management patterns.
    """
    print("\n=== Enterprise Configuration Management ===")
    
    # Environment-specific configurations
    configs = {
        "development": AisertConfig(
            model_provider="openai",
            token_model="gpt-3.5-turbo",
            sentence_transformer_model="all-MiniLM-L6-v1"  # Fast for dev
        ),
        "production": AisertConfig(
            model_provider="openai",
            token_model="gpt-4",
            sentence_transformer_model="all-MiniLM-L12-v2"  # Production-grade
        )
    }
    
    # Simulate environment selection
    import os
    env = os.getenv("ENVIRONMENT", "development")
    config = configs.get(env, configs["development"])
    
    print(f"Using {env} configuration: {config.token_model}")
    
    test_content = "This is a test response for validation."
    result = (
        Aisert(test_content, config)
        .assert_contains(["test"], strict=False)
        .assert_tokens(max_tokens=50, strict=False)
        .collect()
    )
    
    print(f"Validation result: {'✅ PASS' if result.status else '❌ FAIL'}")


def microservices_integration_pattern():
    """
    Integration patterns for microservices architecture.
    """
    print("\n=== Microservices Integration Pattern ===")
    
    class ValidationService:
        """Centralized validation service for microservices."""
        
        def __init__(self):
            self.config = AisertConfig(
                model_provider="openai",
                token_model="gpt-3.5-turbo",
                sentence_transformer_model="all-MiniLM-L6-v1"
            )
        
        def validate_user_content(self, content: str) -> dict:
            """Validate user-generated content."""
            result = (
                Aisert(content, self.config)
                .assert_not_contains(["spam", "inappropriate"], strict=False)
                .assert_tokens(max_tokens=500, strict=False)
                .collect()
            )
            
            return {
                "is_valid": result.status,
                "validation_details": result.rules,
                "service": "content-validation"
            }
    
    # Usage example
    validation_service = ValidationService()
    user_content = "This is a great product review!"
    result = validation_service.validate_user_content(user_content)
    print(f"User content validation: {'✅ PASS' if result['is_valid'] else '❌ FAIL'}")


if __name__ == "__main__":
    print("🏢 Aisert Production Patterns")
    print("=" * 50)
    
    print("1. Testing Framework Integration:")
    test_llm_response_quality()
    
    print("\n2. CI/CD Pipeline Validation:")
    cicd_validation_pipeline()
    
    print("\n3. A/B Testing:")
    ab_test_llm_responses()
    
    print("\n4. Custom Validation Rules:")
    custom_validation_example()
    
    print("\n5. Performance Monitoring:")
    performance_monitoring()
    
    enterprise_configuration_management()
    microservices_integration_pattern()
    
    print("\n✨ Production patterns completed!")
    print("💡 These patterns can be adapted for your specific enterprise needs.")