# Add this to the top of main.py after other imports
import anthropic
import re

# Initialize Claude client (add this after the FastAPI app creation)
try:
    claude_client = anthropic.Anthropic(
        api_key=os.getenv("ANTHROPIC_API_KEY", "your-api-key-here")
    )
    logger.info("✅ Claude client initialized successfully")
except Exception as e:
    logger.warning(f"⚠️ Claude client not initialized: {e}")
    claude_client = None

@app.post("/api/v1/analyze-feature")
async def analyze_custom_feature(request: Request):
    """Real AI-powered feature analysis using Claude"""
    try:
        data = await request.json()
        feature_description = data.get('description', '')
        project_type = data.get('project_type', '')
        feature_name = data.get('feature_name', '')
        requirements = data.get('requirements', [])
        
        logger.info(f"Analyzing feature: {feature_name} for {project_type}")
        logger.info(f"Requirements: {requirements}")
        
        # If Claude is not available, use intelligent fallback
        if not claude_client:
            logger.warning("Claude not available, using intelligent fallback")
            return await intelligent_fallback_analysis(feature_name, feature_description, requirements, project_type)
        
        # Build comprehensive prompt for Claude
        requirements_text = "\n".join([f"- {req}" for req in requirements if req.strip()])
        
        claude_prompt = f"""
        Analyze this custom feature for a {project_type} project:
        
        Feature Name: {feature_name}
        Description: {feature_description}
        
        Detailed Requirements:
        {requirements_text}
        
        Based on these requirements, provide a detailed analysis in JSON format:
        {{
            "feature_name": "Improved technical name",
            "complexity": "low|medium|high",
            "logic_rules": ["Business rule 1", "Business rule 2"],
            "implementation_details": ["Technical detail 1", "Technical detail 2"],
            "technical_requirements": ["Requirement 1", "Requirement 2"], 
            "estimated_effort": "1-2 weeks|3-4 weeks|etc",
            "dependencies": ["Dependency 1", "Dependency 2"],
            "api_endpoints": ["POST /api/endpoint1", "GET /api/endpoint2"],
            "database_tables": ["table1", "table2"],
            "confidence_score": 0.85
        }}
        
        For complexity assessment:
        - "low": Simple CRUD, basic features
        - "medium": Moderate business logic, some integrations
        - "high": Complex business rules, external integrations, security requirements
        
        For logic_rules, generate business rules based on the requirements like:
        - Access control rules
        - Data validation rules  
        - Business process rules
        - Security requirements
        
        Return ONLY the JSON object, no other text.
        """
        
        try:
            # Call Claude API
            message = claude_client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=2000,
                temperature=0.1,
                messages=[{"role": "user", "content": claude_prompt}]
            )
            
            # Parse Claude's response
            response_text = message.content[0].text.strip()
            
            # Extract JSON from response
            json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
            if json_match:
                analysis = json.loads(json_match.group())
            else:
                analysis = json.loads(response_text)
            
            logger.info(f"✅ Claude analysis completed: {analysis.get('complexity')} complexity")
            
            return {
                "success": True,
                "analysis": analysis
            }
            
        except json.JSONDecodeError as e:
            logger.error(f"JSON parsing error: {e}")
            return await intelligent_fallback_analysis(feature_name, feature_description, requirements, project_type)
            
        except Exception as e:
            logger.error(f"Claude API error: {e}")
            return await intelligent_fallback_analysis(feature_name, feature_description, requirements, project_type)
        
    except Exception as e:
        logger.error(f"Feature analysis failed: {e}")
        return {
            "success": False,
            "error": str(e)
        }

async def intelligent_fallback_analysis(feature_name: str, description: str, requirements: list, project_type: str):
    """Intelligent fallback analysis when Claude is not available"""
    
    # Analyze complexity based on keywords
    complexity_indicators = {
        "high": ["encryption", "hipaa", "compliance", "security", "integration", "real-time", "ai", "machine learning", "blockchain"],
        "medium": ["crud", "database", "api", "authentication", "validation", "search", "filter"],
        "low": ["display", "show", "view", "list", "basic"]
    }
    
    text_to_analyze = f"{feature_name} {description} {' '.join(requirements)}".lower()
    
    complexity = "medium"  # default
    for level, keywords in complexity_indicators.items():
        if any(keyword in text_to_analyze for keyword in keywords):
            complexity = level
            break
    
    # Generate logical business rules based on project type and requirements
    logic_rules = []
    
    if project_type.lower() == "healthcare":
        logic_rules.extend([
            "Only authorized caregivers can access patient data",
            "All patient data access must be logged for HIPAA compliance",
            "Patient data must be encrypted at rest and in transit"
        ])
    
    if "crud" in text_to_analyze or "manage" in text_to_analyze:
        logic_rules.append("Users can only modify data they have created or been granted access to")
    
    if "patient" in text_to_analyze:
        logic_rules.extend([
            "Patient information can only be accessed by assigned caregivers",
            "All patient data modifications require audit trail"
        ])
    
    # Remove duplicates
    logic_rules = list(set(logic_rules))
    
    analysis = {
        "feature_name": feature_name or "Enhanced Feature",
        "complexity": complexity,
        "logic_rules": logic_rules,
        "implementation_details": [
            f"Implement {feature_name} with proper validation",
            "Add error handling and logging",
            "Include unit and integration tests"
        ],
        "technical_requirements": [
            "Database schema design",
            "API endpoint implementation", 
            "Frontend component development"
        ],
        "estimated_effort": "2-3 weeks" if complexity == "high" else "1-2 weeks",
        "dependencies": ["User authentication", "Database setup"],
        "api_endpoints": [f"POST /api/{feature_name.lower().replace(' ', '-')}", f"GET /api/{feature_name.lower().replace(' ', '-')}"],
        "database_tables": [f"{feature_name.lower().replace(' ', '_')}_table"],
        "confidence_score": 0.75
    }
    
    logger.info(f"✅ Fallback analysis completed: {complexity} complexity with {len(logic_rules)} logic rules")
    
    return {
        "success": True,
        "analysis": analysis
    }
