from typing import Dict, Any
from loguru import logger
from datetime import datetime

class ArchitectureCombiner:
    """Combines outputs from technology specialists into unified architecture"""
    
    def __init__(self):
        logger.info("Architecture Combiner initialized")
    
    def combine_architecture_outputs(self, frontend_result: Dict, backend_result: Dict, 
                                   database_result: Dict, tech_stack: Any) -> Dict[str, Any]:
        """Combine specialist outputs into unified architecture design"""
        try:
            logger.info("🔄 Combining specialist architecture outputs...")
            
            combined = {
                "architecture_overview": {
                    "technology_stack": {
                        "frontend": tech_stack.frontend_framework,
                        "backend": tech_stack.backend_language,
                        "database": tech_stack.database_system,
                        "ui_library": tech_stack.ui_library,
                        "state_management": tech_stack.state_management,
                        "authentication": tech_stack.authentication
                    },
                    "specialists_used": {
                        "frontend_specialist": frontend_result.get('specialist', 'Unknown'),
                        "backend_specialist": backend_result.get('specialist', 'Unknown'),
                        "database_specialist": database_result.get('specialist', 'Unknown')
                    },
                    "design_patterns": self._extract_design_patterns(frontend_result, backend_result, database_result)
                },
                
                "frontend_architecture": self._extract_frontend_architecture(frontend_result),
                "backend_architecture": self._extract_backend_architecture(backend_result),
                "database_architecture": self._extract_database_architecture(database_result),
                
                "integrated_features": self._create_integrated_features(frontend_result, backend_result, database_result),
                "deployment_configuration": self._create_deployment_config(tech_stack),
                "development_workflow": self._create_development_workflow(tech_stack)
            }
            
            logger.info("✅ Architecture combination completed")
            return combined
            
        except Exception as e:
            logger.error(f"❌ Architecture combination failed: {e}")
            return self._create_fallback_combined_architecture(tech_stack)
    
    def _extract_frontend_architecture(self, frontend_result: Dict) -> Dict:
        """Extract frontend architecture from specialist result"""
        if not frontend_result.get('success'):
            return {"error": "Frontend architecture generation failed"}
        
        architecture = frontend_result.get('architecture', {})
        
        return {
            "framework": frontend_result.get('specialist', 'React'),
            "folder_structure": architecture.get('folder_structure', {}),
            "components": architecture.get('components', {}),
            "routing": architecture.get('routing', {}),
            "state_management": architecture.get('state_management', {}),
            "styling": architecture.get('styling', {}),
            "patterns": frontend_result.get('patterns_used', [])
        }
    
    def _extract_backend_architecture(self, backend_result: Dict) -> Dict:
        """Extract backend architecture from specialist result"""
        if not backend_result.get('success'):
            return {"error": "Backend architecture generation failed"}
        
        architecture = backend_result.get('architecture', {})
        
        return {
            "framework": f"{backend_result.get('specialist', 'Node.js')}/{backend_result.get('framework', 'Express')}",
            "folder_structure": architecture.get('folder_structure', {}),
            "api_endpoints": architecture.get('api_endpoints', {}),
            "middleware": architecture.get('middleware', {}),
            "authentication": architecture.get('authentication', {}),
            "error_handling": architecture.get('error_handling', {}),
            "patterns": backend_result.get('patterns_used', [])
        }
    
    def _extract_database_architecture(self, database_result: Dict) -> Dict:
        """Extract database architecture from specialist result"""
        if not database_result.get('success'):
            return {"error": "Database architecture generation failed"}
        
        architecture = database_result.get('architecture', {})
        
        return {
            "database_system": database_result.get('specialist', 'PostgreSQL'),
            "schema": architecture.get('database_schema', {}),
            "configuration": architecture.get('database_configuration', {}),
            "features": architecture.get('postgresql_features', {}),
            "backup_strategy": architecture.get('backup_strategy', {}),
            "security": architecture.get('security_implementation', {})
        }
    
    def _extract_design_patterns(self, frontend_result: Dict, backend_result: Dict, database_result: Dict) -> Dict:
        """Extract design patterns used across all specialists"""
        return {
            "frontend_patterns": frontend_result.get('patterns_used', []),
            "backend_patterns": backend_result.get('patterns_used', []),
            "database_patterns": database_result.get('features_used', []),
            "integration_patterns": [
                "RESTful API communication",
                "JWT-based authentication",
                "Error boundary handling",
                "Optimistic UI updates"
            ]
        }
    
    def _create_integrated_features(self, frontend_result: Dict, backend_result: Dict, database_result: Dict) -> Dict:
        """Create integrated features that span multiple layers"""
        return {
            "authentication_flow": {
                "frontend": "Login form with validation and token storage",
                "backend": "JWT token generation and verification middleware", 
                "database": "User table with secure password hashing"
            },
            "data_flow": {
                "frontend": "React components with state management",
                "backend": "Express API with validation and business logic",
                "database": "PostgreSQL with optimized queries and indexes"
            },
            "error_handling": {
                "frontend": "Error boundaries and user-friendly error messages",
                "backend": "Structured error responses with proper HTTP codes",
                "database": "Constraint violations and connection error handling"
            }
        }
    
    def _create_deployment_config(self, tech_stack: Any) -> Dict:
        """Create deployment configuration"""
        return {
            "containerization": {
                "frontend": f"Multi-stage Docker build for {tech_stack.frontend_framework}",
                "backend": f"Node.js Docker container with production optimizations",
                "database": "PostgreSQL container with persistent volumes"
            },
            "environment_variables": {
                "frontend": ["REACT_APP_API_URL", "REACT_APP_ENVIRONMENT"],
                "backend": ["NODE_ENV", "PORT", "DATABASE_URL", "JWT_SECRET"],
                "database": ["POSTGRES_DB", "POSTGRES_USER", "POSTGRES_PASSWORD"]
            },
            "cloud_deployment": {
                "provider": tech_stack.cloud_provider,
                "frontend_hosting": "Static site hosting (Vercel, Netlify)",
                "backend_hosting": "Container service (AWS ECS, Google Cloud Run)",
                "database_hosting": "Managed PostgreSQL service"
            }
        }
    
    def _create_development_workflow(self, tech_stack: Any) -> Dict:
        """Create development workflow configuration"""
        return {
            "development_setup": {
                "frontend": f"Create {tech_stack.frontend_framework} app with {tech_stack.ui_library}",
                "backend": "Node.js with Express and TypeScript",
                "database": "Local PostgreSQL with Docker"
            },
            "testing_strategy": {
                "frontend": "Jest + React Testing Library for component testing",
                "backend": "Jest + Supertest for API testing",
                "database": "Database migrations and seed data for testing"
            },
            "build_process": {
                "frontend": "Vite/Webpack build with code splitting",
                "backend": "TypeScript compilation and bundling",
                "database": "Migration scripts and schema validation"
            }
        }
    
    def _create_fallback_combined_architecture(self, tech_stack: Any) -> Dict:
        """Create fallback combined architecture"""
        logger.warning("Using fallback combined architecture")
        
        return {
            "architecture_overview": {
                "technology_stack": tech_stack.__dict__,
                "note": "Fallback architecture due to specialist failures"
            },
            "frontend_architecture": {
                "framework": tech_stack.frontend_framework,
                "basic_setup": "Standard React application with components"
            },
            "backend_architecture": {
                "framework": f"{tech_stack.backend_language}/Express",
                "basic_setup": "Standard Express API with authentication"
            },
            "database_architecture": {
                "database_system": tech_stack.database_system,
                "basic_setup": "Standard PostgreSQL with user table"
            }
        }
