"""
AI Agent-Friendly Coding Standards Server
Provides tools, resources, and prompts for writing code that is optimized for AI agent development.
"""

from typing import Dict, List, Optional, Any
from fastmcp import FastMCP
import json
import re
from pathlib import Path

# Import necessary modules
try:
    from ..models import AIFriendlinessCheck, NamingConventionViolation, CodeChangeExplanation
    from ..type_hints import FilePath, CodeString, CheckResult
except ImportError:
    # Fallback for development
    AIFriendlinessCheck = dict
    NamingConventionViolation = dict
    CodeChangeExplanation = dict
    FilePath = str
    CodeString = str
    CheckResult = dict


def create_agentic_standards_server() -> FastMCP:
    """
    Create a specialized server for AI agent-friendly coding standards.
    
    Returns:
        FastMCP server instance with AI-friendly coding tools
    """
    server = FastMCP(
        name="AI Agent-Friendly Standards Server",
        instructions="""
        This server provides tools and resources for writing code that is optimized
        for AI agent development and collaboration. It helps ensure code is clear,
        unambiguous, and follows patterns that work well with AI agents.
        
        Key principles:
        - Clear naming conventions
        - Avoiding confusion (like _refactored versions)
        - Consistent patterns
        - Self-documenting code
        - AI-readable structures
        """,
    )
    
    @server.tool(tags={"public", "stable"})
    def check_code_ai_friendliness(
        file_path: str,
        check_level: str = "comprehensive"
    ) -> str:
        """
        Check if code follows AI agent-friendly patterns.
        
        Args:
            file_path: Path to the file to check
            check_level: Level of checking ("basic", "standard", "comprehensive")
            
        Returns:
            JSON string with AI-friendliness analysis and recommendations
        """
        issues = []
        recommendations = []
        score = 100
        
        try:
            with open(file_path, 'r') as f:
                content = f.read()
                
            # Check for confusing patterns
            if "_refactored" in file_path or "_refactored" in content:
                issues.append({
                    "type": "naming",
                    "severity": "high",
                    "message": "Found '_refactored' pattern which is confusing for AI agents and humans",
                    "recommendation": "Either modify the original file or use clear versioning (v2, _improved)"
                })
                score -= 20
                
            # Check for ambiguous file names
            path = Path(file_path)
            if any(pattern in path.name for pattern in ["_copy", "_backup", "_old", "_new", "_temp"]):
                issues.append({
                    "type": "naming",
                    "severity": "medium",
                    "message": f"File name '{path.name}' uses ambiguous naming pattern",
                    "recommendation": "Use descriptive names that indicate purpose, not state"
                })
                score -= 10
                
            # Check for clear docstrings
            if check_level in ["standard", "comprehensive"]:
                # Count functions/classes without docstrings
                func_pattern = r'^\s*def\s+\w+\s*\([^)]*\)\s*:'
                class_pattern = r'^\s*class\s+\w+\s*(?:\([^)]*\))?\s*:'
                
                functions = re.findall(func_pattern, content, re.MULTILINE)
                classes = re.findall(class_pattern, content, re.MULTILINE)
                
                # Simple heuristic: check if docstring follows
                total_definitions = len(functions) + len(classes)
                docstring_count = content.count('"""')
                
                if total_definitions > 0 and docstring_count < total_definitions:
                    issues.append({
                        "type": "documentation",
                        "severity": "medium",
                        "message": "Missing docstrings for some functions/classes",
                        "recommendation": "Add clear docstrings explaining purpose and usage"
                    })
                    score -= 15
                    
            # Check for TODO/FIXME without context
            if check_level == "comprehensive":
                todo_pattern = r'#\s*(TODO|FIXME|HACK|XXX)(?:\s|:|$)'
                todos = re.findall(todo_pattern, content, re.IGNORECASE)
                if todos:
                    issues.append({
                        "type": "clarity",
                        "severity": "low",
                        "message": f"Found {len(todos)} TODO/FIXME comments that may lack context",
                        "recommendation": "Add ticket numbers or detailed explanations to TODO comments"
                    })
                    score -= 5
                    
            # Check for consistent naming
            if check_level in ["standard", "comprehensive"]:
                # Check for mixed naming conventions
                snake_case = re.findall(r'\b[a-z]+(?:_[a-z]+)+\b', content)
                camelCase = re.findall(r'\b[a-z]+(?:[A-Z][a-z]+)+\b', content)
                
                if snake_case and camelCase and len(camelCase) > 5:
                    issues.append({
                        "type": "consistency",
                        "severity": "medium",
                        "message": "Mixed naming conventions detected (snake_case and camelCase)",
                        "recommendation": "Use consistent naming throughout the file"
                    })
                    score -= 10
                    
            # Generate recommendations
            if score >= 90:
                recommendations.append("Code is highly AI-friendly! Minor improvements possible.")
            elif score >= 70:
                recommendations.append("Code is reasonably AI-friendly but has some areas for improvement.")
            else:
                recommendations.append("Code needs significant improvements for AI-friendliness.")
                
            # Add specific recommendations based on issues
            if any(issue["type"] == "naming" for issue in issues):
                recommendations.append("Review naming conventions guide at storm-logger://agentic/naming-conventions")
                
            if any(issue["type"] == "documentation" for issue in issues):
                recommendations.append("Add comprehensive docstrings following Storm Logger patterns")
                
            result = {
                "file": file_path,
                "score": max(0, score),
                "status": "pass" if score >= 70 else "fail",
                "issues": issues,
                "recommendations": recommendations,
                "check_level": check_level
            }
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            return json.dumps({
                "error": str(e),
                "file": file_path,
                "status": "error"
            }, indent=2)
    
    @server.tool(tags={"public", "stable"})
    def validate_naming_conventions(
        code_snippet: str,
        context: str = "general"
    ) -> str:
        """
        Validate naming conventions in a code snippet.
        
        Args:
            code_snippet: The code to validate
            context: Context of the code ("function", "class", "file", "variable", "general")
            
        Returns:
            JSON string with naming convention violations and suggestions
        """
        violations = []
        
        # Define patterns that are problematic
        problematic_patterns = {
            "_refactored": "Creates confusion - modify original or use clear versioning",
            "_temp": "Ambiguous - use descriptive names",
            "_old": "Version control handles this - remove from names",
            "_new": "Ambiguous - use descriptive version numbers",
            "_copy": "Unclear purpose - use descriptive names",
            "_backup": "Use version control instead",
            "test_": "Only use for test files, not production code",
            "_test": "Only use for test files, not production code"
        }
        
        # Check for problematic patterns
        for pattern, recommendation in problematic_patterns.items():
            if pattern in code_snippet and context != "test":
                violations.append({
                    "pattern": pattern,
                    "line": code_snippet.find(pattern),
                    "severity": "high" if pattern == "_refactored" else "medium",
                    "recommendation": recommendation
                })
                
        # Context-specific checks
        if context == "function":
            # Check function naming
            func_matches = re.findall(r'def\s+(\w+)', code_snippet)
            for func_name in func_matches:
                if not func_name.islower() or func_name.startswith('_'):
                    if not (func_name.startswith('_') and func_name[1:].islower()):
                        violations.append({
                            "pattern": func_name,
                            "severity": "medium",
                            "recommendation": "Use snake_case for function names"
                        })
                        
        elif context == "class":
            # Check class naming
            class_matches = re.findall(r'class\s+(\w+)', code_snippet)
            for class_name in class_matches:
                if not (class_name[0].isupper() and '_' not in class_name):
                    violations.append({
                        "pattern": class_name,
                        "severity": "medium",
                        "recommendation": "Use PascalCase for class names"
                    })
                    
        # Check for overly generic names
        generic_names = ["data", "info", "temp", "var", "val", "obj", "item"]
        for name in generic_names:
            if re.search(rf'\b{name}\b', code_snippet):
                violations.append({
                    "pattern": name,
                    "severity": "low",
                    "recommendation": f"'{name}' is too generic - use descriptive names"
                })
                
        result = {
            "code_length": len(code_snippet),
            "context": context,
            "violations": violations,
            "total_violations": len(violations),
            "severity_counts": {
                "high": sum(1 for v in violations if v.get("severity") == "high"),
                "medium": sum(1 for v in violations if v.get("severity") == "medium"),
                "low": sum(1 for v in violations if v.get("severity") == "low")
            },
            "ai_friendly": len(violations) == 0
        }
        
        return json.dumps(result, indent=2)
    
    @server.tool(tags={"public", "stable"})
    def explain_code_changes(
        original_code: str,
        new_code: str,
        context: str = ""
    ) -> str:
        """
        Generate AI-friendly explanation of code changes.
        
        Args:
            original_code: The original code
            new_code: The modified code
            context: Additional context about the changes
            
        Returns:
            JSON string with structured explanation of changes
        """
        import difflib
        
        # Generate diff
        original_lines = original_code.splitlines(keepends=True)
        new_lines = new_code.splitlines(keepends=True)
        
        diff = list(difflib.unified_diff(
            original_lines,
            new_lines,
            fromfile="original",
            tofile="modified",
            lineterm=""
        ))
        
        # Analyze changes
        added_lines = [line for line in diff if line.startswith('+') and not line.startswith('+++')]
        removed_lines = [line for line in diff if line.startswith('-') and not line.startswith('---')]
        
        # Detect types of changes
        changes = {
            "summary": "",
            "added_lines": len(added_lines),
            "removed_lines": len(removed_lines),
            "change_type": "",
            "details": [],
            "ai_notes": []
        }
        
        # Analyze change patterns
        if "_refactored" in new_code and "_refactored" not in original_code:
            changes["ai_notes"].append("WARNING: Adding '_refactored' to names is not AI-friendly")
            
        # Detect common change patterns
        if len(added_lines) > len(removed_lines) * 2:
            changes["change_type"] = "expansion"
            changes["summary"] = "Code was significantly expanded with new functionality"
        elif len(removed_lines) > len(added_lines) * 2:
            changes["change_type"] = "reduction"
            changes["summary"] = "Code was simplified or functionality removed"
        elif abs(len(added_lines) - len(removed_lines)) < 5:
            changes["change_type"] = "modification"
            changes["summary"] = "Code was modified without significant size change"
        else:
            changes["change_type"] = "refactoring"
            changes["summary"] = "Code was refactored"
            
        # Look for specific patterns
        if "class" in original_code and "class" in new_code:
            orig_classes = re.findall(r'class\s+(\w+)', original_code)
            new_classes = re.findall(r'class\s+(\w+)', new_code)
            if set(orig_classes) != set(new_classes):
                changes["details"].append(f"Class structure changed: {orig_classes} → {new_classes}")
                
        if "def" in original_code and "def" in new_code:
            orig_funcs = re.findall(r'def\s+(\w+)', original_code)
            new_funcs = re.findall(r'def\s+(\w+)', new_code)
            added_funcs = set(new_funcs) - set(orig_funcs)
            removed_funcs = set(orig_funcs) - set(new_funcs)
            if added_funcs:
                changes["details"].append(f"Added functions: {list(added_funcs)}")
            if removed_funcs:
                changes["details"].append(f"Removed functions: {list(removed_funcs)}")
                
        # Add context if provided
        if context:
            changes["context"] = context
            
        # Add AI-friendly recommendations
        if changes["change_type"] == "refactoring":
            changes["ai_notes"].append("For refactoring, modify the original file instead of creating new versions")
            
        changes["ai_recommendation"] = "Changes are AI-friendly" if not any("WARNING" in note for note in changes["ai_notes"]) else "Review AI notes for improvements"
        
        return json.dumps(changes, indent=2)
    
    @server.tool(tags={"public", "experimental"})
    def suggest_ai_friendly_refactoring(
        file_path: str,
        refactoring_type: str = "general"
    ) -> str:
        """
        Suggest AI-friendly refactoring for a file.
        
        Args:
            file_path: Path to the file to analyze
            refactoring_type: Type of refactoring ("naming", "structure", "documentation", "general")
            
        Returns:
            JSON string with refactoring suggestions
        """
        suggestions = []
        
        try:
            with open(file_path, 'r') as f:
                content = f.read()
                
            path = Path(file_path)
            
            # File naming suggestions
            if refactoring_type in ["naming", "general"]:
                if "_refactored" in path.name:
                    suggestions.append({
                        "type": "file_rename",
                        "current": path.name,
                        "suggested": path.name.replace("_refactored", "_v2"),
                        "reason": "Version numbers are clearer than '_refactored'"
                    })
                    
            # Code structure suggestions
            if refactoring_type in ["structure", "general"]:
                # Check for long functions
                func_pattern = r'def\s+(\w+)\s*\([^)]*\)\s*:.*?(?=\ndef|\nclass|\Z)'
                functions = re.findall(func_pattern, content, re.DOTALL | re.MULTILINE)
                
                for func in functions:
                    if len(func) > 1000:  # Rough heuristic
                        suggestions.append({
                            "type": "function_split",
                            "target": func[:50] + "...",
                            "reason": "Long functions are harder for AI to process"
                        })
                        
            # Documentation suggestions
            if refactoring_type in ["documentation", "general"]:
                # Check for missing module docstring
                if not content.strip().startswith('"""'):
                    suggestions.append({
                        "type": "add_module_docstring",
                        "reason": "Module docstrings help AI understand file purpose"
                    })
                    
            # Pattern improvements
            if refactoring_type == "general":
                # Check for inconsistent patterns
                if "TODO" in content and "FIXME" in content:
                    suggestions.append({
                        "type": "standardize_comments",
                        "reason": "Use consistent comment markers (prefer TODO)"
                    })
                    
            result = {
                "file": file_path,
                "refactoring_type": refactoring_type,
                "suggestions": suggestions,
                "total_suggestions": len(suggestions),
                "priority": "high" if any(s["type"] == "file_rename" for s in suggestions) else "medium"
            }
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            return json.dumps({
                "error": str(e),
                "file": file_path,
                "status": "error"
            }, indent=2)
    
    @server.tool(tags={"public", "stable"})
    def check_import_consistency(
        project_path: str,
        check_renamed_classes: bool = True
    ) -> str:
        """
        Check for import consistency across the project.
        
        This tool helps prevent import errors by:
        - Scanning all Python files for import statements
        - Detecting when imported names don't exist
        - Finding renamed classes/functions that weren't updated everywhere
        - Identifying circular import risks
        
        Args:
            project_path: Root path of the project to check
            check_renamed_classes: Whether to detect potential renames
            
        Returns:
            JSON string with import consistency analysis
        """
        import ast
        import os
        
        issues = []
        imports_map = {}  # file -> list of imports
        exports_map = {}  # file -> list of exported names
        
        try:
            # First pass: collect all imports and exports
            for root, dirs, files in os.walk(project_path):
                # Skip common directories that shouldn't be scanned
                dirs[:] = [d for d in dirs if d not in ['__pycache__', '.git', 'venv', '.venv', 'node_modules']]
                
                for file in files:
                    if file.endswith('.py'):
                        file_path = os.path.join(root, file)
                        rel_path = os.path.relpath(file_path, project_path)
                        
                        try:
                            with open(file_path, 'r', encoding='utf-8') as f:
                                content = f.read()
                            
                            # Parse the AST
                            tree = ast.parse(content, filename=file_path)
                            
                            # Collect imports
                            file_imports = []
                            for node in ast.walk(tree):
                                if isinstance(node, ast.ImportFrom):
                                    module = node.module or ''
                                    for alias in node.names:
                                        imported_name = alias.name
                                        file_imports.append({
                                            'from': module,
                                            'name': imported_name,
                                            'line': node.lineno
                                        })
                                elif isinstance(node, ast.Import):
                                    for alias in node.names:
                                        file_imports.append({
                                            'module': alias.name,
                                            'line': node.lineno
                                        })
                            
                            imports_map[rel_path] = file_imports
                            
                            # Collect exports (top-level classes and functions)
                            exports = []
                            for node in tree.body:
                                if isinstance(node, ast.ClassDef):
                                    exports.append(node.name)
                                elif isinstance(node, ast.FunctionDef):
                                    exports.append(node.name)
                                elif isinstance(node, ast.Assign):
                                    # Check for __all__ exports
                                    for target in node.targets:
                                        if isinstance(target, ast.Name) and target.id == '__all__':
                                            if isinstance(node.value, ast.List):
                                                for elt in node.value.elts:
                                                    if isinstance(elt, ast.Constant):
                                                        exports.append(elt.value)
                            
                            exports_map[rel_path] = exports
                            
                        except Exception as e:
                            issues.append({
                                'type': 'parse_error',
                                'file': rel_path,
                                'error': str(e),
                                'severity': 'medium'
                            })
            
            # Second pass: check for inconsistencies
            for file_path, imports in imports_map.items():
                for imp in imports:
                    if 'from' in imp:  # ImportFrom
                        # Convert relative imports to absolute
                        module_path = imp['from']
                        if module_path.startswith('.'):
                            # Handle relative imports
                            current_package = os.path.dirname(file_path).replace(os.sep, '.')
                            if module_path == '.':
                                module_path = current_package
                            else:
                                level = len(module_path) - len(module_path.lstrip('.'))
                                if level == 1:
                                    module_path = current_package + module_path[1:]
                                else:
                                    parts = current_package.split('.')
                                    module_path = '.'.join(parts[:-level+1]) + module_path[level:]
                        
                        # Find the target file
                        target_file = module_path.replace('.', os.sep) + '.py'
                        
                        if target_file in exports_map:
                            if imp['name'] not in exports_map[target_file]:
                                # Check if it might be a renamed class
                                suggestions = []
                                if check_renamed_classes:
                                    # Simple heuristic: look for similar names
                                    for export in exports_map[target_file]:
                                        if (imp['name'].lower() in export.lower() or 
                                            export.lower() in imp['name'].lower() or
                                            imp['name'].replace('_', '') == export.replace('_', '')):
                                            suggestions.append(export)
                                
                                issues.append({
                                    'type': 'import_not_found',
                                    'file': file_path,
                                    'line': imp['line'],
                                    'import': imp['name'],
                                    'from': imp['from'],
                                    'severity': 'high',
                                    'suggestions': suggestions,
                                    'recommendation': f"Update import to use existing name or add '{imp['name']}' to {target_file}"
                                })
            
            # Generate summary
            summary = {
                'total_files_scanned': len(imports_map),
                'total_imports': sum(len(imps) for imps in imports_map.values()),
                'total_exports': sum(len(exps) for exps in exports_map.values()),
                'issues_found': len(issues),
                'critical_issues': len([i for i in issues if i.get('severity') == 'high'])
            }
            
            # Generate recommendations
            recommendations = []
            if issues:
                recommendations.append("Fix import errors before running the code")
                if any(i['type'] == 'import_not_found' for i in issues):
                    recommendations.append("Check for renamed classes/functions that weren't updated everywhere")
                if any(i.get('suggestions') for i in issues):
                    recommendations.append("Review suggestions for potential correct import names")
            else:
                recommendations.append("All imports are consistent!")
            
            result = {
                'status': 'error' if summary['critical_issues'] > 0 else 'warning' if issues else 'success',
                'summary': summary,
                'issues': issues,
                'recommendations': recommendations,
                'ai_notes': [
                    'Import consistency is crucial for avoiding runtime errors',
                    'Always update all imports when renaming classes or functions',
                    'Use this tool before committing refactoring changes'
                ]
            }
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            return json.dumps({
                'error': str(e),
                'status': 'error',
                'recommendation': 'Check if project path is correct and accessible'
            }, indent=2)
    
    # Resources
    @server.resource("storm-logger://agentic/standards")
    def get_ai_agent_standards() -> str:
        """
        Get comprehensive AI agent coding standards.
        
        Returns:
            JSON string with AI agent coding standards
        """
        return json.dumps({
            "standards": {
                "naming": {
                    "avoid": [
                        "_refactored - Creates confusion, modify original instead",
                        "_temp, _tmp - Use descriptive names",
                        "_old, _new - Use version control",
                        "_copy, _backup - Unclear purpose",
                        "_test outside test files - Keep test markers in test directory"
                    ],
                    "prefer": [
                        "Descriptive names that explain purpose",
                        "Version numbers for iterations (v2, v3)",
                        "Clear suffixes (_handler, _manager, _processor)",
                        "Consistent case (snake_case for Python)",
                        "Domain-specific terms"
                    ]
                },
                "structure": {
                    "principles": [
                        "One clear purpose per file",
                        "Consistent module organization",
                        "Clear import hierarchy",
                        "Avoid circular dependencies",
                        "Explicit is better than implicit"
                    ],
                    "patterns": [
                        "Use dependency injection",
                        "Separate concerns clearly",
                        "Keep functions focused and small",
                        "Use type hints consistently",
                        "Document complex logic inline"
                    ]
                },
                "documentation": {
                    "requirements": [
                        "Module-level docstrings explaining purpose",
                        "Class docstrings with usage examples",
                        "Function docstrings with clear parameters",
                        "Inline comments for complex logic",
                        "TODO comments with context/tickets"
                    ],
                    "style": [
                        "Use imperative mood ('Return' not 'Returns')",
                        "Include type information in docstrings",
                        "Provide examples for complex usage",
                        "Link to related modules/functions",
                        "Keep docstrings up-to-date"
                    ]
                },
                "collaboration": {
                    "principles": [
                        "Make changes in-place, not copies",
                        "Use clear commit messages",
                        "Keep related changes together",
                        "Test before committing",
                        "Document breaking changes"
                    ],
                    "communication": [
                        "Explain 'why' not just 'what'",
                        "Reference tickets/issues",
                        "Highlight important changes",
                        "Use conventional commits",
                        "Update documentation with code"
                    ]
                }
            },
            "rationale": "These standards optimize code for AI agent understanding and collaboration",
            "version": "1.0.0"
        }, indent=2)
    
    @server.resource("storm-logger://agentic/naming-conventions")
    def get_naming_conventions() -> str:
        """
        Get detailed naming conventions for AI-friendly code.
        
        Returns:
            JSON string with naming convention guidelines
        """
        return json.dumps({
            "naming_conventions": {
                "files": {
                    "python_modules": {
                        "pattern": "lowercase_with_underscores.py",
                        "examples": ["user_handler.py", "data_processor.py", "config_manager.py"],
                        "avoid": ["userData.py", "user-handler.py", "user_handler_refactored.py"]
                    },
                    "test_files": {
                        "pattern": "test_<module_name>.py",
                        "examples": ["test_user_handler.py", "test_data_processor.py"],
                        "location": "tests/ directory only"
                    },
                    "configuration": {
                        "pattern": "<purpose>_config.py or config.py",
                        "examples": ["django_config.py", "database_config.py", "config.py"],
                        "avoid": ["configuration.py", "cfg.py", "settings_new.py"]
                    }
                },
                "classes": {
                    "pattern": "PascalCase",
                    "examples": ["UserHandler", "DataProcessor", "ConfigManager"],
                    "avoid": ["user_handler", "User_Handler", "userHandler"],
                    "suffixes": {
                        "Manager": "Manages lifecycle or state",
                        "Handler": "Handles specific operations",
                        "Processor": "Processes/transforms data",
                        "Factory": "Creates instances",
                        "Strategy": "Implements strategy pattern",
                        "Builder": "Builds complex objects"
                    }
                },
                "functions": {
                    "pattern": "snake_case",
                    "examples": ["process_user_data", "get_configuration", "validate_input"],
                    "avoid": ["processUserData", "ProcessUserData", "process-user-data"],
                    "prefixes": {
                        "get_": "Retrieves data without side effects",
                        "set_": "Sets data with side effects",
                        "is_": "Returns boolean",
                        "has_": "Checks existence",
                        "validate_": "Validates and may raise errors",
                        "process_": "Transforms data",
                        "handle_": "Handles events/operations"
                    }
                },
                "variables": {
                    "pattern": "snake_case",
                    "examples": ["user_count", "is_valid", "max_retries"],
                    "avoid": ["userCount", "UserCount", "usr_cnt"],
                    "constants": {
                        "pattern": "UPPER_SNAKE_CASE",
                        "examples": ["MAX_RETRIES", "DEFAULT_TIMEOUT", "API_VERSION"]
                    }
                },
                "special_cases": {
                    "private": {
                        "pattern": "_leading_underscore",
                        "usage": "Internal use only",
                        "examples": ["_internal_cache", "_process_data"]
                    },
                    "dunder": {
                        "pattern": "__double_underscore__",
                        "usage": "Python special methods only",
                        "examples": ["__init__", "__str__", "__repr__"]
                    },
                    "type_vars": {
                        "pattern": "SingleCapital or PascalCase",
                        "examples": ["T", "K", "UserType", "ConfigType"]
                    }
                }
            },
            "anti_patterns": {
                "versioning_in_names": {
                    "avoid": ["function_v2", "class_new", "module_refactored"],
                    "instead": "Use version control or clear feature names"
                },
                "state_in_names": {
                    "avoid": ["user_temp", "data_old", "config_backup"],
                    "instead": "Use descriptive purpose-based names"
                },
                "abbreviations": {
                    "avoid": ["usr", "cfg", "ctx", "evt"],
                    "prefer": ["user", "config", "context", "event"],
                    "exceptions": ["id", "url", "api", "io"]
                }
            }
        }, indent=2)
    
    @server.resource("storm-logger://agentic/collaboration-patterns")
    def get_collaboration_patterns() -> str:
        """
        Get AI agent collaboration patterns and best practices.
        
        Returns:
            JSON string with collaboration patterns
        """
        return json.dumps({
            "collaboration_patterns": {
                "file_modifications": {
                    "pattern": "in_place_modification",
                    "description": "Always modify files in place rather than creating new versions",
                    "rationale": "Prevents confusion and maintains clear history",
                    "examples": {
                        "good": "Edit django_config.py directly",
                        "bad": "Create django_config_refactored.py"
                    },
                    "exceptions": [
                        "Creating genuinely new modules with different purposes",
                        "Extracting functionality to new files with clear names"
                    ]
                },
                "code_organization": {
                    "pattern": "clear_separation",
                    "principles": [
                        "One concept per file",
                        "Clear module boundaries",
                        "Consistent directory structure",
                        "Logical grouping of related code"
                    ],
                    "examples": {
                        "good": "handlers/user_handler.py, handlers/auth_handler.py",
                        "bad": "handlers_new.py, handlers_all.py"
                    }
                },
                "communication": {
                    "commit_messages": {
                        "format": "<type>: <description>",
                        "types": ["feat", "fix", "refactor", "docs", "test", "style"],
                        "examples": [
                            "feat: add user authentication handler",
                            "fix: resolve memory leak in logger",
                            "refactor: simplify configuration validation"
                        ]
                    },
                    "code_comments": {
                        "when": [
                            "Complex algorithms",
                            "Non-obvious design decisions",
                            "Workarounds with reasons",
                            "Integration points"
                        ],
                        "format": [
                            "# TODO(ticket-123): Description of task",
                            "# NOTE: Explanation of important detail",
                            "# WARNING: Potential issue to be aware of"
                        ]
                    }
                },
                "testing": {
                    "pattern": "test_with_changes",
                    "description": "Always update tests when modifying code",
                    "structure": {
                        "unit_tests": "Mirror source structure in tests/",
                        "integration_tests": "Group by feature in tests/integration/",
                        "fixtures": "Share common test data in conftest.py"
                    }
                },
                "documentation": {
                    "pattern": "document_as_you_go",
                    "requirements": [
                        "Update docstrings with code changes",
                        "Keep README files current",
                        "Document breaking changes",
                        "Include examples for complex features"
                    ],
                    "ai_specific": [
                        "Explain 'why' not just 'what'",
                        "Include context for decisions",
                        "Reference related modules",
                        "Highlight important constraints"
                    ]
                }
            },
            "workflow_patterns": {
                "feature_addition": [
                    "1. Understand existing code structure",
                    "2. Plan changes with clear naming",
                    "3. Implement in appropriate modules",
                    "4. Add comprehensive tests",
                    "5. Update documentation",
                    "6. Commit with clear message"
                ],
                "bug_fixing": [
                    "1. Reproduce the issue",
                    "2. Identify root cause",
                    "3. Fix in the original location",
                    "4. Add test to prevent regression",
                    "5. Document the fix"
                ],
                "refactoring": [
                    "1. Ensure tests pass before starting",
                    "2. Make incremental changes",
                    "3. Keep commits focused",
                    "4. Update affected documentation",
                    "5. Never create _refactored versions"
                ]
            }
        }, indent=2)
    
    @server.resource("storm-logger://agentic/refactoring-checklist")
    def get_refactoring_checklist() -> str:
        """
        Get a comprehensive checklist for safe refactoring.
        
        Returns:
            JSON string with step-by-step refactoring checklist
        """
        return json.dumps({
            "refactoring_checklist": {
                "pre_refactoring": {
                    "title": "Before You Start",
                    "steps": [
                        "1. Ensure all tests pass",
                        "2. Commit current changes (clean working directory)",
                        "3. Create a feature branch for the refactoring",
                        "4. Document the refactoring goal and scope",
                        "5. List all files that will be affected"
                    ],
                    "class_rename_specific": [
                        "Run grep/search for all occurrences of the class name",
                        "Check for string references to the class name",
                        "List all import statements that use the class",
                        "Check configuration files that might reference the class",
                        "Look for dynamic imports using the class name as string"
                    ]
                },
                "during_refactoring": {
                    "title": "While Refactoring",
                    "steps": [
                        "1. Make changes incrementally",
                        "2. Run tests after each significant change",
                        "3. Keep a list of all modified files",
                        "4. Update imports immediately when renaming",
                        "5. Search for both direct and string references"
                    ],
                    "naming_rules": [
                        "NEVER create _refactored versions",
                        "Modify files in place",
                        "Use version numbers (v2) only for truly new implementations",
                        "Keep names descriptive and purpose-driven"
                    ]
                },
                "post_refactoring": {
                    "title": "After Refactoring",
                    "verification_steps": [
                        "1. Run all tests again",
                        "2. Use 'check_import_consistency' tool",
                        "3. Search for any remaining old references",
                        "4. Check that all imports resolve correctly",
                        "5. Review all changed files for completeness"
                    ],
                    "import_verification": [
                        "python -m py_compile **/*.py  # Check syntax",
                        "python -m compileall .  # Compile all Python files",
                        "grep -r 'from.*OldClassName' .  # Search for old imports",
                        "Use IDE's 'Find Usages' feature"
                    ]
                },
                "common_pitfalls": {
                    "title": "What Often Goes Wrong",
                    "issues": [
                        {
                            "problem": "Missed imports in rarely-used files",
                            "solution": "Search entire codebase, not just main files"
                        },
                        {
                            "problem": "String references to class names",
                            "solution": "Search for quoted versions of the name"
                        },
                        {
                            "problem": "Dynamic imports that break",
                            "solution": "Check for __import__, importlib usage"
                        },
                        {
                            "problem": "Configuration files with class names",
                            "solution": "Check JSON, YAML, INI files"
                        },
                        {
                            "problem": "Test files that weren't updated",
                            "solution": "Always include test/ directory in searches"
                        }
                    ]
                },
                "ai_agent_tips": {
                    "title": "Tips for AI Agents",
                    "guidelines": [
                        "Always use the check_import_consistency tool after renaming",
                        "Search for both CamelCase and snake_case variations",
                        "Check relative imports (.module) carefully",
                        "Update type hints and docstrings that reference the old name",
                        "Consider using AST parsing for complex refactoring"
                    ]
                }
            },
            "quick_commands": {
                "find_class_usage": "grep -r 'ClassName' --include='*.py' .",
                "find_imports": "grep -r 'from .* import ClassName' --include='*.py' .",
                "check_syntax": "python -m py_compile path/to/file.py",
                "run_import_check": "check_import_consistency(project_path='.')"
            }
        }, indent=2)
    
    # Prompts
    @server.prompt
    def ai_friendly_code_review(
        file_path: str,
        review_focus: str = "comprehensive"
    ) -> str:
        """
        Generate an AI-friendly code review checklist.
        
        Args:
            file_path: Path to the file being reviewed
            review_focus: Focus area for review
            
        Returns:
            Comprehensive code review checklist
        """
        return f"""
# AI-Friendly Code Review Checklist

**File**: `{file_path}`
**Review Focus**: {review_focus}

## 1. Naming Conventions ✓
- [ ] No `_refactored`, `_temp`, `_old`, `_new` in file names
- [ ] Clear, descriptive function and variable names
- [ ] Consistent naming style (snake_case for Python)
- [ ] No overly generic names (data, info, temp)
- [ ] Version numbers instead of state descriptors

## 2. Code Structure ✓
- [ ] Single responsibility per file/class/function
- [ ] Clear module organization
- [ ] No circular dependencies
- [ ] Proper separation of concerns
- [ ] Logical grouping of related functionality

## 3. Documentation ✓
- [ ] Module-level docstring present and informative
- [ ] All public functions have docstrings
- [ ] Complex logic has inline comments
- [ ] TODO comments include context/ticket numbers
- [ ] Examples provided for complex usage

## 4. AI Collaboration ✓
- [ ] Changes made to original files (not copies)
- [ ] Clear commit messages following conventions
- [ ] No ambiguous file versions
- [ ] Self-documenting code patterns
- [ ] Consistent patterns throughout

## 5. Testing ✓
- [ ] Tests updated with code changes
- [ ] Test files follow naming conventions
- [ ] Fixtures used appropriately
- [ ] Edge cases covered
- [ ] Clear test descriptions

## 6. Specific Anti-Patterns to Avoid
- [ ] Creating `filename_refactored.py` instead of modifying original
- [ ] Using temporary names that persist
- [ ] Mixing naming conventions
- [ ] Leaving cryptic TODO comments
- [ ] Creating unnecessary file copies

## Review Summary
**AI-Friendliness Score**: [Calculate based on checklist]
**Recommendations**: [Key improvements needed]
**Good Practices Found**: [Positive patterns to maintain]

Remember: Code should be clear to both humans and AI agents. When in doubt, choose clarity over cleverness.
"""
    
    @server.prompt
    def refactoring_approach_guide(
        refactoring_type: str = "general",
        target_module: str = "module"
    ) -> str:
        """
        Generate a guide for AI-friendly refactoring approach.
        
        Args:
            refactoring_type: Type of refactoring planned
            target_module: Module being refactored
            
        Returns:
            Step-by-step refactoring guide
        """
        return f"""
# AI-Friendly Refactoring Guide

**Refactoring Type**: {refactoring_type}
**Target Module**: {target_module}

## Critical Rule #1: Never Create _refactored Versions
❌ **DON'T**: Create `{target_module}_refactored.py`
✅ **DO**: Modify `{target_module}.py` directly

## Step-by-Step Approach

### 1. Pre-Refactoring Setup
- Ensure all tests pass
- Create a feature branch
- Document current functionality
- Identify specific goals

### 2. Refactoring Strategy
Based on refactoring type: **{refactoring_type}**

#### If Restructuring:
1. Plan new structure clearly
2. Move code incrementally
3. Update imports as you go
4. Run tests after each change

#### If Renaming:
1. Use IDE refactoring tools
2. Update all references
3. Check string references
4. Update documentation

#### If Extracting:
1. Identify cohesive units
2. Create new modules with clear names
3. Move related functionality together
4. Update dependencies

### 3. During Refactoring
- Make atomic commits
- Keep tests passing
- Update docstrings immediately
- Add comments for non-obvious changes

### 4. Post-Refactoring
- Run full test suite
- Update module documentation
- Review import structure
- Check for unused code

## Naming Guidelines for Refactoring

### Good Names:
- `user_authentication.py` (extracted auth logic)
- `data_processor_v2.py` (major version change)
- `legacy_handler.py` (for old code that must remain)

### Bad Names:
- `module_refactored.py` ❌
- `module_new.py` ❌
- `module_temp.py` ❌
- `module_backup.py` ❌

## Communication Template

### Commit Message:
```
refactor({target_module}): [specific change]

- Moved X to improve Y
- Renamed Z for clarity
- Extracted W into separate module

Breaking changes: [if any]
```

### Code Comment:
```python
# Refactored from previous implementation
# to improve [specific aspect].
# See commit [hash] for details.
```

## Checklist
- [ ] All changes in original files
- [ ] No _refactored versions created
- [ ] Tests updated and passing
- [ ] Documentation updated
- [ ] Clear commit messages
- [ ] No temporary files left

Remember: Future AI agents (and humans) will thank you for clean, in-place refactoring!
"""
    
    @server.prompt
    def safe_rename_guide(
        old_name: str,
        new_name: str,
        file_path: str
    ) -> str:
        """
        Generate a comprehensive guide for safely renaming a class or function.
        
        Args:
            old_name: Current name of the class/function
            new_name: Desired new name
            file_path: Path to the file containing the class/function
            
        Returns:
            Step-by-step guide for safe renaming
        """
        return f"""
# Safe Rename Guide: {old_name} → {new_name}

**File**: `{file_path}`
**Type**: {'Class' if old_name[0].isupper() else 'Function/Variable'}

## Pre-Rename Checklist

### 1. Find All References
```bash
# Direct imports
grep -r "from .* import {old_name}" --include="*.py" .
grep -r "import.*{old_name}" --include="*.py" .

# Usage in code
grep -r "\\b{old_name}\\b" --include="*.py" .

# String references (dynamic imports, config files)
grep -r '"{old_name}"' --include="*.py" --include="*.json" --include="*.yaml" .
grep -r "'{old_name}'" --include="*.py" --include="*.json" --include="*.yaml" .

# In comments and docstrings
grep -r "{old_name}" --include="*.py" | grep -E "(#|'''|\\"\\"\\")"
```

### 2. List Files to Update
Based on the search results, create a list of all files that need updating:
- [ ] {file_path} (definition)
- [ ] Import statements in: [list files]
- [ ] Usage in: [list files]
- [ ] Tests in: [list test files]
- [ ] Documentation: [list docs]

## Renaming Steps

### Step 1: Update the Definition
```python
# In {file_path}
# Change:
class {old_name}:  # or def {old_name}
# To:
class {new_name}:  # or def {new_name}
```

### Step 2: Update All Imports
For each file with imports:
```python
# Change:
from module import {old_name}
# To:
from module import {new_name}

# Change:
from module import Something, {old_name}, Other
# To:
from module import Something, {new_name}, Other
```

### Step 3: Update All Usages
```python
# Update instantiations:
obj = {old_name}()  →  obj = {new_name}()

# Update type hints:
def func(param: {old_name}) -> {old_name}:
# To:
def func(param: {new_name}) -> {new_name}:

# Update isinstance checks:
isinstance(obj, {old_name})  →  isinstance(obj, {new_name})
```

### Step 4: Update String References
```python
# In dynamic imports:
importlib.import_module(".{old_name}", package="module")
# To:
importlib.import_module(".{new_name}", package="module")

# In configurations:
"handler": "{old_name}"  →  "handler": "{new_name}"
```

### Step 5: Update Tests
```python
# Test class names:
class Test{old_name}:  →  class Test{new_name}:

# Test function names:
def test_{old_name}_creation():  →  def test_{new_name}_creation():
```

### Step 6: Update Documentation
- Update docstrings that reference {old_name}
- Update README.md or other documentation files
- Update code examples in documentation

## Verification Steps

### 1. Run Import Consistency Check
```python
check_import_consistency(project_path=".")
```

### 2. Compile All Python Files
```bash
python -m compileall .
```

### 3. Run Tests
```bash
pytest  # or your test command
```

### 4. Final Search
```bash
# Should return no results:
grep -r "\\b{old_name}\\b" --include="*.py" . | grep -v "{new_name}"
```

## Common Gotchas

1. **Partial Matches**: Be careful with names that are substrings
   - If renaming `User` to `Account`, watch for `UserProfile`, `UserManager`
   
2. **Case Sensitivity**: Python is case-sensitive but some searches aren't
   - Search for both `{old_name}` and `{old_name.lower()}`
   
3. **Import Aliases**: Check for aliased imports
   ```python
   from module import {old_name} as alias
   ```

4. **Relative Imports**: Don't forget to check relative imports
   ```python
   from .module import {old_name}
   from ..module import {old_name}
   ```

5. **Type Comments**: For older Python code
   ```python
   # type: {old_name}
   ```

## AI Agent Tips

- Use AST parsing for more accurate detection
- Consider semantic search tools for complex codebases
- Always make changes atomically (all at once)
- Create a rollback plan before starting
- Use version control to track changes

## Final Checklist

- [ ] All imports updated
- [ ] All usages updated
- [ ] All tests updated
- [ ] All string references updated
- [ ] Documentation updated
- [ ] Import consistency check passes
- [ ] All tests pass
- [ ] No references to old name remain

Remember: NEVER create {file_path.replace('.py', '_refactored.py')}!
Always modify {file_path} directly.
"""
    
    @server.tool(tags={"health", "internal"})
    def health_check() -> Dict:
        """Health check for agentic standards server."""
        return {
            "status": "healthy",
            "server": "agentic_standards",
            "tools_available": 5,
            "resources_available": 3,
            "prompts_available": 2,
            "standards_version": "1.0.0"
        }
    
    return server