# Contributing to CPAP MCP Server

Thank you for your interest in contributing! This document provides guidelines and instructions for contributing to the CPAP MCP Server project.

## Table of Contents

- [Code of Conduct](#code-of-conduct)
- [Getting Started](#getting-started)
- [Development Setup](#development-setup)
- [How to Contribute](#how-to-contribute)
- [Code Quality Standards](#code-quality-standards)
- [Testing Requirements](#testing-requirements)
- [Pull Request Process](#pull-request-process)
- [Style Guide](#style-guide)
- [Documentation](#documentation)
- [Community](#community)

## Code of Conduct

### Our Pledge

We are committed to providing a welcoming and inclusive environment for all contributors, regardless of background or experience level.

### Expected Behavior

- Be respectful and considerate
- Welcome newcomers and help them get started
- Focus on constructive feedback
- Be patient with questions and discussions
- Respect differing viewpoints and experiences

### Unacceptable Behavior

- Harassment or discrimination of any kind
- Trolling, insulting, or derogatory comments
- Publishing others' private information
- Any conduct inappropriate for a professional setting

## Getting Started

### Prerequisites

Before contributing, ensure you have:

- Python 3.10 or higher installed
- Git installed and configured
- A GitHub account
- Familiarity with pytest for testing
- Understanding of MCP (Model Context Protocol)

### First-Time Contributors

If this is your first contribution:

1. **Find an Issue**: Look for issues labeled `good first issue` or `help wanted`
2. **Ask Questions**: Don't hesitate to ask for clarification in the issue comments
3. **Small Changes**: Start with small, manageable changes
4. **Read the Docs**: Familiarize yourself with the [Usage Guide](USAGE.md) and [Development Guide](DEVELOPMENT.md)

## Development Setup

See the [Development Guide](DEVELOPMENT.md) for detailed setup instructions.

Quick setup:

```bash
# Clone the repository with submodules
git clone --recursive https://github.com/dynacylabs/cpap-mcp.git
cd cpap-mcp

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode
pip install -e .
pip install -r requirements.txt

# Run tests to verify setup
./run_tests.sh unit
```

## How to Contribute

### Types of Contributions

We welcome various types of contributions:

- **Bug Fixes**: Fix issues reported in the issue tracker
- **New Features**: Add new MCP tools or enhance existing ones
- **Documentation**: Improve docs, add examples, fix typos
- **Tests**: Add test coverage, improve test quality
- **Performance**: Optimize code for better performance
- **Refactoring**: Improve code structure and readability
- **CPAP Support**: Add support for new CPAP devices or data formats

### Reporting Bugs

When reporting bugs, include:

- **Clear Title**: Descriptive summary of the issue
- **Description**: Detailed explanation of the problem
- **Steps to Reproduce**: Step-by-step instructions
- **Expected Behavior**: What you expected to happen
- **Actual Behavior**: What actually happened
- **Environment**:
  - Python version
  - OS and version
  - CPAP device model (if relevant)
- **Sample Data**: Anonymized CPAP data if possible (remove personal info)
- **Logs**: Relevant error messages or logs

### Suggesting Features

For feature requests:

1. **Check Existing Issues**: Search for similar requests
2. **Describe the Use Case**: Why is this feature needed?
3. **Propose a Solution**: How should it work?
4. **Consider Alternatives**: What other approaches did you consider?
5. **Breaking Changes**: Will this require breaking changes?

### Submitting Changes

1. **Fork the Repository**: Create your own fork
2. **Create a Branch**: Use a descriptive name
   ```bash
   git checkout -b feature/add-resmed-airsense11-support
   git checkout -b fix/session-duration-calculation
   ```
3. **Make Changes**: Implement your changes
4. **Write Tests**: Add tests for new functionality
5. **Run Tests**: Ensure all tests pass
   ```bash
   ./run_tests.sh all
   ```
6. **Commit Changes**: Use clear commit messages
   ```bash
   git commit -m "Add support for ResMed AirSense 11 data format"
   ```
7. **Push to Fork**: Push your branch
   ```bash
   git push origin feature/add-resmed-airsense11-support
   ```
8. **Open Pull Request**: Submit a PR with clear description

## Code Quality Standards

### Code Formatting

We use **Black** for code formatting:

```bash
# Format all code
black src/ tests/

# Check formatting without making changes
black --check src/ tests/
```

Configuration in `pyproject.toml`:
```toml
[tool.black]
line-length = 100
target-version = ["py310"]
```

### Linting

We use **Ruff** for linting:

```bash
# Run linter
ruff check src/ tests/

# Auto-fix issues
ruff check --fix src/ tests/
```

### Type Checking

We encourage type hints. Use **mypy** for type checking:

```bash
mypy src/
```

### Code Review Checklist

Before submitting, ensure:

- [ ] Code follows project style (Black formatting)
- [ ] All tests pass (`./run_tests.sh all`)
- [ ] New features have tests (aim for >80% coverage)
- [ ] Documentation is updated
- [ ] Type hints are added for new functions
- [ ] No debug print statements or commented code
- [ ] Commit messages are clear and descriptive

## Testing Requirements

### Test Structure

- **Unit Tests**: Test individual functions/methods in isolation
- **Integration Tests**: Test interaction with real CPAP data files
- **Coverage**: Aim for at least 80% code coverage

### Running Tests

```bash
# Run all tests
./run_tests.sh all

# Run only unit tests (fast)
./run_tests.sh unit

# Run with coverage report
./run_tests.sh coverage

# Run specific test file
./run_tests.sh tests/test_server.py
```

### Writing Tests

Example test structure:

```python
import pytest
from cpap_mcp.server import function_to_test

# Mark as unit test
pytestmark = pytest.mark.unit

def test_function_behavior():
    """Test that function works as expected."""
    result = function_to_test(input_data)
    assert result == expected_output

@pytest.mark.asyncio
async def test_async_function():
    """Test async function."""
    result = await async_function()
    assert result is not None
```

## Pull Request Process

### Before Submitting

1. **Update Documentation**: If you've added features
2. **Add Tests**: For all new functionality
3. **Update CHANGELOG**: Add entry for your changes
4. **Rebase if Needed**: Keep your branch up to date
   ```bash
   git fetch upstream
   git rebase upstream/main
   ```

### PR Description Template

```markdown
## Description
Brief description of changes

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Refactoring

## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests added/updated
- [ ] All tests passing
- [ ] Manual testing completed

## Checklist
- [ ] Code follows style guidelines
- [ ] Self-reviewed code
- [ ] Commented complex code
- [ ] Updated documentation
- [ ] No breaking changes (or documented)
```

### Review Process

1. **Automated Checks**: CI/CD must pass
2. **Code Review**: At least one maintainer approval
3. **Discussion**: Address review comments
4. **Merge**: Maintainer will merge when approved

## Style Guide

### Python Code Style

- Follow PEP 8 (enforced by Black and Ruff)
- Line length: 100 characters
- Use type hints for function signatures
- Docstrings for all public functions (Google style)

Example:

```python
def analyze_session(
    session_data: Dict[str, Any],
    threshold: float = 5.0
) -> Dict[str, float]:
    """
    Analyze a CPAP session and calculate key metrics.
    
    Args:
        session_data: Dictionary containing session information
        threshold: AHI threshold for classification
        
    Returns:
        Dictionary with calculated metrics
        
    Raises:
        ValueError: If session_data is invalid
    """
    # Implementation
    pass
```

### Commit Messages

Format: `<type>: <subject>`

Types:
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `test`: Adding or updating tests
- `refactor`: Code refactoring
- `perf`: Performance improvements
- `chore`: Maintenance tasks

Examples:
```
feat: add support for Philips DreamStation data
fix: correct AHI calculation for split sessions
docs: update installation guide with macOS instructions
test: add unit tests for event parsing
```

## Documentation

### What to Document

- New features and tools
- Configuration options
- API changes
- Breaking changes
- Migration guides

### Documentation Style

- Use clear, concise language
- Include code examples
- Provide use cases
- Link to related documentation

### README Updates

Update the main README.md for:
- New major features
- Changed requirements
- New configuration options

## Community

### Getting Help

- **GitHub Issues**: Report bugs and request features
- **Discussions**: Ask questions and share ideas
- **Email**: info@dynacylabs.com for sensitive issues

### Recognition

Contributors are recognized in:
- README.md contributors section
- Release notes
- Project documentation

Thank you for contributing to CPAP MCP Server! Your efforts help improve CPAP therapy analysis for everyone.
