# ENHANCED ARCHITECTURE DESIGNER - N8N PIPELINE INTEGRATION
# 
# FEATURES:
# 1. Accept tech-stack-selector output from n8n orchestration
# 2. Use EXACT technology choices from tech-stack-selector
# 3. Generate architecture based on selected technologies
# 4. Return code-generation-ready specifications
# 5. Comprehensive domain knowledge base integration

import os
import sys
import asyncio
import json
import uuid
import re
from datetime import datetime
from typing import Dict, Any, Optional, List, Tuple
from enum import Enum
import hashlib

import uvicorn
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
from loguru import logger
import numpy as np

# Database and AI integrations
try:
    import anthropic
    CLAUDE_AVAILABLE = True
except ImportError:
    CLAUDE_AVAILABLE = False
    logger.warning("Anthropic library not installed. Claude AI features disabled.")

try:
    import openai
    OPENAI_AVAILABLE = True
except ImportError:
    OPENAI_AVAILABLE = False
    logger.warning("OpenAI library not installed. GPT-4 features disabled.")

try:
    import redis
    import asyncpg
    from sentence_transformers import SentenceTransformer
    STORAGE_AVAILABLE = True
except ImportError:
    STORAGE_AVAILABLE = False
    logger.warning("Storage libraries not available. Using fallback storage.")

# Configure logging
logger.remove()
logger.add(sys.stdout, level="INFO", format="{time} | {level} | {message}")

# API Keys Configuration
CLAUDE_API_KEY = "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"
OPENAI_API_KEY = "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"

# Override environment variables if not set
if not os.getenv("CLAUDE_API_KEY") and CLAUDE_API_KEY:
    os.environ["CLAUDE_API_KEY"] = CLAUDE_API_KEY
    logger.info("Claude API key set from code configuration")

if not os.getenv("OPENAI_API_KEY") and OPENAI_API_KEY:
    os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
    logger.info("OpenAI API key set from code configuration")

# ================================================================================================
# UPDATED PYDANTIC MODELS FOR N8N INTEGRATION
# ================================================================================================

class ArchitectureDesignRequest(BaseModel):
    """
    Enhanced request model to receive tech-stack-selector output via n8n
    """
    project_name: str
    project_id: Optional[str] = None
    
    # NEW: Accept complete tech-stack-selector output from n8n
    tech_stack_recommendations: Dict[str, Any] = Field(
        default={},
        description="Complete output from tech-stack-selector service via n8n"
    )
    
    # NEW: Accept processed business requirements from requirement-processor
    business_requirements: Dict[str, Any] = Field(
        default={},
        description="Enhanced business intelligence from requirement-processor"
    )
    
    # NEW: n8n workflow metadata
    n8n_workflow_data: Dict[str, Any] = Field(
        default={},
        description="n8n workflow execution context and metadata"
    )
    
    # Keep existing fields for backward compatibility
    technology_context: Dict[str, Any] = {}
    requirements: Dict[str, Any] = {}
    architecture_requirements: Dict[str, Any] = {}
    processing_metadata: Dict[str, Any] = {}

class ProcessingMethod(str, Enum):
    RULE_BASED_ONLY = "rule_based_only"
    CLAUDE_AI_DRIVEN = "claude_ai_driven"
    TECH_STACK_GUIDED = "tech_stack_guided"
    N8N_ORCHESTRATED = "n8n_orchestrated"

# ================================================================================================
# TECH STACK INTEGRATION MANAGER
# ================================================================================================

class TechStackIntegrationManager:
    """
    Manages integration between tech-stack-selector output and architecture design
    """
    
    def __init__(self):
        self.supported_stacks = self._initialize_supported_stacks()
    
    def extract_tech_stack_context(self, tech_recommendations: Dict) -> Dict:
        """
        Extract and validate technology stack from tech-stack-selector output
        """
        try:
            logger.info("Extracting technology stack from tech-stack-selector recommendations")
            
            # Extract the final recommendations from tech-stack-selector
            data_section = tech_recommendations.get('data', {})
            final_recommendations = data_section.get('final_technology_recommendations', {})
            recommended_stack = final_recommendations.get('recommended_technology_stack', {})
            
            # Extract specific technologies
            tech_context = {
                'frontend': self._extract_frontend_context(recommended_stack),
                'backend': self._extract_backend_context(recommended_stack), 
                'database': self._extract_database_context(recommended_stack),
                'infrastructure': self._extract_infrastructure_context(recommended_stack),
                'confidence_metrics': self._extract_confidence_metrics(tech_recommendations),
                'business_alignment': self._extract_business_alignment(tech_recommendations),
                'source': 'tech_stack_selector_validated'
            }
            
            # Validate stack compatibility
            tech_context['stack_validation'] = self._validate_stack_compatibility(tech_context)
            
            logger.info(f"Extracted tech stack: Frontend={tech_context['frontend']['primary_framework']}, Backend={tech_context['backend']['primary_language']}, Database={tech_context['database']['primary_database']}")
            
            return tech_context
            
        except Exception as e:
            logger.error(f"Failed to extract tech stack context: {e}")
            return self._get_fallback_tech_context()
    
    def _extract_frontend_context(self, recommended_stack: Dict) -> Dict:
        """Extract frontend technology context"""
        frontend_tech = recommended_stack.get('frontend_technologies', {})
        
        return {
            'primary_framework': frontend_tech.get('primary_framework', 'React'),
            'ui_library': frontend_tech.get('ui_library', 'Tailwind CSS'),
            'state_management': frontend_tech.get('state_management', 'Redux Toolkit'),
            'build_tool': frontend_tech.get('build_tool', 'Vite'),
            'testing_framework': frontend_tech.get('testing_framework', 'Jest + Testing Library'),
            'additional_libraries': frontend_tech.get('additional_libraries', [])
        }
    
    def _extract_backend_context(self, recommended_stack: Dict) -> Dict:
        """Extract backend technology context"""
        backend_tech = recommended_stack.get('backend_technologies', {})
        
        return {
            'primary_language': backend_tech.get('primary_language', 'Node.js'),
            'framework': backend_tech.get('framework', 'Express.js'),
            'authentication': backend_tech.get('authentication', 'JWT'),
            'api_style': backend_tech.get('api_style', 'REST'),
            'validation': backend_tech.get('validation', 'Joi'),
            'testing_framework': backend_tech.get('testing_framework', 'Jest + Supertest'),
            'additional_services': backend_tech.get('additional_services', [])
        }
    
    def _extract_database_context(self, recommended_stack: Dict) -> Dict:
        """Extract database technology context"""
        database_tech = recommended_stack.get('database_technologies', {})
        
        return {
            'primary_database': database_tech.get('primary_database', 'PostgreSQL'),
            'caching': database_tech.get('caching', 'Redis'),
            'orm_tool': database_tech.get('orm_tool', 'Prisma'),
            'migration_tool': database_tech.get('migration_tool', 'Native'),
            'backup_strategy': database_tech.get('backup_strategy', 'Automated'),
            'additional_databases': database_tech.get('additional_databases', [])
        }
    
    def _extract_infrastructure_context(self, recommended_stack: Dict) -> Dict:
        """Extract infrastructure technology context"""
        infrastructure_tech = recommended_stack.get('infrastructure_technologies', {})
        
        return {
            'cloud_provider': infrastructure_tech.get('cloud_provider', 'AWS'),
            'hosting': infrastructure_tech.get('hosting', 'Vercel'),
            'containerization': infrastructure_tech.get('containerization', 'Docker'),
            'orchestration': infrastructure_tech.get('orchestration', 'Kubernetes'),
            'monitoring': infrastructure_tech.get('monitoring', 'Prometheus'),
            'ci_cd': infrastructure_tech.get('ci_cd', 'GitHub Actions')
        }
    
    def _extract_confidence_metrics(self, tech_recommendations: Dict) -> Dict:
        """Extract confidence metrics from tech-stack-selector"""
        data_section = tech_recommendations.get('data', {})
        project_metadata = data_section.get('project_metadata', {})
        
        return {
            'overall_confidence': project_metadata.get('overall_confidence', 0.8),
            'pattern_matches': project_metadata.get('pattern_matches_found', 0),
            'llm_confidence': project_metadata.get('llm_confidence', 0.8),
            'recommendation_method': project_metadata.get('recommendation_method', 'pattern_database_plus_llm')
        }
    
    def _extract_business_alignment(self, tech_recommendations: Dict) -> Dict:
        """Extract business alignment data"""
        data_section = tech_recommendations.get('data', {})
        business_alignment = data_section.get('business_alignment', {})
        
        return {
            'alignment_score': business_alignment.get('overall_alignment_score', 0.8),
            'business_vertical': data_section.get('project_metadata', {}).get('business_vertical', 'general'),
            'team_capability_fit': business_alignment.get('team_capability_fit', {}),
            'budget_timeline_fit': business_alignment.get('budget_timeline_fit', {})
        }
    
    def _validate_stack_compatibility(self, tech_context: Dict) -> Dict:
        """Validate the extracted technology stack for compatibility"""
        validation_results = {
            'is_valid': True,
            'compatibility_score': 0.9,
            'warnings': [],
            'recommendations': []
        }
        
        frontend = tech_context.get('frontend', {}).get('primary_framework', '')
        backend = tech_context.get('backend', {}).get('primary_language', '')
        database = tech_context.get('database', {}).get('primary_database', '')
        
        # Check for known good combinations
        if frontend in ['React', 'Next.js'] and backend in ['Node.js'] and database in ['PostgreSQL']:
            validation_results['compatibility_score'] = 0.95
            validation_results['recommendations'].append("Excellent technology combination for modern web applications")
        
        return validation_results
    
    def _get_fallback_tech_context(self) -> Dict:
        """Get fallback technology context when extraction fails"""
        logger.warning("Using fallback technology context")
        return {
            'frontend': {
                'primary_framework': 'React',
                'ui_library': 'Tailwind CSS',
                'state_management': 'Redux Toolkit'
            },
            'backend': {
                'primary_language': 'Node.js',
                'framework': 'Express.js',
                'authentication': 'JWT'
            },
            'database': {
                'primary_database': 'PostgreSQL',
                'caching': 'Redis'
            },
            'infrastructure': {
                'cloud_provider': 'AWS',
                'hosting': 'Vercel'
            },
            'source': 'fallback_default',
            'stack_validation': {
                'is_valid': True,
                'compatibility_score': 0.7,
                'warnings': ['Using fallback technology stack'],
                'recommendations': ['Consider providing tech-stack-selector output for better recommendations']
            }
        }
    
    def _initialize_supported_stacks(self) -> Dict:
        """Initialize supported technology stack combinations"""
        return {
            'frontend_frameworks': ['React', 'Vue.js', 'Angular', 'Next.js', 'Nuxt.js'],
            'backend_languages': ['Node.js', 'Python', 'Java', 'C#', 'Go', 'Rust'],
            'databases': ['PostgreSQL', 'MySQL', 'MongoDB', 'Redis', 'Cassandra'],
            'cloud_providers': ['AWS', 'Azure', 'GCP', 'Vercel', 'Netlify']
        }

# ================================================================================================
# ENHANCED AI ARCHITECTURE ANALYZER
# ================================================================================================

class AIArchitectureAnalyzer:
    """
    AI analyzer enhanced for tech-stack-selector integration
    """
    
    def __init__(self):
        self.claude_client = anthropic.Anthropic(api_key=CLAUDE_API_KEY) if CLAUDE_AVAILABLE and CLAUDE_API_KEY else None
        self.openai_client = openai.OpenAI(api_key=OPENAI_API_KEY) if OPENAI_AVAILABLE and OPENAI_API_KEY else None
        self.tech_integration = TechStackIntegrationManager()
    
    async def generate_tech_stack_guided_architecture(self, request_data: Dict) -> Dict:
        """
        Generate architecture based on tech-stack-selector recommendations
        """
        try:
            logger.info(f"Starting tech-stack-guided architecture design for: {request_data.get('project_name', 'Unknown')}")
            
            # Extract technology context from tech-stack-selector
            tech_recommendations = request_data.get('tech_stack_recommendations', {})
            tech_context = self.tech_integration.extract_tech_stack_context(tech_recommendations)
            
            # Extract business requirements
            business_requirements = request_data.get('business_requirements', {})
            
            # Create comprehensive context
            comprehensive_context = {
                'project_data': request_data,
                'selected_technologies': tech_context,
                'business_context': business_requirements,
                'n8n_metadata': request_data.get('n8n_workflow_data', {})
            }
            
            # Generate architecture with Claude
            if self.claude_client:
                claude_result = await self._claude_tech_stack_guided_analysis(comprehensive_context)
                if claude_result.get('success'):
                    return {
                        'success': True,
                        'data': claude_result['data'],
                        'processing_method': ProcessingMethod.TECH_STACK_GUIDED,
                        'ai_model': 'claude-3-5-sonnet',
                        'confidence': claude_result.get('confidence', 0.9),
                        'tech_stack_source': 'tech_stack_selector_validated'
                    }
            
            # Fallback to structured response
            return self._create_structured_fallback_response(comprehensive_context)
            
        except Exception as e:
            logger.error(f"Tech-stack-guided architecture generation failed: {e}")
            return {
                'success': False,
                'error': f'Architecture generation failed: {str(e)}',
                'processing_method': ProcessingMethod.RULE_BASED_ONLY
            }
    
    async def _claude_tech_stack_guided_analysis(self, context: Dict) -> Dict:
        """
        Claude analysis using specific technology stack from tech-stack-selector
        """
        try:
            prompt = self._create_tech_stack_guided_prompt(context)
            
            logger.info(f"Sending tech-stack-guided prompt to Claude (length: {len(prompt)} chars)")
            
            message = self.claude_client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=8000,
                temperature=0.2,  # Lower temperature for consistent output
                messages=[{"role": "user", "content": prompt}]
            )
            
            response_text = message.content[0].text
            logger.info(f"Claude response length: {len(response_text)} characters")
            
            # Try to extract JSON
            json_content = self._extract_json_with_validation(response_text)
            if json_content:
                architecture_data = json.loads(json_content)
                
                return {
                    'success': True,
                    'data': {
                        'architecture_design': architecture_data,
                        'ai_metadata': {
                            'model': 'claude-3-5-sonnet-20241022',
                            'analysis_type': 'tech_stack_guided',
                            'response_length': len(response_text),
                            'generated_at': datetime.utcnow().isoformat(),
                            'parsing_method': 'json_extraction'
                        }
                    },
                    'confidence': 0.95
                }
            
            # Fallback to structured parsing
            structured_data = self._parse_response_to_structure(response_text, context)
            
            return {
                'success': True,
                'data': {
                    'architecture_design': structured_data,
                    'ai_metadata': {
                        'model': 'claude-3-5-sonnet-20241022',
                        'analysis_type': 'tech_stack_guided_structured',
                        'response_length': len(response_text),
                        'generated_at': datetime.utcnow().isoformat(),
                        'parsing_method': 'structured_fallback'
                    }
                },
                'confidence': 0.85
            }
            
        except Exception as e:
            logger.error(f"Claude tech-stack-guided analysis failed: {e}")
            return {'success': False, 'error': f'Claude analysis error: {e}'}
    
    def _create_tech_stack_guided_prompt(self, context: Dict) -> str:
        """
        Create prompt that uses EXACT technologies from tech-stack-selector
        """
        project_data = context.get('project_data', {})
        selected_tech = context.get('selected_technologies', {})
        business_context = context.get('business_context', {})
        
        project_name = project_data.get('project_name', 'Technology Project')
        
        # Extract exact technologies
        frontend_framework = selected_tech.get('frontend', {}).get('primary_framework', 'React')
        backend_language = selected_tech.get('backend', {}).get('primary_language', 'Node.js')
        backend_framework = selected_tech.get('backend', {}).get('framework', 'Express.js')
        database = selected_tech.get('database', {}).get('primary_database', 'PostgreSQL')
        caching = selected_tech.get('database', {}).get('caching', 'Redis')
        cloud_provider = selected_tech.get('infrastructure', {}).get('cloud_provider', 'AWS')
        hosting = selected_tech.get('infrastructure', {}).get('hosting', 'Vercel')
        
        tech_stack_summary = f"""
## EXACT TECHNOLOGY STACK (FROM TECH-STACK-SELECTOR):
- **Frontend**: {frontend_framework} + {selected_tech.get('frontend', {}).get('ui_library', 'Tailwind CSS')}
- **Backend**: {backend_language} + {backend_framework}
- **Database**: {database} + {caching} (caching)
- **Infrastructure**: {cloud_provider} + {hosting}
- **State Management**: {selected_tech.get('frontend', {}).get('state_management', 'Redux Toolkit')}
- **Authentication**: {selected_tech.get('backend', {}).get('authentication', 'JWT')}
"""
        
        return f"""You are a world-class software architect. You have been given EXACT technology choices from an AI-powered tech-stack-selector system that has already analyzed business requirements and chosen the optimal technologies.

## PROJECT TO ARCHITECT:
**Project Name**: {project_name}
**Business Requirements**: {json.dumps(business_context, indent=2)}

{tech_stack_summary}

## YOUR CRITICAL MISSION:
Create a detailed, implementable architecture design using the EXACT technologies specified above. Do NOT suggest alternative technologies - use only what has been provided.

## REQUIRED JSON OUTPUT FORMAT:

You MUST respond with a valid JSON object with this EXACT structure:

```json
{{
    "project_analysis": {{
        "project_understanding": "Analysis of project requirements and how they align with selected technologies",
        "technology_stack_validation": "Confirmation that selected stack meets project needs",
        "architecture_approach": "Overall architectural strategy using the selected technologies"
    }},
    
    "detailed_architecture": {{
        "frontend_architecture": {{
            "framework": "{frontend_framework}",
            "ui_library": "{selected_tech.get('frontend', {}).get('ui_library', 'Tailwind CSS')}",
            "state_management": "{selected_tech.get('frontend', {}).get('state_management', 'Redux Toolkit')}",
            "folder_structure": {{
                "components": "src/components - Reusable UI components",
                "pages": "src/pages - Route-level components",
                "hooks": "src/hooks - Custom React hooks",
                "services": "src/services - API service calls",
                "utils": "src/utils - Utility functions",
                "store": "src/store - State management setup"
            }},
            "routing_strategy": "React Router with lazy loading and code splitting",
            "styling_approach": "Tailwind CSS with component-based styling",
            "performance_optimizations": ["Code splitting", "Lazy loading", "Memoization", "Image optimization"]
        }},
        
        "backend_architecture": {{
            "language": "{backend_language}",
            "framework": "{backend_framework}",
            "authentication": "{selected_tech.get('backend', {}).get('authentication', 'JWT')}",
            "api_design": {{
                "style": "RESTful API",
                "versioning": "URL path versioning (/api/v1/)",
                "documentation": "OpenAPI/Swagger",
                "error_handling": "Standardized error responses"
            }},
            "folder_structure": {{
                "controllers": "src/controllers - Request handlers",
                "services": "src/services - Business logic",
                "models": "src/models - Data models and schemas",
                "middleware": "src/middleware - Authentication, validation, etc.",
                "routes": "src/routes - API route definitions",
                "config": "src/config - Configuration management"
            }},
            "security_measures": ["JWT authentication", "Input validation", "Rate limiting", "CORS configuration", "Helmet.js security headers"]
        }},
        
        "database_architecture": {{
            "primary_database": "{database}",
            "caching_layer": "{caching}",
            "connection_management": "Connection pooling with {database}",
            "schema_design": {{
                "users_table": "id, email, name, password_hash, created_at, updated_at",
                "roles_table": "id, name, permissions, created_at",
                "user_roles_table": "user_id, role_id, assigned_at",
                "sessions_table": "id, user_id, token_hash, expires_at, created_at"
            }},
            "indexing_strategy": "Primary keys, unique constraints on email, indexes on frequently queried columns",
            "migration_strategy": "Version-controlled database migrations",
            "backup_strategy": "Automated daily backups with point-in-time recovery"
        }},
        
        "infrastructure_architecture": {{
            "cloud_provider": "{cloud_provider}",
            "hosting_strategy": "{hosting}",
            "deployment_approach": "Containerized deployment with Docker",
            "environment_management": "Separate dev, staging, and production environments",
            "monitoring_setup": "Application and infrastructure monitoring",
            "ci_cd_pipeline": "Automated testing, building, and deployment"
        }}
    }},
    
    "implementation_specifications": {{
        "database_schema": {{
            "sql_definitions": "CREATE TABLE users (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), email VARCHAR(255) UNIQUE NOT NULL, name VARCHAR(255) NOT NULL, password_hash VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);",
            "sample_data": "INSERT INTO users (email, name, password_hash) VALUES ('admin@example.com', 'Admin User', '$2b$10$...');",
            "indexes": "CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_users_created_at ON users(created_at);"
        }},
        
        "api_endpoints": {{
            "authentication": {{
                "POST /api/v1/auth/register": "User registration with email and password",
                "POST /api/v1/auth/login": "User login returning JWT token",
                "POST /api/v1/auth/refresh": "Refresh JWT token",
                "POST /api/v1/auth/logout": "User logout"
            }},
            "user_management": {{
                "GET /api/v1/users": "Get list of users (admin only)",
                "GET /api/v1/users/:id": "Get user profile",
                "PUT /api/v1/users/:id": "Update user profile",
                "DELETE /api/v1/users/:id": "Delete user (admin only)"
            }}
        }},
        
        "frontend_components": {{
            "authentication_components": ["LoginForm", "RegisterForm", "PasswordReset", "UserProfile"],
            "layout_components": ["Header", "Sidebar", "Footer", "Navigation"],
            "ui_components": ["Button", "Input", "Modal", "Table", "Card"],
            "page_components": ["Dashboard", "UserList", "Settings", "NotFound"]
        }},
        
        "configuration_files": {{
            "environment_variables": "NODE_ENV, PORT, DATABASE_URL, REDIS_URL, JWT_SECRET, CORS_ORIGIN",
            "docker_setup": "Multi-stage Dockerfile for optimized production builds",
            "package_dependencies": "Express.js, jsonwebtoken, bcryptjs, helmet, cors, dotenv"
        }}
    }},
    
    "deployment_roadmap": {{
        "phase_1": {{
            "duration": "2-3 weeks",
            "deliverables": ["Project setup", "Authentication system", "Basic CRUD operations", "Database schema"],
            "testing": "Unit tests for core functionality"
        }},
        "phase_2": {{
            "duration": "3-4 weeks", 
            "deliverables": ["Frontend components", "API integration", "User interface", "Error handling"],
            "testing": "Integration tests and E2E testing"
        }},
        "phase_3": {{
            "duration": "1-2 weeks",
            "deliverables": ["Production deployment", "Performance optimization", "Security hardening", "Monitoring setup"],
            "testing": "Load testing and security audit"
        }}
    }},
    
    "code_generation_ready": {{
        "frontend_ready": true,
        "backend_ready": true,
        "database_ready": true,
        "deployment_ready": true,
        "technology_specifications": {{
            "frontend_framework": "{frontend_framework}",
            "backend_language": "{backend_language}",
            "database_system": "{database}",
            "infrastructure_platform": "{cloud_provider}"
        }}
    }}
}}
```

**CRITICAL REQUIREMENTS:**
1. Use ONLY the technologies specified in the tech stack
2. Create detailed implementation specifications for immediate code generation
3. Include working database schemas and API endpoint specifications
4. Provide deployment-ready configuration details
5. Ensure all specifications are implementable with the chosen technologies

Generate the comprehensive architecture design NOW using the EXACT technology stack provided:"""

    def _extract_json_with_validation(self, response_text: str) -> Optional[str]:
        """Extract and validate JSON from Claude response"""
        try:
            # Remove markdown code blocks
            response_text = re.sub(r'```json\s*', '', response_text)
            response_text = re.sub(r'\s*```', '', response_text)
            
            # Find JSON boundaries
            json_start = response_text.find('{')
            json_end = response_text.rfind('}') + 1
            
            if json_start >= 0 and json_end > json_start:
                json_content = response_text[json_start:json_end]
                
                # Validate JSON by parsing it
                test_parse = json.loads(json_content)
                logger.info("JSON validation successful")
                return json_content
                
        except json.JSONDecodeError as e:
            logger.warning(f"JSON validation failed: {e}")
        except Exception as e:
            logger.error(f"JSON extraction failed: {e}")
        
        return None
    
    def _parse_response_to_structure(self, response_text: str, context: Dict) -> Dict:
        """Parse response text into structured architecture data"""
        selected_tech = context.get('selected_technologies', {})
        
        return {
            "project_analysis": {
                "project_understanding": "Architecture design based on tech-stack-selector recommendations",
                "technology_stack_validation": "Selected technologies validated for project requirements",
                "architecture_approach": "Modern web application architecture with proven technology stack"
            },
            "detailed_architecture": {
                "frontend_architecture": {
                    "framework": selected_tech.get('frontend', {}).get('primary_framework', 'React'),
                    "ui_library": selected_tech.get('frontend', {}).get('ui_library', 'Tailwind CSS'),
                    "state_management": selected_tech.get('frontend', {}).get('state_management', 'Redux Toolkit'),
                    "folder_structure": {
                        "components": "src/components - Reusable UI components",
                        "pages": "src/pages - Route-level components",
                        "hooks": "src/hooks - Custom React hooks",
                        "services": "src/services - API service calls"
                    }
                },
                "backend_architecture": {
                    "language": selected_tech.get('backend', {}).get('primary_language', 'Node.js'),
                    "framework": selected_tech.get('backend', {}).get('framework', 'Express.js'),
                    "authentication": selected_tech.get('backend', {}).get('authentication', 'JWT'),
                    "api_design": {
                        "style": "RESTful API",
                        "versioning": "URL path versioning (/api/v1/)"
                    }
                },
                "database_architecture": {
                    "primary_database": selected_tech.get('database', {}).get('primary_database', 'PostgreSQL'),
                    "caching_layer": selected_tech.get('database', {}).get('caching', 'Redis')
                }
            },
            "implementation_specifications": {
                "database_schema": {
                    "sql_definitions": "Standard user management schema with authentication tables",
                    "sample_data": "Default admin user and role data",
                    "indexes": "Performance-optimized indexes on key columns"
                },
                "api_endpoints": {
                    "authentication": "Standard auth endpoints: login, register, refresh, logout",
                    "user_management": "CRUD operations for user management"
                }
            },
            "code_generation_ready": {
                "frontend_ready": True,
                "backend_ready": True,
                "database_ready": True,
                "deployment_ready": True,
                "technology_specifications": {
                    "frontend_framework": selected_tech.get('frontend', {}).get('primary_framework', 'React'),
                    "backend_language": selected_tech.get('backend', {}).get('primary_language', 'Node.js'),
                    "database_system": selected_tech.get('database', {}).get('primary_database', 'PostgreSQL')
                }
            }
        }
    
    def _create_structured_fallback_response(self, context: Dict) -> Dict:
        """Create structured fallback response when Claude is not available"""
        selected_tech = context.get('selected_technologies', {})
        
        return {
            'success': True,
            'data': {
                'architecture_design': self._parse_response_to_structure("Fallback response", context),
                'ai_metadata': {
                    'model': 'structured_fallback',
                    'analysis_type': 'rule_based_with_tech_stack',
                    'generated_at': datetime.utcnow().isoformat(),
                    'parsing_method': 'structured_generation'
                }
            },
            'confidence': 0.75,
            'note': 'Generated using structured fallback due to AI unavailability'
        }

# ================================================================================================
# ENHANCED ARCHITECTURE DESIGNER
# ================================================================================================

class EnhancedArchitectureDesigner:
    """
    Main architecture designer enhanced for n8n integration
    """
    
    def __init__(self):
        self.ai_analyzer = AIArchitectureAnalyzer()
        logger.info("Enhanced Architecture Designer initialized for n8n integration")
    
    async def design_architecture_from_tech_stack(self, request: ArchitectureDesignRequest) -> Dict:
        """
        Design architecture based on tech-stack-selector recommendations
        """
        try:
            project_id = request.project_id or str(uuid.uuid4())
            
            logger.info(f"Starting architecture design for: {request.project_name}")
            logger.info(f"Tech stack recommendations received: {bool(request.tech_stack_recommendations)}")
            logger.info(f"Business requirements received: {bool(request.business_requirements)}")
            
            # Prepare request data
            request_data = {
                'project_name': request.project_name,
                'project_id': project_id,
                'tech_stack_recommendations': request.tech_stack_recommendations,
                'business_requirements': request.business_requirements,
                'n8n_workflow_data': request.n8n_workflow_data,
                'technology_context': request.technology_context,
                'requirements': request.requirements,
                'architecture_requirements': request.architecture_requirements,
                'processing_metadata': request.processing_metadata
            }
            
            # Generate architecture using tech-stack-guided approach
            ai_result = await self.ai_analyzer.generate_tech_stack_guided_architecture(request_data)
            
            if not ai_result.get('success'):
                raise HTTPException(
                    status_code=500,
                    detail=f"Architecture generation failed: {ai_result.get('error', 'Unknown error')}"
                )
            
            # Generate response for code-generator
            response = {
                "success": True,
                "data": {
                    "project_name": request.project_name,
                    "project_id": project_id,
                    "architecture_metadata": {
                        "processing_method": ai_result.get('processing_method', ProcessingMethod.TECH_STACK_GUIDED).value,
                        "ai_model_used": ai_result.get('ai_model', 'structured_fallback'),
                        "analysis_timestamp": datetime.utcnow().isoformat(),
                        "confidence_score": ai_result.get('confidence', 0.8),
                        "tech_stack_source": ai_result.get('tech_stack_source', 'tech_stack_selector'),
                        "n8n_orchestrated": True,
                        "processing_version": "6.0.0"
                    },
                    "architecture_design": ai_result['data'],
                    "code_generation_input": {
                        "ready_for_code_generation": True,
                        "architecture_specifications": ai_result['data'].get('architecture_design', {}),
                        "technology_stack": self._extract_tech_stack_for_code_gen(request.tech_stack_recommendations),
                        "project_context": {
                            "project_name": request.project_name,
                            "project_id": project_id,
                            "business_requirements": request.business_requirements
                        }
                    }
                },
                "service": "enhanced-architecture-designer-v6",
                "timestamp": datetime.utcnow().isoformat(),
                "n8n_workflow_ready": True
            }
            
            logger.info(f"Architecture design completed for {request.project_name}")
            logger.info(f"Ready for code generation: {response['data']['code_generation_input']['ready_for_code_generation']}")
            
            return response
            
        except Exception as e:
            logger.error(f"Architecture design failed for {request.project_name}: {str(e)}")
            raise HTTPException(
                status_code=500,
                detail=f"Architecture design failed: {str(e)}"
            )
    
    def _extract_tech_stack_for_code_gen(self, tech_recommendations: Dict) -> Dict:
        """Extract technology stack in format expected by code generator"""
        try:
            data_section = tech_recommendations.get('data', {})
            final_recommendations = data_section.get('final_technology_recommendations', {})
            recommended_stack = final_recommendations.get('recommended_technology_stack', {})
            
            return {
                "frontend": {
                    "framework": recommended_stack.get('frontend_technologies', {}).get('primary_framework', 'React'),
                    "ui_library": recommended_stack.get('frontend_technologies', {}).get('ui_library', 'Tailwind CSS'),
                    "state_management": recommended_stack.get('frontend_technologies', {}).get('state_management', 'Redux Toolkit')
                },
                "backend": {
                    "language": recommended_stack.get('backend_technologies', {}).get('primary_language', 'Node.js'),
                    "framework": recommended_stack.get('backend_technologies', {}).get('framework', 'Express.js'),
                    "authentication": recommended_stack.get('backend_technologies', {}).get('authentication', 'JWT')
                },
                "database": {
                    "primary": recommended_stack.get('database_technologies', {}).get('primary_database', 'PostgreSQL'),
                    "caching": recommended_stack.get('database_technologies', {}).get('caching', 'Redis')
                },
                "infrastructure": {
                    "cloud": recommended_stack.get('infrastructure_technologies', {}).get('cloud_provider', 'AWS'),
                    "hosting": recommended_stack.get('infrastructure_technologies', {}).get('hosting', 'Vercel')
                }
            }
        except Exception as e:
            logger.error(f"Failed to extract tech stack for code generator: {e}")
            return {
                "frontend": {"framework": "React", "ui_library": "Tailwind CSS"},
                "backend": {"language": "Node.js", "framework": "Express.js"},
                "database": {"primary": "PostgreSQL", "caching": "Redis"},
                "infrastructure": {"cloud": "AWS", "hosting": "Vercel"}
            }

# Initialize the enhanced designer
enhanced_designer = EnhancedArchitectureDesigner()

# ================================================================================================
# FASTAPI APPLICATION SETUP
# ================================================================================================

app = FastAPI(
    title="Enhanced Architecture Designer - n8n Integration",
    description="Architecture design service integrated with n8n workflow orchestration and tech-stack-selector",
    version="6.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

start_time = datetime.utcnow()

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    uptime = (datetime.utcnow() - start_time).total_seconds()
    
    return {
        "status": "healthy",
        "service": "enhanced-architecture-designer",
        "version": "6.0.0",
        "uptime": uptime,
        "timestamp": datetime.utcnow().isoformat(),
        "features": {
            "tech_stack_integration": True,
            "n8n_orchestration": True,
            "claude_ai": bool(CLAUDE_AVAILABLE and CLAUDE_API_KEY),
            "code_generation_ready": True
        },
        "n8n_integration": {
            "accepts_tech_stack_selector_output": True,
            "accepts_business_requirements": True,
            "provides_code_generation_input": True,
            "workflow_orchestration_ready": True
        }
    }

@app.post("/api/v1/design-architecture")
async def design_architecture(request: ArchitectureDesignRequest):
    """
    Design architecture based on tech-stack-selector recommendations
    
    Enhanced for n8n workflow integration:
    - Accepts tech-stack-selector output
    - Uses EXACT technology choices provided
    - Generates code-generation-ready specifications
    - Returns structured output for next service in pipeline
    """
    return await enhanced_designer.design_architecture_from_tech_stack(request)

# Legacy endpoint for backward compatibility
@app.post("/api/v1/design")
async def design_architecture_legacy(request: ArchitectureDesignRequest):
    """Legacy endpoint for backward compatibility"""
    return await enhanced_designer.design_architecture_from_tech_stack(request)

if __name__ == "__main__":
    port = int(os.getenv("PORT", 8003))
    logger.info(f"Starting Enhanced Architecture Designer v6.0 on port {port}")
    logger.info("="*80)
    logger.info("🏗️ ENHANCED ARCHITECTURE DESIGNER - N8N INTEGRATION")
    logger.info("="*80)
    logger.info(f"🤖 Claude AI: {'✅ Available' if CLAUDE_AVAILABLE and CLAUDE_API_KEY else '❌ Not Available'}")
    logger.info(f"🤖 OpenAI: {'✅ Available' if OPENAI_AVAILABLE and OPENAI_API_KEY else '❌ Not Available'}")
    logger.info("🔄 n8n Orchestration: ✅ Enabled")
    logger.info("⚡ Tech Stack Integration: ✅ Enabled")
    logger.info("🎯 Code Generation Ready: ✅ Enabled")
    logger.info("="*80)
    logger.info("🚀 READY FOR N8N WORKFLOW INTEGRATION")
    logger.info("="*80)
    
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=port,
        log_level="info",
        access_log=True,
        reload=False
    )