"""
Python tooling templates and configurations for Storm Logger development
"""

import json
from typing import Dict, Any, List


def get_python_tooling_templates() -> str:
    """
    Get comprehensive Python tooling templates and configurations
    
    Returns:
        JSON string with tooling templates, configurations, and best practices
    """
    templates = {
        "development_environment": {
            "pyproject_toml": {
                "description": "Modern Python project configuration",
                "template": """
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "storm-logger-project"
version = "1.0.0"
description = "Storm Logger based Python project"
readme = "README.md"
license = {text = "MIT"}
authors = [
    {name = "Your Name", email = "your.email@example.com"},
]
classifiers = [
    "Development Status :: 4 - Beta",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
    "Programming Language :: Python :: 3.12",
]
requires-python = ">=3.10"
dependencies = [
    "storm-logger>=2.0.0",
    "rich>=13.0.0",
    "click>=8.0.0",
    "pydantic>=2.0.0",
    "httpx>=0.25.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0.0",
    "pytest-cov>=4.0.0",
    "pytest-asyncio>=0.21.0",
    "black>=23.0.0",
    "ruff>=0.1.0",
    "mypy>=1.0.0",
    "pre-commit>=3.0.0",
    "sphinx>=7.0.0",
    "sphinx-rtd-theme>=1.3.0",
]
test = [
    "pytest>=7.0.0",
    "pytest-cov>=4.0.0",
    "pytest-asyncio>=0.21.0",
    "pytest-mock>=3.11.0",
    "factory-boy>=3.3.0",
    "hypothesis>=6.82.0",
]
docs = [
    "sphinx>=7.0.0",
    "sphinx-rtd-theme>=1.3.0",
    "myst-parser>=2.0.0",
]

[project.urls]
Homepage = "https://github.com/yourusername/storm-logger-project"
Documentation = "https://storm-logger-project.readthedocs.io"
Repository = "https://github.com/yourusername/storm-logger-project"
Issues = "https://github.com/yourusername/storm-logger-project/issues"

[project.scripts]
storm-project = "storm_project.cli:main"

[tool.setuptools.packages.find]
where = ["src"]
include = ["storm_project*"]

[tool.setuptools.package-data]
storm_project = ["py.typed", "*.pyi"]

# Black configuration
[tool.black]
line-length = 100
target-version = ['py310', 'py311', 'py312']
include = '\\.pyi?$'
exclude = '''
/(
    \\.git
  | \\.hg
  | \\.mypy_cache
  | \\.nox
  | \\.tox
  | \\.venv
  | venv
  | \\.svn
  | _build
  | buck-out
  | build
  | dist
)/
'''

# Ruff configuration
[tool.ruff]
line-length = 100
target-version = "py310"
select = [
    "E",   # pycodestyle errors
    "W",   # pycodestyle warnings
    "F",   # pyflakes
    "I",   # isort
    "N",   # pep8-naming
    "D",   # pydocstyle
    "UP",  # pyupgrade
    "ANN", # flake8-annotations
    "S",   # flake8-bandit
    "B",   # flake8-bugbear
    "A",   # flake8-builtins
    "C4",  # flake8-comprehensions
    "T10", # flake8-debugger
    "T20", # flake8-print
    "PT",  # flake8-pytest-style
    "Q",   # flake8-quotes
    "RET", # flake8-return
    "SIM", # flake8-simplify
    "TCH", # flake8-type-checking
    "ARG", # flake8-unused-arguments
    "PTH", # flake8-use-pathlib
    "ERA", # eradicate
    "PGH", # pygrep-hooks
    "PL",  # pylint
    "TRY", # tryceratops
    "FLY", # flynt
    "NPY", # numpy
    "PERF", # perflint
    "FURB", # refurb
    "LOG", # flake8-logging
]
ignore = [
    "D100",  # Missing docstring in public module
    "D104",  # Missing docstring in public package
    "D107",  # Missing docstring in __init__
    "ANN101", # Missing type annotation for self
    "ANN102", # Missing type annotation for cls
    "S101",  # Use of assert
    "PT011", # pytest.raises too broad
    "T201",  # print found (for debugging)
    "T203",  # pprint found (for debugging)
]
exclude = [
    ".git",
    ".hg",
    ".mypy_cache",
    ".nox",
    ".tox",
    ".venv",
    "venv",
    ".svn",
    "_build",
    "buck-out",
    "build",
    "dist",
]

[tool.ruff.per-file-ignores]
"tests/*" = ["S101", "ANN001", "ANN201", "D103"]
"scripts/*" = ["T201", "S101"]

[tool.ruff.pydocstyle]
convention = "google"

[tool.ruff.isort]
known-first-party = ["storm_project"]

# MyPy configuration
[tool.mypy]
python_version = "3.10"
warn_return_any = true
warn_unused_configs = true
warn_redundant_casts = true
warn_unused_ignores = true
warn_unreachable = true
check_untyped_defs = true
disallow_any_generics = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
disallow_untyped_decorators = true
no_implicit_optional = true
strict_optional = true
show_error_codes = true
show_column_numbers = true
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = ["tests.*"]
disallow_untyped_defs = false

# Pytest configuration
[tool.pytest.ini_options]
minversion = "7.0"
addopts = [
    "--strict-markers",
    "--strict-config",
    "--cov=storm_project",
    "--cov-report=term-missing",
    "--cov-report=html",
    "--cov-report=xml",
    "--cov-fail-under=90",
]
testpaths = ["tests"]
markers = [
    "slow: marks tests as slow (deselect with '-m \"not slow\"')",
    "integration: marks tests as integration tests",
    "unit: marks tests as unit tests",
    "functional: marks tests as functional tests",
    "performance: marks tests as performance tests",
]
asyncio_mode = "auto"

# Coverage configuration
[tool.coverage.run]
source = ["src"]
omit = [
    "tests/*",
    "scripts/*",
    "docs/*",
    "**/__pycache__/*",
    "**/.pytest_cache/*",
]

[tool.coverage.report]
exclude_lines = [
    "pragma: no cover",
    "def __repr__",
    "if self.debug:",
    "if settings.DEBUG",
    "raise AssertionError",
    "raise NotImplementedError",
    "if 0:",
    "if __name__ == .__main__.:",
    "class .*\\bProtocol\\):",
    "@(abc\\.)?abstractmethod",
]
show_missing = true
precision = 2

[tool.coverage.html]
directory = "htmlcov"
"""
            },
            "requirements_txt": {
                "description": "Dependencies specification",
                "template": """
# Production dependencies
storm-logger>=2.0.0
rich>=13.0.0
click>=8.0.0
pydantic>=2.0.0
httpx>=0.25.0

# Development dependencies (install with: pip install -r requirements-dev.txt)
"""
            },
            "requirements_dev_txt": {
                "description": "Development dependencies",
                "template": """
# Include production requirements
-r requirements.txt

# Testing
pytest>=7.0.0
pytest-cov>=4.0.0
pytest-asyncio>=0.21.0
pytest-mock>=3.11.0
factory-boy>=3.3.0
hypothesis>=6.82.0

# Code quality
black>=23.0.0
ruff>=0.1.0
mypy>=1.0.0
pre-commit>=3.0.0

# Documentation
sphinx>=7.0.0
sphinx-rtd-theme>=1.3.0
myst-parser>=2.0.0

# Development tools
ipython>=8.0.0
ipdb>=0.13.0
"""
            },
            "gitignore": {
                "description": "Git ignore patterns for Python projects",
                "template": """
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
Pipfile.lock

# PEP 582
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Local development
.local/
temp/
tmp/
"""
            }
        },
        "ci_cd_templates": {
            "github_actions": {
                "description": "GitHub Actions workflow for Python projects",
                "template": """
name: CI/CD Pipeline

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [3.10, 3.11, 3.12]

    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v4
      with:
        python-version: ${{ matrix.python-version }}
    
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements-dev.txt
    
    - name: Lint with ruff
      run: |
        ruff check .
        ruff format --check .
    
    - name: Type check with mypy
      run: mypy src/
    
    - name: Test with pytest
      run: |
        pytest --cov=src --cov-report=xml
    
    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v3
      with:
        file: ./coverage.xml
        flags: unittests
        name: codecov-umbrella

  security:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    
    - name: Run security scan
      uses: pypa/gh-action-pip-audit@v1.0.8
      with:
        inputs: requirements.txt requirements-dev.txt

  build:
    needs: [test, security]
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: 3.11
    
    - name: Install build dependencies
      run: |
        python -m pip install --upgrade pip
        pip install build
    
    - name: Build package
      run: python -m build
    
    - name: Upload artifacts
      uses: actions/upload-artifact@v3
      with:
        name: dist
        path: dist/

  deploy:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Download artifacts
      uses: actions/download-artifact@v3
      with:
        name: dist
        path: dist/
    
    - name: Publish to PyPI
      uses: pypa/gh-action-pypi-publish@v1.8.10
      with:
        user: __token__
        password: ${{ secrets.PYPI_API_TOKEN }}
"""
            },
            "pre_commit_config": {
                "description": "Pre-commit hooks configuration",
                "template": """
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
      - id: check-merge-conflict
      - id: check-toml
      - id: debug-statements
      - id: mixed-line-ending

  - repo: https://github.com/psf/black
    rev: 23.9.1
    hooks:
      - id: black
        language_version: python3.11

  - repo: https://github.com/charliermarsh/ruff-pre-commit
    rev: v0.1.3
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.6.1
    hooks:
      - id: mypy
        additional_dependencies: [types-requests]
        args: [--strict]

  - repo: https://github.com/pycqa/bandit
    rev: 1.7.5
    hooks:
      - id: bandit
        args: ["-c", "pyproject.toml"]

  - repo: https://github.com/PyCQA/docformatter
    rev: v1.7.5
    hooks:
      - id: docformatter
        args: [--in-place]

  - repo: local
    hooks:
      - id: pytest
        name: pytest
        entry: pytest
        language: system
        pass_filenames: false
        always_run: true
        args: [--cov=src, --cov-fail-under=90]
"""
            }
        },
        "docker_templates": {
            "dockerfile": {
                "description": "Multi-stage Dockerfile for Python applications",
                "template": """
# Build stage
FROM python:3.11-slim as builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y \\
    gcc \\
    && rm -rf /var/lib/apt/lists/*

# Copy requirements first for better caching
COPY requirements*.txt ./
RUN pip install --user --no-cache-dir -r requirements.txt

# Copy source code
COPY src/ ./src/
COPY pyproject.toml ./
COPY README.md ./

# Install the package
RUN pip install --user .

# Runtime stage
FROM python:3.11-slim

WORKDIR /app

# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser

# Copy installed packages from builder
COPY --from=builder /root/.local /home/appuser/.local

# Copy application
COPY --from=builder /app/src ./src

# Set PATH to include user packages
ENV PATH=/home/appuser/.local/bin:$PATH

# Switch to non-root user
USER appuser

# Set environment variables
ENV PYTHONPATH=/app/src
ENV PYTHONUNBUFFERED=1

# Health check
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \\
    CMD python -c "import storm_project; print('OK')" || exit 1

# Default command
CMD ["python", "-m", "storm_project"]
"""
            },
            "docker_compose": {
                "description": "Docker Compose for development",
                "template": """
version: '3.8'

services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - STORM_LOGGER_LEVEL=DEBUG
      - STORM_LOGGER_FORMAT=json
    volumes:
      - ./src:/app/src
      - ./tests:/app/tests
    depends_on:
      - redis
      - postgres
    networks:
      - storm-network

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    networks:
      - storm-network

  postgres:
    image: postgres:15-alpine
    environment:
      - POSTGRES_DB=storm_project
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - storm-network

  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus
    networks:
      - storm-network

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
    volumes:
      - grafana_data:/var/lib/grafana
    networks:
      - storm-network

volumes:
  redis_data:
  postgres_data:
  prometheus_data:
  grafana_data:

networks:
  storm-network:
    driver: bridge
"""
            }
        },
        "testing_templates": {
            "conftest_py": {
                "description": "Pytest configuration and fixtures",
                "template": """
import pytest
from unittest.mock import Mock
from storm_logger import StormLogger
from storm_project.config import get_config


@pytest.fixture
def storm_logger():
    \"\"\"Storm Logger fixture for testing.\"\"\"
    logger = StormLogger()
    logger.set_level('DEBUG')
    return logger


@pytest.fixture
def mock_storm_logger():
    \"\"\"Mock Storm Logger fixture.\"\"\"
    mock_logger = Mock(spec=StormLogger)
    mock_logger.info = Mock()
    mock_logger.debug = Mock()
    mock_logger.warning = Mock()
    mock_logger.error = Mock()
    mock_logger.critical = Mock()
    mock_logger.track_business_event = Mock()
    return mock_logger


@pytest.fixture
def test_config():
    \"\"\"Test configuration fixture.\"\"\"
    config = get_config()
    config.database_url = "sqlite:///:memory:"
    config.redis_url = "redis://localhost:6379/1"
    config.debug = True
    return config


@pytest.fixture
def sample_data():
    \"\"\"Sample data fixture.\"\"\"
    return {
        'users': [
            {'id': 1, 'name': 'Alice', 'email': 'alice@example.com'},
            {'id': 2, 'name': 'Bob', 'email': 'bob@example.com'},
        ],
        'products': [
            {'id': 1, 'name': 'Widget', 'price': 10.99},
            {'id': 2, 'name': 'Gadget', 'price': 25.50},
        ]
    }


@pytest.fixture
async def async_storm_logger():
    \"\"\"Async Storm Logger fixture.\"\"\"
    logger = StormLogger()
    logger.set_level('DEBUG')
    yield logger
    # Cleanup if needed
    await logger.close()


@pytest.fixture
def temp_file(tmp_path):
    \"\"\"Temporary file fixture.\"\"\"
    file_path = tmp_path / "test_file.txt"
    file_path.write_text("test content")
    return file_path


@pytest.fixture
def mock_external_api():
    \"\"\"Mock external API fixture.\"\"\"
    with patch('storm_project.external_api.requests') as mock_requests:
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {'status': 'success'}
        mock_requests.get.return_value = mock_response
        mock_requests.post.return_value = mock_response
        yield mock_requests


@pytest.fixture(autouse=True)
def setup_test_environment(monkeypatch):
    \"\"\"Setup test environment variables.\"\"\"
    monkeypatch.setenv('STORM_LOGGER_LEVEL', 'DEBUG')
    monkeypatch.setenv('STORM_LOGGER_FORMAT', 'json')
    monkeypatch.setenv('ENVIRONMENT', 'test')
"""
            },
            "test_template": {
                "description": "Test file template",
                "template": """
import pytest
from unittest.mock import Mock, patch
from storm_logger import StormLogger
from storm_project.services.user_service import UserService
from storm_project.models.user import User


class TestUserService:
    \"\"\"Test cases for UserService.\"\"\"
    
    def test_create_user_success(self, storm_logger, sample_data):
        \"\"\"Test successful user creation.\"\"\"
        # Arrange
        user_data = sample_data['users'][0]
        mock_repository = Mock()
        mock_repository.create.return_value = User(**user_data)
        
        service = UserService(storm_logger, mock_repository)
        
        # Act
        result = service.create_user(user_data)
        
        # Assert
        assert result.name == user_data['name']
        assert result.email == user_data['email']
        mock_repository.create.assert_called_once_with(user_data)
        storm_logger.info.assert_called_once()
    
    def test_create_user_validation_error(self, storm_logger):
        \"\"\"Test user creation with validation error.\"\"\"
        # Arrange
        invalid_data = {'name': '', 'email': 'invalid-email'}
        mock_repository = Mock()
        service = UserService(storm_logger, mock_repository)
        
        # Act & Assert
        with pytest.raises(ValueError, match="Invalid user data"):
            service.create_user(invalid_data)
        
        storm_logger.error.assert_called_once()
        mock_repository.create.assert_not_called()
    
    @pytest.mark.parametrize("name,email,expected_error", [
        ("", "test@example.com", "Name is required"),
        ("Test", "", "Email is required"),
        ("Test", "invalid", "Invalid email format"),
    ])
    def test_create_user_validation_parametrized(
        self, storm_logger, name, email, expected_error
    ):
        \"\"\"Test user creation validation with different invalid inputs.\"\"\"
        # Arrange
        user_data = {'name': name, 'email': email}
        mock_repository = Mock()
        service = UserService(storm_logger, mock_repository)
        
        # Act & Assert
        with pytest.raises(ValueError, match=expected_error):
            service.create_user(user_data)
    
    @pytest.mark.asyncio
    async def test_async_operation(self, async_storm_logger):
        \"\"\"Test asynchronous operation.\"\"\"
        # Arrange
        service = UserService(async_storm_logger, mock_repository)
        
        # Act
        result = await service.async_operation()
        
        # Assert
        assert result is not None
        async_storm_logger.info.assert_called_once()
    
    @pytest.mark.integration
    def test_integration_with_database(self, storm_logger, test_config):
        \"\"\"Integration test with real database.\"\"\"
        # Arrange
        from storm_project.repositories.user_repository import UserRepository
        repository = UserRepository(test_config.database_url)
        service = UserService(storm_logger, repository)
        
        # Act
        user_data = {'name': 'Integration Test', 'email': 'integration@test.com'}
        result = service.create_user(user_data)
        
        # Assert
        assert result.id is not None
        assert result.name == user_data['name']
        
        # Verify in database
        saved_user = repository.find_by_id(result.id)
        assert saved_user is not None
        assert saved_user.name == user_data['name']
    
    @pytest.mark.performance
    def test_performance_benchmark(self, storm_logger, benchmark):
        \"\"\"Performance benchmark test.\"\"\"
        # Arrange
        mock_repository = Mock()
        service = UserService(storm_logger, mock_repository)
        user_data = {'name': 'Performance Test', 'email': 'perf@test.com'}
        
        # Act & Assert
        result = benchmark(service.create_user, user_data)
        assert result is not None


@pytest.mark.slow
class TestUserServiceSlowOperations:
    \"\"\"Test cases for slow operations.\"\"\"
    
    def test_bulk_user_creation(self, storm_logger, sample_data):
        \"\"\"Test bulk user creation (slow operation).\"\"\"
        # Arrange
        users_data = sample_data['users'] * 1000  # Large dataset
        mock_repository = Mock()
        service = UserService(storm_logger, mock_repository)
        
        # Act
        results = service.bulk_create_users(users_data)
        
        # Assert
        assert len(results) == len(users_data)
        assert mock_repository.bulk_create.called
"""
            }
        },
        "project_structure": {
            "description": "Recommended project structure",
            "template": {
                "src/": {
                    "description": "Source code directory",
                    "files": {
                        "storm_project/": {
                            "__init__.py": "Package initialization",
                            "main.py": "Application entry point",
                            "config.py": "Configuration management",
                            "cli.py": "Command-line interface",
                            "core/": {
                                "__init__.py": "",
                                "models.py": "Data models",
                                "exceptions.py": "Custom exceptions",
                                "interfaces.py": "Abstract interfaces"
                            },
                            "services/": {
                                "__init__.py": "",
                                "user_service.py": "User business logic",
                                "data_service.py": "Data processing logic"
                            },
                            "repositories/": {
                                "__init__.py": "",
                                "user_repository.py": "User data access",
                                "base_repository.py": "Base repository"
                            },
                            "utils/": {
                                "__init__.py": "",
                                "helpers.py": "Helper functions",
                                "validators.py": "Data validation"
                            }
                        }
                    }
                },
                "tests/": {
                    "description": "Test directory",
                    "files": {
                        "conftest.py": "Pytest configuration",
                        "unit/": {
                            "test_services.py": "Service unit tests",
                            "test_repositories.py": "Repository unit tests",
                            "test_utils.py": "Utility unit tests"
                        },
                        "integration/": {
                            "test_database.py": "Database integration tests",
                            "test_api.py": "API integration tests"
                        },
                        "functional/": {
                            "test_user_workflows.py": "User workflow tests",
                            "test_data_processing.py": "Data processing tests"
                        },
                        "performance/": {
                            "test_benchmarks.py": "Performance benchmarks"
                        }
                    }
                },
                "docs/": {
                    "description": "Documentation",
                    "files": {
                        "conf.py": "Sphinx configuration",
                        "index.rst": "Documentation index",
                        "api.rst": "API documentation",
                        "tutorials/": {
                            "quickstart.rst": "Quick start guide",
                            "advanced.rst": "Advanced usage"
                        }
                    }
                },
                "scripts/": {
                    "description": "Build and deployment scripts",
                    "files": {
                        "build.sh": "Build script",
                        "deploy.sh": "Deployment script",
                        "test.sh": "Test runner script"
                    }
                }
            }
        },
        "makefile_template": {
            "description": "Makefile for common development tasks",
            "template": """
.PHONY: help install install-dev test test-cov lint format type-check security clean docs build deploy

help:  ## Show this help message
	@echo "Available commands:"
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  \\033[36m%-20s\\033[0m %s\\n", $$1, $$2}'

install:  ## Install production dependencies
	pip install -r requirements.txt

install-dev:  ## Install development dependencies
	pip install -r requirements-dev.txt
	pre-commit install

test:  ## Run tests
	pytest tests/

test-cov:  ## Run tests with coverage
	pytest --cov=src --cov-report=html --cov-report=term-missing tests/

test-fast:  ## Run fast tests only
	pytest -m "not slow" tests/

lint:  ## Run linting
	ruff check .

format:  ## Format code
	black .
	ruff format .

type-check:  ## Run type checking
	mypy src/

security:  ## Run security checks
	bandit -r src/
	pip-audit

clean:  ## Clean build artifacts
	rm -rf build/ dist/ *.egg-info/
	find . -type d -name __pycache__ -exec rm -rf {} +
	find . -type f -name "*.pyc" -delete
	rm -rf .coverage htmlcov/ .pytest_cache/ .mypy_cache/

docs:  ## Build documentation
	cd docs && make html

build:  ## Build package
	python -m build

deploy:  ## Deploy to PyPI
	twine upload dist/*

docker-build:  ## Build Docker image
	docker build -t storm-project .

docker-run:  ## Run Docker container
	docker run -it --rm storm-project

docker-compose-up:  ## Start services with Docker Compose
	docker-compose up -d

docker-compose-down:  ## Stop services with Docker Compose
	docker-compose down

all: install-dev lint type-check test-cov build  ## Run all quality checks
"""
        }
    }
    
    return json.dumps(templates, indent=2)


def get_storm_logger_integration_templates() -> str:
    """
    Get Storm Logger integration templates
    
    Returns:
        JSON string with Storm Logger integration patterns and templates
    """
    templates = {
        "basic_integration": {
            "description": "Basic Storm Logger integration",
            "template": """
from storm_logger import StormLogger, StormLoggerConfig
from storm_logger.professional_logger import ProfessionalStormLogger

# Basic setup
logger = StormLogger()
logger.info("Application started")

# Professional setup
config = StormLoggerConfig(
    level="INFO",
    format="json",
    enable_console=True,
    enable_metrics=True
)
professional_logger = ProfessionalStormLogger(config)

# Business event tracking
professional_logger.track_business_event("user_login", {
    "user_id": 123,
    "login_method": "oauth",
    "timestamp": "2025-01-18T10:30:00Z"
})

# Professional console output
professional_logger.log_business_success("User registration completed successfully")
"""
        },
        "service_layer_integration": {
            "description": "Service layer integration with Storm Logger",
            "template": """
from typing import Dict, Any, Optional
from storm_logger import StormLogger
from storm_project.repositories.user_repository import UserRepository
from storm_project.models.user import User

class UserService:
    def __init__(self, logger: StormLogger, user_repository: UserRepository):
        self.logger = logger
        self.user_repository = user_repository
    
    def create_user(self, user_data: Dict[str, Any]) -> User:
        self.logger.info("Creating user", extra={"user_data": user_data})
        
        try:
            # Validate user data
            self._validate_user_data(user_data)
            
            # Create user
            user = self.user_repository.create(user_data)
            
            # Track business event
            self.logger.track_business_event("user_created", {
                "user_id": user.id,
                "registration_method": user_data.get("registration_method", "direct")
            })
            
            self.logger.info("User created successfully", extra={"user_id": user.id})
            return user
            
        except ValidationError as e:
            self.logger.error("User validation failed", extra={"error": str(e)})
            raise
        except Exception as e:
            self.logger.error("User creation failed", extra={"error": str(e)})
            raise
    
    def _validate_user_data(self, user_data: Dict[str, Any]) -> None:
        self.logger.debug("Validating user data")
        
        required_fields = ["name", "email"]
        for field in required_fields:
            if not user_data.get(field):
                raise ValidationError(f"{field} is required")
        
        # Email validation
        if "@" not in user_data["email"]:
            raise ValidationError("Invalid email format")
        
        self.logger.debug("User data validation passed")
"""
        },
        "context_manager_integration": {
            "description": "Context manager integration with Storm Logger",
            "template": """
from contextlib import contextmanager
from typing import Dict, Any, Generator
from storm_logger import StormLogger

@contextmanager
def business_operation_context(
    logger: StormLogger, 
    operation_name: str, 
    context_data: Dict[str, Any]
) -> Generator[StormLogger, None, None]:
    \"\"\"Context manager for business operations with logging.\"\"\"
    
    # Start operation
    logger.info(f"Starting {operation_name}", extra=context_data)
    operation_start_time = time.time()
    
    try:
        # Update logger context
        original_context = logger.get_context()
        logger.update_context({
            "operation": operation_name,
            **context_data
        })
        
        yield logger
        
        # Success
        operation_time = time.time() - operation_start_time
        logger.track_business_event(f"{operation_name}_completed", {
            "duration_seconds": operation_time,
            "status": "success",
            **context_data
        })
        logger.info(f"Completed {operation_name}", extra={
            "duration_seconds": operation_time
        })
        
    except Exception as e:
        # Error handling
        operation_time = time.time() - operation_start_time
        logger.track_business_event(f"{operation_name}_failed", {
            "duration_seconds": operation_time,
            "error": str(e),
            "status": "error",
            **context_data
        })
        logger.error(f"Failed {operation_name}", extra={
            "error": str(e),
            "duration_seconds": operation_time
        })
        raise
        
    finally:
        # Restore context
        logger.set_context(original_context)

# Usage
def process_user_data(user_id: int):
    logger = StormLogger()
    
    with business_operation_context(
        logger, 
        "user_data_processing", 
        {"user_id": user_id}
    ) as ctx_logger:
        # Your business logic here
        ctx_logger.info("Processing user data")
        # ... processing logic ...
        ctx_logger.info("User data processed successfully")
"""
        },
        "decorator_integration": {
            "description": "Decorator integration with Storm Logger",
            "template": """
import functools
import time
from typing import Any, Callable
from storm_logger import StormLogger

def track_business_operation(
    operation_name: str, 
    track_performance: bool = True,
    track_errors: bool = True
):
    \"\"\"Decorator to track business operations with Storm Logger.\"\"\"
    
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def wrapper(*args, **kwargs) -> Any:
            logger = StormLogger()
            
            # Start tracking
            start_time = time.time()
            logger.info(f"Starting {operation_name}", extra={
                "function": func.__name__,
                "args_count": len(args),
                "kwargs_count": len(kwargs)
            })
            
            try:
                # Execute function
                result = func(*args, **kwargs)
                
                # Track success
                duration = time.time() - start_time
                if track_performance:
                    logger.track_business_event(f"{operation_name}_performance", {
                        "function": func.__name__,
                        "duration_seconds": duration,
                        "status": "success"
                    })
                
                logger.info(f"Completed {operation_name}", extra={
                    "function": func.__name__,
                    "duration_seconds": duration
                })
                
                return result
                
            except Exception as e:
                # Track error
                duration = time.time() - start_time
                if track_errors:
                    logger.track_business_event(f"{operation_name}_error", {
                        "function": func.__name__,
                        "duration_seconds": duration,
                        "error": str(e),
                        "error_type": type(e).__name__,
                        "status": "error"
                    })
                
                logger.error(f"Failed {operation_name}", extra={
                    "function": func.__name__,
                    "error": str(e),
                    "duration_seconds": duration
                })
                raise
                
        return wrapper
    return decorator

# Usage
@track_business_operation("user_registration", track_performance=True)
def register_user(user_data: dict):
    # Your registration logic here
    pass

@track_business_operation("data_processing", track_performance=True, track_errors=True)
def process_data(data: list):
    # Your data processing logic here
    pass
"""
        },
        "async_integration": {
            "description": "Async integration with Storm Logger",
            "template": """
import asyncio
import time
from typing import Dict, Any
from storm_logger import StormLogger

class AsyncBusinessService:
    def __init__(self):
        self.logger = StormLogger()
    
    async def process_async_operation(self, operation_data: Dict[str, Any]) -> Dict[str, Any]:
        \"\"\"Async operation with Storm Logger integration.\"\"\"
        
        operation_id = operation_data.get("id", "unknown")
        self.logger.info("Starting async operation", extra={
            "operation_id": operation_id,
            "operation_type": "async_processing"
        })
        
        start_time = time.time()
        
        try:
            # Simulate async work
            await asyncio.sleep(0.1)
            
            # Process data
            result = await self._process_data(operation_data)
            
            # Track success
            duration = time.time() - start_time
            self.logger.track_business_event("async_operation_completed", {
                "operation_id": operation_id,
                "duration_seconds": duration,
                "status": "success",
                "result_size": len(str(result))
            })
            
            self.logger.info("Async operation completed", extra={
                "operation_id": operation_id,
                "duration_seconds": duration
            })
            
            return result
            
        except Exception as e:
            # Track error
            duration = time.time() - start_time
            self.logger.track_business_event("async_operation_failed", {
                "operation_id": operation_id,
                "duration_seconds": duration,
                "error": str(e),
                "status": "error"
            })
            
            self.logger.error("Async operation failed", extra={
                "operation_id": operation_id,
                "error": str(e),
                "duration_seconds": duration
            })
            raise
    
    async def _process_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
        \"\"\"Internal async data processing.\"\"\"
        
        self.logger.debug("Processing data", extra={"data_keys": list(data.keys())})
        
        # Simulate processing
        await asyncio.sleep(0.05)
        
        # Return processed result
        result = {
            "processed": True,
            "input_data": data,
            "processed_at": time.time()
        }
        
        self.logger.debug("Data processing completed", extra={
            "result_keys": list(result.keys())
        })
        
        return result

# Usage
async def main():
    service = AsyncBusinessService()
    
    # Process multiple operations concurrently
    tasks = []
    for i in range(5):
        operation_data = {"id": f"op_{i}", "data": f"test_data_{i}"}
        task = service.process_async_operation(operation_data)
        tasks.append(task)
    
    results = await asyncio.gather(*tasks)
    
    logger = StormLogger()
    logger.info("All async operations completed", extra={
        "total_operations": len(results),
        "success_count": len(results)
    })

if __name__ == "__main__":
    asyncio.run(main())
"""
        }
    }
    
    return json.dumps(templates, indent=2)


def get_development_workflow_templates() -> str:
    """
    Get development workflow templates
    
    Returns:
        JSON string with development workflow templates and best practices
    """
    workflows = {
        "development_workflow": {
            "setup_new_project": {
                "description": "Steps to set up a new Python project with Storm Logger",
                "steps": [
                    "1. Create project directory and virtual environment",
                    "2. Install Storm Logger and dependencies",
                    "3. Set up project structure",
                    "4. Configure development tools (Black, Ruff, MyPy)",
                    "5. Set up pre-commit hooks",
                    "6. Create initial tests",
                    "7. Configure CI/CD pipeline",
                    "8. Set up monitoring and logging"
                ],
                "commands": [
                    "mkdir storm-project && cd storm-project",
                    "python -m venv venv && source venv/bin/activate",
                    "pip install storm-logger",
                    "pip install -r requirements-dev.txt",
                    "pre-commit install",
                    "pytest tests/",
                    "git init && git add . && git commit -m 'Initial commit'"
                ]
            },
            "daily_development": {
                "description": "Daily development workflow",
                "steps": [
                    "1. Pull latest changes",
                    "2. Run tests to ensure everything works",
                    "3. Create feature branch",
                    "4. Implement changes with Storm Logger integration",
                    "5. Run linting and formatting",
                    "6. Run tests with coverage",
                    "7. Commit changes",
                    "8. Push branch and create pull request"
                ],
                "commands": [
                    "git pull origin main",
                    "pytest tests/",
                    "git checkout -b feature/new-feature",
                    "# Make your changes",
                    "ruff check . && black .",
                    "pytest --cov=src tests/",
                    "git add . && git commit -m 'Add new feature'",
                    "git push origin feature/new-feature"
                ]
            },
            "testing_workflow": {
                "description": "Testing workflow with Storm Logger",
                "steps": [
                    "1. Write unit tests with Storm Logger fixtures",
                    "2. Write integration tests",
                    "3. Write functional tests",
                    "4. Run performance tests",
                    "5. Check test coverage",
                    "6. Validate logging behavior"
                ],
                "commands": [
                    "pytest tests/unit/",
                    "pytest tests/integration/",
                    "pytest tests/functional/",
                    "pytest tests/performance/",
                    "pytest --cov=src --cov-report=html",
                    "# Check htmlcov/index.html for coverage report"
                ]
            },
            "release_workflow": {
                "description": "Release workflow",
                "steps": [
                    "1. Update version number",
                    "2. Update changelog",
                    "3. Run full test suite",
                    "4. Build package",
                    "5. Test package installation",
                    "6. Create release tag",
                    "7. Deploy to PyPI",
                    "8. Create GitHub release"
                ],
                "commands": [
                    "# Update version in pyproject.toml",
                    "# Update CHANGELOG.md",
                    "pytest tests/",
                    "python -m build",
                    "pip install dist/*.whl",
                    "git tag v1.0.0",
                    "twine upload dist/*",
                    "# Create GitHub release"
                ]
            }
        }
    }
    
    return json.dumps(workflows, indent=2)