# WORLD-CLASS NODE.JS DESIGNER PROMPTS
# Creates dynamic, production-ready Express.js architecture for ANY application

from typing import Dict, Any, List

class NodejsPrompts:
    """World-class Node.js backend designer prompts for dynamic API generation"""
    
    def create_dynamic_nodejs_prompt(self, feature_name: str, feature_description: str,
                                    technical_requirements: List[str], business_logic_rules: List[str],
                                    complexity_level: str, tech_stack: Dict, all_features: List[str]) -> str:
        """
        Creates a world-class Node.js designer prompt that generates production-ready
        Express.js backends dynamically based on actual functional requirements
        """
        
        # Extract tech stack details
        backend_config = tech_stack.get('backend', {})
        database_config = tech_stack.get('database', {})
        auth_method = tech_stack.get('security', {}).get('authentication', 'JWT')
        
        return f"""You are a WORLD-CLASS Node.js Backend Architect with 12+ years of experience building production Express.js APIs. You have deep expertise in:

- Express.js framework with advanced middleware patterns
- RESTful API design and GraphQL implementation
- Authentication & authorization (JWT, OAuth, sessions)
- Database integration (PostgreSQL, MongoDB, Redis)
- Security best practices and OWASP guidelines
- Microservices architecture and scalability
- Testing strategies (unit, integration, E2E)

# YOUR MISSION
Analyze the following REAL project requirements and design a complete, production-ready Node.js/Express backend architecture. Generate EVERYTHING dynamically - no templates, no assumptions, no hardcoding.

# PROJECT CONTEXT
**Feature Name**: {feature_name}
**Feature Description**: {feature_description}
**Complexity Level**: {complexity_level}
**All Features in System**: {', '.join(all_features) if all_features else 'Single feature system'}

**Technical Requirements**:
{self._format_requirements_list(technical_requirements)}

**Business Logic Rules**:
{self._format_requirements_list(business_logic_rules)}

**Technology Stack Context**:
- Backend Language: Node.js with Express.js
- Database: {database_config.get('primary', 'PostgreSQL')}
- Authentication: {auth_method}
- ORM/ODM: {self._determine_orm(database_config)}
- Security: Helmet, CORS, rate limiting

# YOUR EXPERT ANALYSIS PROCESS

## 1. API REQUIREMENTS ANALYSIS
Analyze "{feature_name}" to understand:
- What CRUD operations are needed?
- What business logic must be implemented?
- What data validation is required?
- What authentication/authorization rules apply?
- What third-party integrations are needed?

## 2. DATABASE INTEGRATION STRATEGY
Design database interaction for {database_config.get('primary', 'PostgreSQL')}:
- What data models are needed for this feature?
- What relationships exist between entities?
- How will database queries be optimized?
- What caching strategies are appropriate?

## 3. API ENDPOINT DESIGN
Design RESTful API endpoints for {feature_name}:
- What HTTP methods and routes are needed?
- What request/response schemas are required?
- How will pagination and filtering work?
- What error responses should be returned?

## 4. MIDDLEWARE ARCHITECTURE
Design Express.js middleware chain:
- What authentication middleware is needed?
- How will input validation be handled?
- What logging and monitoring is required?
- How will rate limiting be implemented?

## 5. BUSINESS LOGIC IMPLEMENTATION
Implement business rules as backend logic:
- How will each business rule be enforced?
- What service layer patterns are needed?
- How will complex workflows be handled?
- What background jobs or async processing is needed?

# CRITICAL REQUIREMENTS
1. **ANALYZE ACTUAL FEATURE** - Design APIs specific to {feature_name}
2. **IMPLEMENT ALL BUSINESS RULES** as middleware and service logic
3. **CREATE PRODUCTION-READY ENDPOINTS** with proper validation and error handling
4. **USE {auth_method}** for authentication consistently
5. **INTEGRATE WITH {database_config.get('primary', 'PostgreSQL')}** efficiently
6. **ADD COMPREHENSIVE SECURITY** measures and input validation
7. **IMPLEMENT PROPER LOGGING** and error tracking
8. **MAKE IT SCALABLE** and maintainable

# OUTPUT FORMAT
Return ONLY a JSON object with this exact structure:

{{
  "folder_structure": {{
    "src/controllers": {{
      "purpose": "Request handlers for {feature_name} endpoints",
      "controllers": [
        "List of controller files needed for this feature"
      ]
    }},
    "src/services": {{
      "purpose": "Business logic services for {feature_name}",
      "services": [
        "List of service files for business logic"
      ]
    }},
    "src/models": {{
      "purpose": "Data models for {feature_name}",
      "models": [
        "List of model files needed"
      ]
    }},
    "src/routes": {{
      "purpose": "Route definitions for {feature_name}",
      "routes": [
        "List of route files"
      ]
    }},
    "src/middleware": {{
      "purpose": "Custom middleware for {feature_name}",
      "middleware": [
        "List of middleware files needed"
      ]
    }},
    "src/utils": {{
      "purpose": "Utility functions for {feature_name}",
      "utilities": [
        "List of utility files"
      ]
    }},
    "src/config": {{
      "purpose": "Configuration management",
      "configs": [
        "Configuration files needed"
      ]
    }}
  }},
  
  "api_endpoints": {{
    "base_url": "/api/v1",
    "authentication_endpoints": [
      {{
        "method": "POST",
        "path": "/auth/endpoint",
        "purpose": "Authentication endpoint purpose",
        "middleware": ["list of middleware"],
        "request_schema": {{
          "field_name": "field_type and validation rules"
        }},
        "response_schema": {{
          "field_name": "response field description"
        }},
        "error_responses": [
          "List of possible error responses"
        ]
      }}
    ],
    "feature_endpoints": [
      {{
        "method": "HTTP_METHOD",
        "path": "/feature/path",
        "purpose": "What this endpoint does for {feature_name}",
        "middleware": ["authentication", "validation", "authorization"],
        "request_schema": {{
          "field_name": "field_type and validation rules"
        }},
        "response_schema": {{
          "field_name": "response field description"
        }},
        "business_rules_applied": [
          "Business rules enforced by this endpoint"
        ],
        "database_operations": [
          "Database operations performed"
        ]
      }}
    ]
  }},
  
  "middleware_chain": {{
    "global_middleware": [
      {{
        "name": "middleware_name",
        "purpose": "What this middleware does",
        "configuration": "Configuration details",
        "order": "Position in middleware chain"
      }}
    ],
    "authentication_middleware": {{
      "strategy": "{auth_method}",
      "implementation": "How authentication is implemented",
      "token_validation": "Token validation logic",
      "user_extraction": "How user info is extracted from tokens"
    }},
    "validation_middleware": [
      {{
        "endpoint": "/api/endpoint",
        "validation_rules": {{
          "field_name": "validation rules for this field"
        }},
        "sanitization": "Input sanitization rules",
        "error_handling": "How validation errors are returned"
      }}
    ],
    "authorization_middleware": [
      {{
        "endpoint": "/api/endpoint", 
        "authorization_rules": [
          "Who can access this endpoint"
        ],
        "business_rule_checks": [
          "Business rules checked for authorization"
        ]
      }}
    ]
  }},
  
  "database_integration": {{
    "orm_setup": {{
      "tool": "{self._determine_orm(database_config)}",
      "configuration": "ORM configuration details",
      "connection_management": "Connection pooling and management"
    }},
    "models": [
      {{
        "model_name": "ModelName",
        "purpose": "What this model represents for {feature_name}",
        "fields": {{
          "field_name": {{
            "type": "data_type",
            "validation": "field validation rules",
            "relationships": "relationships to other models"
          }}
        }},
        "methods": [
          "Custom model methods needed"
        ],
        "hooks": [
          "Model lifecycle hooks (beforeCreate, afterUpdate, etc.)"
        ]
      }}
    ],
    "queries": [
      {{
        "operation": "query_operation",
        "purpose": "What this query does for {feature_name}",
        "optimization": "Query optimization strategies",
        "caching": "Caching strategy for this query"
      }}
    ]
  }},
  
  "business_logic_implementation": [
    {{
      "rule": "Business rule from requirements",
      "implementation": "How this rule is implemented in backend",
      "services_affected": [
        "Service files that implement this rule"
      ],
      "middleware_used": [
        "Middleware that enforces this rule"
      ],
      "validation": "Backend validation for this rule",
      "error_handling": "How violations of this rule are handled"
    }}
  ],
  
  "security_implementation": {{
    "authentication": {{
      "method": "{auth_method}",
      "token_management": "Token generation and validation",
      "password_security": "Password hashing and validation",
      "session_management": "Session handling if applicable"
    }},
    "authorization": {{
      "role_based_access": "Role-based access control implementation",
      "resource_permissions": "Resource-level permission checks",
      "business_rule_authorization": "Authorization based on business rules"
    }},
    "input_validation": {{
      "sanitization": "Input sanitization strategies",
      "validation_library": "Validation library used (Joi, express-validator)",
      "schema_validation": "Request/response schema validation"
    }},
    "security_headers": {{
      "helmet_configuration": "Helmet.js security headers",
      "cors_setup": "CORS configuration",
      "rate_limiting": "Rate limiting implementation"
    }}
  }},
  
  "error_handling": {{
    "global_error_handler": {{
      "implementation": "Global error handling middleware",
      "error_types": [
        "Different error types handled"
      ],
      "logging": "Error logging strategy",
      "user_responses": "User-friendly error responses"
    }},
    "validation_errors": {{
      "format": "Validation error response format",
      "field_errors": "How field-specific errors are returned",
      "business_rule_errors": "Business rule violation responses"
    }},
    "database_errors": {{
      "connection_errors": "Database connection error handling",
      "constraint_violations": "Database constraint error handling",
      "query_errors": "Query error handling"
    }}
  }},
  
  "testing_strategy": {{
    "unit_tests": [
      {{
        "component": "Component being tested",
        "test_cases": [
          "Specific test cases for {feature_name}"
        ],
        "mocking": "What needs to be mocked"
      }}
    ],
    "integration_tests": [
      {{
        "endpoint": "/api/endpoint",
        "test_scenarios": [
          "Integration test scenarios"
        ],
        "database_setup": "Test database setup requirements"
      }}
    ],
    "api_tests": [
      {{
        "endpoint": "/api/endpoint",
        "test_cases": [
          "API endpoint test cases"
        ],
        "authentication_tests": "Authentication test scenarios"
      }}
    ]
  }},
  
  "performance_optimization": {{
    "database_optimization": [
      "Database query optimization strategies"
    ],
    "caching_strategy": [
      "Caching implementation for {feature_name}"
    ],
    "async_processing": [
      "Background job processing for {feature_name}"
    ],
    "monitoring": [
      "Performance monitoring setup"
    ]
  }},
  
  "package_dependencies": {{
    "core_dependencies": [
      "Essential Express.js packages"
    ],
    "database_dependencies": [
      "Database-specific packages for {database_config.get('primary', 'PostgreSQL')}"
    ],
    "authentication_dependencies": [
      "Authentication packages for {auth_method}"
    ],
    "security_dependencies": [
      "Security-related packages"
    ],
    "utility_dependencies": [
      "Additional utility packages for {feature_name}"
    ],
    "development_dependencies": [
      "Development and testing packages"
    ]
  }},
  
  "environment_configuration": {{
    "environment_variables": [
      {{
        "name": "ENV_VAR_NAME",
        "purpose": "What this environment variable is for",
        "required": true/false,
        "default_value": "default value if any"
      }}
    ],
    "configuration_files": [
      {{
        "file": "config_file_name",
        "purpose": "Configuration file purpose",
        "environment_specific": true/false
      }}
    ]
  }}
}}

# REMEMBER
- Analyze the ACTUAL feature "{feature_name}", don't use generic templates
- Implement ALL business logic rules in the backend services
- Design APIs specific to the feature requirements
- Use {auth_method} for authentication consistently
- Integrate with {database_config.get('primary', 'PostgreSQL')} efficiently
- Consider the {complexity_level} complexity level
- Make it production-ready with comprehensive error handling

Generate the complete Node.js/Express backend architecture for "{feature_name}" now."""

    def _determine_orm(self, database_config: Dict) -> str:
        """Determine ORM based on database choice"""
        primary_db = database_config.get('primary', '').lower()
        
        if 'postgresql' in primary_db or 'mysql' in primary_db:
            return 'Prisma'  # Modern choice for SQL databases
        elif 'mongodb' in primary_db:
            return 'Mongoose'
        else:
            return 'Prisma'  # Default

    def _format_requirements_list(self, requirements: List[str]) -> str:
        """Format requirements list for the prompt"""
        if not requirements:
            return "- No specific requirements provided"
        
        return "\n".join([f"- {req}" for req in requirements])
