"""
MCP Component Templates for Storm Logger Development
"""

# Tool template with proper FastMCP syntax
TOOL_TEMPLATE = '''@mcp.tool
def {tool_name}({parameters}) -> {return_type}:
    """
    {description}
    
    Args:
        {args_description}
        
    Returns:
        {return_description}
    """
    # Implementation
    {implementation}
'''

# Resource template
RESOURCE_TEMPLATE = '''@mcp.resource("{protocol}://{path}")
def {resource_name}() -> str:
    """
    {description}
    
    Returns:
        {return_description}
    """
    # Implementation
    {implementation}
'''

# Prompt template - Note: No 'arguments' parameter in decorator
PROMPT_TEMPLATE = '''@mcp.prompt
def {prompt_name}({parameters}) -> str:
    """
    {description}
    
    Args:
        {args_description}
        
    Returns:
        {return_description}
    """
    return f"""{template_string}"""
'''

# Basic MCP server template
MCP_SERVER_TEMPLATE = '''"""
{project_name} MCP Server
{description}
"""
from fastmcp import FastMCP
from pathlib import Path
import json

# Create the MCP server instance
mcp = FastMCP("{server_name}")


@mcp.tool
def example_tool(param: str) -> str:
    """
    Example tool implementation
    
    Args:
        param: Example parameter
        
    Returns:
        Example response
    """
    return f"Processed: {{param}}"


@mcp.resource("example://status")
def get_status() -> str:
    """
    Example resource implementation
    
    Returns:
        JSON status information
    """
    status = {{
        "status": "active",
        "version": "1.0.0"
    }}
    return json.dumps(status, indent=2)


@mcp.prompt
def example_prompt(context: str) -> str:
    """
    Example prompt implementation
    
    Args:
        context: Context for the prompt
        
    Returns:
        Generated prompt text
    """
    return f"""Generate content based on: {{context}}"""


if __name__ == "__main__":
    # Run the MCP server
    mcp.run()
'''

# Unit test template
UNIT_TEST_TEMPLATE = '''"""
Tests for {component_name}
"""
import asyncio
import pytest
from unittest.mock import MagicMock
import json

# Skip tests if fastmcp is not installed
try:
    from fastmcp import Client
except ImportError:
    pytest.skip("fastmcp not installed", allow_module_level=True)


class Test{test_class_name}:
    """Test {component_type} functionality"""
    
    @pytest.fixture
    def mock_client(self):
        """Create a mock client for testing"""
        client = MagicMock(spec=Client)
        client.__aenter__ = MagicMock(return_value=asyncio.coroutine(lambda: client)())
        client.__aexit__ = MagicMock(return_value=asyncio.coroutine(lambda *args: None)())
        return client
    
    @pytest.mark.asyncio
    async def test_{test_name}(self, mock_client):
        """Test {test_description}"""
        # Mock the response
        mock_client.{method_name} = MagicMock(
            return_value=asyncio.coroutine(
                lambda: {expected_response}
            )()
        )
        
        async with mock_client as client:
            result = await client.{method_name}({method_args})
            
            # Assertions
            {assertions}
'''

# Integration test template
INTEGRATION_TEST_TEMPLATE = '''@pytest.mark.asyncio
@pytest.mark.integration
async def test_real_{test_name}(self, client):
    """Test {test_description} on real server"""
    try:
        async with client:
            result = await client.{method_name}({method_args})
            
            # Assertions
            {assertions}
    except Exception as e:
        pytest.skip(f"{test_description} test failed: {{e}}")
'''

# Common patterns and solutions
COMMON_PATTERNS = {
    "tool_method": "call_tool",
    "resource_method": "read_resource", 
    "prompt_method": "get_prompt",
    "error_handling": '''try:
    # Your code here
except Exception as e:
    # Handle specific errors
    if "specific error" in str(e):
        # Specific handling
    else:
        raise''',
    "async_pattern": '''async with client:
    result = await client.method()''',
    "mock_pattern": '''mock_client.method = MagicMock(
    return_value=asyncio.coroutine(lambda: expected_value)()
)''',
    "gitlab_elicitation_pattern": '''# GitLab elicitation pattern with FastMCP
elicitation_result = await ctx.elicit([
    {
        "type": "text",
        "name": "project_type",
        "label": "Project Type",
        "placeholder": "e.g., Python Django, Node.js, Java Spring"
    },
    {
        "type": "select",
        "name": "deployment_strategy",
        "label": "Deployment Strategy",
        "options": [
            {"value": "rolling", "label": "Rolling Deployment"},
            {"value": "blue_green", "label": "Blue-Green Deployment"},
            {"value": "canary", "label": "Canary Deployment"}
        ]
    }
])

# Handle cancellation
if not elicitation_result:
    return json.dumps({
        "status": "cancelled",
        "message": "Operation cancelled by user"
    }, indent=2)''',
    "gitlab_pipeline_template": '''# GitLab CI/CD pipeline with Storm Logger integration
stages:
  - build
  - test
  - security
  - deploy

variables:
  STORM_LOGGER_LEVEL: "INFO"
  STORM_ENABLE_BUSINESS_METRICS: "true"
  STORM_CONSOLE_THEME: "professional"

before_script:
  - pip install storm-logger
  - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-ci'); logger.info('Pipeline started')"

build:
  stage: build
  script:
    - echo "Building application..."
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-build'); logger.info('Build completed')"

test:
  stage: test
  script:
    - echo "Running tests..."
    - ./test.sh --quick --gitlab-ci || pytest
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-test'); logger.track_business_event('test_completion', {'success': True})"

security:
  stage: security
  script:
    - echo "Running security scans..."
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-security'); logger.info('Security scan completed')"

deploy:
  stage: deploy
  script:
    - echo "Deploying application..."
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-deploy'); logger.track_business_event('deployment', {'environment': 'production', 'status': 'success'})"
  when: manual''',
    "gitlab_security_template": '''# GitLab Security Scanning with Storm Logger
include:
  - template: Security/SAST.gitlab-ci.yml
  - template: Security/Dependency-Scanning.gitlab-ci.yml
  - template: Security/Secret-Detection.gitlab-ci.yml
  - template: Security/Container-Scanning.gitlab-ci.yml

variables:
  SAST_CONFIDENCE_LEVEL: "3"
  SAST_EXCLUDED_PATHS: "spec, test, tests, tmp"
  STORM_LOGGER_LEVEL: "INFO"
  STORM_ENABLE_SECURITY_METRICS: "true"

security_monitoring:
  stage: security
  script:
    - echo "Security monitoring with Storm Logger..."
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-security'); logger.track_business_event('security_scan', {'vulnerabilities': 'tracked', 'compliance': 'checked'})"''',
    "gitlab_deployment_template": '''# GitLab Deployment with Storm Logger tracking
deploy_production:
  stage: deploy
  environment:
    name: production
    url: https://production.example.com
  script:
    - echo "Deploying to production..."
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-deploy'); logger.track_business_event('deployment_start', {'environment': 'production', 'version': '$CI_COMMIT_SHA'})"
    - ./deploy.sh
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-deploy'); logger.track_business_event('deployment_success', {'environment': 'production', 'duration': 'tracked'})"
  when: manual
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH''',
    "gitlab_storm_test_integration": '''# Storm Test Script integration with GitLab CI/CD
test_with_storm:
  stage: test
  script:
    - echo "Running tests with Storm Logger integration..."
    # Use Storm test script if available
    - if [ -f "./test.sh" ]; then
        ./test.sh --quick --gitlab-ci
      else
        pytest --cov=. --cov-report=xml
      fi
    # Track test results with Storm Logger
    - python -c "from storm_logger import get_storm_logger; logger = get_storm_logger('gitlab-test'); logger.track_business_event('test_execution', {'framework': 'storm', 'environment': 'gitlab-ci'})"
  coverage: '/^TOTAL.*\\s+(\\d+%)$/'
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage.xml'''
}

# Common pitfalls and solutions
PITFALLS_AND_SOLUTIONS = {
    "prompt_arguments": {
        "issue": "TypeError: FastMCP.prompt() got an unexpected keyword argument 'arguments'",
        "solution": "Use @mcp.prompt without any parameters. Define arguments as function parameters.",
        "example": PROMPT_TEMPLATE
    },
    "client_initialization": {
        "issue": "ValueError: Could not infer a valid transport",
        "solution": "For file paths, pass as string: Client('path/to/server.py')",
        "example": "client = Client(server_path)  # Not Client([python, server_path])"
    },
    "async_tests": {
        "issue": "async def functions are not natively supported",
        "solution": "Install pytest-asyncio and mark tests with @pytest.mark.asyncio",
        "example": "@pytest.mark.asyncio\nasync def test_example():"
    },
    "import_errors": {
        "issue": "Import 'fastmcp' could not be resolved",
        "solution": "Add fastmcp to requirements.txt and pyproject.toml",
        "example": "fastmcp>=0.1.0"
    },
    "gitlab_elicitation_cancelled": {
        "issue": "GitLab elicitation was cancelled by user",
        "solution": "Handle cancellation gracefully and return appropriate status",
        "example": '''if not elicitation_result:
    return json.dumps({
        "status": "cancelled",
        "message": "GitLab operation cancelled by user"
    }, indent=2)'''
    },
    "gitlab_yaml_parsing_error": {
        "issue": "YAML parsing error in GitLab CI/CD configuration",
        "solution": "Use yaml.safe_load() with try/except for error handling",
        "example": '''try:
    config = yaml.safe_load(pipeline_yaml)
except yaml.YAMLError as e:
    return json.dumps({
        "error": "Invalid YAML format",
        "details": str(e)
    }, indent=2)'''
    },
    "gitlab_security_scan_failure": {
        "issue": "GitLab security scanning tools fail to run",
        "solution": "Check GitLab security scanner configuration and permissions",
        "example": '''variables:
  SAST_CONFIDENCE_LEVEL: "3"
  SAST_EXCLUDED_PATHS: "spec, test, tests, tmp"
  STORM_LOGGER_LEVEL: "INFO"'''
    }
}

def get_template(template_type: str, **kwargs) -> str:
    """
    Get a formatted template for MCP component creation
    
    Args:
        template_type: Type of template (tool, resource, prompt, server, test)
        **kwargs: Template variables
        
    Returns:
        Formatted template string
    """
    templates = {
        "tool": TOOL_TEMPLATE,
        "resource": RESOURCE_TEMPLATE,
        "prompt": PROMPT_TEMPLATE,
        "server": MCP_SERVER_TEMPLATE,
        "unit_test": UNIT_TEST_TEMPLATE,
        "integration_test": INTEGRATION_TEST_TEMPLATE
    }
    
    template = templates.get(template_type, "")
    if template and kwargs:
        return template.format(**kwargs)
    return template

def get_pattern(pattern_name: str) -> str:
    """Get a common pattern example"""
    return COMMON_PATTERNS.get(pattern_name, "")

def get_solution(issue_name: str) -> dict:
    """Get solution for a common pitfall"""
    return PITFALLS_AND_SOLUTIONS.get(issue_name, {})