# DYNAMIC REACT DESIGNER - AI-powered React architecture based on actual features
# Uses Claude AI to generate React components based on functional requirements

from typing import Dict, Any
from loguru import logger
from designers.base_designer import BaseFrontendDesigner
from prompts.frontend.react_prompts import ReactPrompts

class ReactDesigner(BaseFrontendDesigner):
    """Dynamic React specialist - Generates React architecture based on actual project features"""
    
    def __init__(self):
        super().__init__()
        self.prompts = ReactPrompts()
        logger.info("🎨 Dynamic React Designer initialized - AI-powered feature-based design")
    
    def get_technology_name(self) -> str:
        return "React"
    
    async def design_architecture(self, context: Dict[str, Any]) -> Dict[str, Any]:
        """Design React architecture dynamically based on actual features and tech stack"""
        try:
            logger.info("🎨 React Designer analyzing project features...")
            
            # Extract real project data
            functional_reqs = context['functional_requirements']
            tech_stack = context['technology_stack']
            business_context = context['business_context']
            
            logger.info(f"   Feature: {functional_reqs['feature_name']}")
            logger.info(f"   Technical Requirements: {len(functional_reqs['technical_requirements'])} items")
            logger.info(f"   Business Rules: {len(functional_reqs['business_logic_rules'])} rules")
            
            # Generate AI prompt based on actual project requirements
            prompt = self.prompts.create_dynamic_react_prompt(
                feature_name=functional_reqs['feature_name'],
                feature_description=functional_reqs['description'],
                technical_requirements=functional_reqs['technical_requirements'],
                business_logic_rules=functional_reqs['business_logic_rules'],
                complexity_level=functional_reqs['complexity_level'],
                tech_stack=tech_stack,
                all_features=functional_reqs['all_features']
            )
            
            # Get AI-generated React architecture
            logger.info("🤖 Generating React architecture with Claude AI...")
            response = await self.claude_client.generate_architecture(prompt)
            
            if response.get('success'):
                react_architecture = response['data']
                
                # Enhance with React-specific patterns based on tech stack
                enhanced_architecture = self._enhance_with_tech_stack(
                    react_architecture, tech_stack, functional_reqs
                )
                
                logger.info("✅ Dynamic React architecture generated successfully")
                return {
                    "success": True,
                    "architecture": enhanced_architecture,
                    "specialist": "React",
                    "framework_version": "React 18+",
                    "generated_for_feature": functional_reqs['feature_name'],
                    "ui_library": tech_stack.get('frontend', {}).get('ui_library', 'Tailwind CSS'),
                    "state_management": self._extract_state_management(tech_stack),
                    "patterns_used": self._extract_react_patterns(tech_stack),
                    "ai_generated": True,
                    "feature_specific": True
                }
            else:
                logger.warning("Claude AI generation failed, creating feature-based fallback")
                return self._create_feature_based_fallback(functional_reqs, tech_stack)
                
        except Exception as e:
            logger.error(f"❌ React architecture design failed: {e}")
            return self._create_feature_based_fallback(functional_reqs, tech_stack)
    
    async def design_components(self, context: Dict[str, Any]) -> Dict[str, Any]:
        """Design React components based on actual features"""
        # Will implement specific component design if needed
        pass
    
    async def design_routing(self, context: Dict[str, Any]) -> Dict[str, Any]:
        """Design React Router configuration based on features"""
        # Will implement specific routing design if needed
        pass
    
    async def design_state_management(self, context: Dict[str, Any]) -> Dict[str, Any]:
        """Design state management based on complexity and features"""
        # Will implement specific state management design if needed
        pass
    
    def _enhance_with_tech_stack(self, architecture: Dict, tech_stack: Dict, functional_reqs: Dict) -> Dict:
        """Enhance AI-generated architecture with specific tech stack choices"""
        
        # Extract tech stack details
        frontend_config = tech_stack.get('frontend', {})
        ui_library = self._get_ui_library(frontend_config)
        state_management = self._extract_state_management(tech_stack)
        
        # Enhance folder structure based on complexity
        if 'folder_structure' not in architecture:
            architecture['folder_structure'] = {}
        
        # Add tech-stack-specific folder structure
        architecture['folder_structure'].update({
            "package_json_dependencies": self._generate_dependencies(tech_stack),
            "ui_library_setup": self._generate_ui_setup(ui_library),
            "state_management_setup": self._generate_state_setup(state_management),
            "routing_setup": self._generate_routing_setup(functional_reqs)
        })
        
        # Add environment configuration
        architecture['environment_configuration'] = {
            "environment_variables": self._generate_env_vars(tech_stack),
            "build_configuration": self._generate_build_config(tech_stack),
            "development_setup": self._generate_dev_setup(ui_library, state_management)
        }
        
        return architecture
    
    def _get_ui_library(self, frontend_config: Dict) -> str:
        """Extract UI library from tech stack"""
        libraries = frontend_config.get('libraries', [])
        
        ui_libraries = ['tailwind css', 'material-ui', 'chakra ui', 'ant design', 'bootstrap']
        
        for lib in libraries:
            if any(ui_lib in lib.lower() for ui_lib in ui_libraries):
                return lib
        
        return 'Tailwind CSS'  # Default from tech-stack-selector
    
    def _extract_state_management(self, tech_stack: Dict) -> str:
        """Extract state management choice from tech stack"""
        frontend_config = tech_stack.get('frontend', {})
        libraries = frontend_config.get('libraries', [])
        
        state_libs = ['redux toolkit', 'zustand', 'context api', 'recoil', 'jotai']
        
        for lib in libraries:
            if any(state_lib in lib.lower() for state_lib in state_libs):
                return lib
        
        return 'Redux Toolkit'  # Default for complex apps
    
    def _extract_react_patterns(self, tech_stack: Dict) -> list:
        """Extract React patterns based on tech stack and complexity"""
        patterns = [
            "Functional Components",
            "React Hooks (useState, useEffect, useMemo, useCallback)",
            "Custom Hooks for business logic",
            "Error Boundaries",
            "Lazy Loading with React.lazy()"
        ]
        
        # Add patterns based on state management choice
        state_mgmt = self._extract_state_management(tech_stack)
        if 'redux' in state_mgmt.lower():
            patterns.extend([
                "Redux Toolkit with createSlice",
                "RTK Query for data fetching",
                "useSelector and useDispatch hooks"
            ])
        elif 'zustand' in state_mgmt.lower():
            patterns.append("Zustand stores with immer")
        
        return patterns
    
    def _generate_dependencies(self, tech_stack: Dict) -> Dict:
        """Generate package.json dependencies based on tech stack"""
        frontend_config = tech_stack.get('frontend', {})
        ui_library = self._get_ui_library(frontend_config)
        state_management = self._extract_state_management(tech_stack)
        
        dependencies = {
            "react": "^18.2.0",
            "react-dom": "^18.2.0",
            "react-router-dom": "^6.8.0"
        }
        
        # Add UI library dependencies
        if 'tailwind' in ui_library.lower():
            dependencies.update({
                "tailwindcss": "^3.2.0",
                "@tailwindcss/forms": "^0.5.3",
                "@tailwindcss/typography": "^0.5.9"
            })
        elif 'material-ui' in ui_library.lower():
            dependencies.update({
                "@mui/material": "^5.11.0",
                "@emotion/react": "^11.10.5",
                "@emotion/styled": "^11.10.5"
            })
        
        # Add state management dependencies
        if 'redux toolkit' in state_management.lower():
            dependencies.update({
                "@reduxjs/toolkit": "^1.9.0",
                "react-redux": "^8.0.5"
            })
        elif 'zustand' in state_management.lower():
            dependencies["zustand"] = "^4.3.0"
        
        return dependencies
    
    def _generate_ui_setup(self, ui_library: str) -> Dict:
        """Generate UI library setup based on choice"""
        if 'tailwind' in ui_library.lower():
            return {
                "config_file": "tailwind.config.js",
                "css_import": "@tailwind base; @tailwind components; @tailwind utilities;",
                "class_examples": "bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded"
            }
        elif 'material-ui' in ui_library.lower():
            return {
                "theme_setup": "createTheme() configuration",
                "provider": "ThemeProvider wrapper",
                "component_examples": "Button, TextField, Card, AppBar"
            }
        
        return {"note": f"Setup for {ui_library}"}
    
    def _generate_state_setup(self, state_management: str) -> Dict:
        """Generate state management setup"""
        if 'redux toolkit' in state_management.lower():
            return {
                "store_setup": "configureStore with slices",
                "slice_pattern": "createSlice with reducers and actions",
                "provider": "Provider wrapper in App.js",
                "usage": "useSelector and useDispatch hooks"
            }
        elif 'zustand' in state_management.lower():
            return {
                "store_pattern": "create() with state and actions",
                "usage": "Direct store hook usage",
                "persistence": "persist middleware for local storage"
            }
        
        return {"pattern": f"Setup for {state_management}"}
    
    def _generate_routing_setup(self, functional_reqs: Dict) -> Dict:
        """Generate routing setup based on features"""
        feature_name = functional_reqs.get('feature_name', '')
        
        routes = {
            "/": "Landing/Home page",
            "/login": "Authentication page",
            "/dashboard": "Main application dashboard"
        }
        
        # Add feature-specific routes
        if feature_name:
            clean_feature = feature_name.lower().replace(' ', '-')
            routes[f"/{clean_feature}"] = f"{feature_name} main page"
            routes[f"/{clean_feature}/create"] = f"Create new {feature_name.lower()}"
            routes[f"/{clean_feature}/:id"] = f"View specific {feature_name.lower()}"
        
        return {
            "routes": routes,
            "protection": "ProtectedRoute component for authenticated routes",
            "lazy_loading": "React.lazy() for code splitting"
        }
    
    def _generate_env_vars(self, tech_stack: Dict) -> list:
        """Generate environment variables based on tech stack"""
        return [
            "REACT_APP_API_URL",
            "REACT_APP_ENVIRONMENT", 
            "REACT_APP_VERSION",
            "REACT_APP_BUILD_DATE"
        ]
    
    def _generate_build_config(self, tech_stack: Dict) -> Dict:
        """Generate build configuration"""
        return {
            "build_tool": "Vite or Create React App",
            "output_directory": "build/",
            "optimization": "Code splitting, tree shaking, minification",
            "source_maps": "Enabled for development"
        }
    
    def _generate_dev_setup(self, ui_library: str, state_management: str) -> Dict:
        """Generate development setup instructions"""
        return {
            "installation": f"npm install with {ui_library} and {state_management}",
            "development_server": "npm start on port 3000",
            "hot_reload": "Enabled for fast development",
            "linting": "ESLint with React rules"
        }
    
    def _create_feature_based_fallback(self, functional_reqs: Dict, tech_stack: Dict) -> Dict:
        """Create fallback React architecture based on actual features"""
        logger.warning("Creating feature-based React fallback architecture")
        
        feature_name = functional_reqs.get('feature_name', 'Application')
        ui_library = self._get_ui_library(tech_stack.get('frontend', {}))
        
        return {
            "success": True,
            "architecture": {
                "folder_structure": {
                    "src/components": f"React components for {feature_name}",
                    "src/pages": f"Pages for {feature_name} functionality", 
                    "src/hooks": f"Custom hooks for {feature_name} logic",
                    "src/services": "API services",
                    "src/utils": "Utility functions"
                },
                "components_for_feature": {
                    f"{feature_name}List": f"List view for {feature_name}",
                    f"{feature_name}Form": f"Create/edit form for {feature_name}",
                    f"{feature_name}Card": f"Card component for {feature_name}"
                },
                "ui_library": ui_library,
                "state_management": self._extract_state_management(tech_stack),
                "routing": f"Routes for {feature_name} functionality"
            },
            "specialist": "React",
            "fallback": True,
            "feature_based": True,
            "generated_for": feature_name
        }
