# Contributing to PunimTag

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

---

## 📋 Table of Contents

1. [Code of Conduct](#code-of-conduct)
2. [Getting Started](#getting-started)
3. [Development Workflow](#development-workflow)
4. [Coding Standards](#coding-standards)
5. [Testing](#testing)
6. [Documentation](#documentation)
7. [Pull Request Process](#pull-request-process)
8. [Project Structure](#project-structure)

---

## 🤝 Code of Conduct

### Our Pledge
We are committed to providing a welcoming and inclusive environment for all contributors.

### Expected Behavior
- Be respectful and considerate
- Welcome newcomers and help them learn
- Accept constructive criticism gracefully
- Focus on what's best for the project
- Show empathy towards other contributors

### Unacceptable Behavior
- Harassment or discriminatory language
- Trolling or insulting comments
- Public or private harassment
- Publishing others' private information
- Other unprofessional conduct

---

## 🚀 Getting Started

### Prerequisites
- Python 3.12+
- Git
- Basic understanding of Python and Tkinter
- Familiarity with face recognition concepts (helpful)

### Setting Up Development Environment

1. **Fork and Clone**
```bash
git fork <repository-url>
git clone <your-fork-url>
cd punimtag
```

2. **Create Virtual Environment**
```bash
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
```

3. **Install Dependencies**
```bash
pip install -r requirements.txt
pip install -r requirements-dev.txt  # If available
```

4. **Verify Installation**
```bash
python src/gui/dashboard_gui.py
```

---

## 🔄 Development Workflow

### Branch Strategy

```
main/master     - Stable releases
develop         - Integration branch
feature/*       - New features
bugfix/*        - Bug fixes
hotfix/*        - Urgent fixes
release/*       - Release preparation
```

### Creating a Feature Branch

```bash
git checkout develop
git pull origin develop
git checkout -b feature/your-feature-name
```

### Making Changes

1. Make your changes in the appropriate directory:
   - Business logic: `src/core/`
   - GUI components: `src/gui/`
   - Utilities: `src/utils/`
   - Tests: `tests/`

2. Follow coding standards (see below)

3. Add/update tests

4. Update documentation

5. Test your changes thoroughly

### Committing Changes

Use clear, descriptive commit messages:

```bash
git add .
git commit -m "feat: add face clustering algorithm"
```

**Commit Message Format:**
```
<type>: <subject>

<body>

<footer>
```

**Types:**
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `style`: Code style changes (formatting)
- `refactor`: Code refactoring
- `test`: Adding or updating tests
- `chore`: Maintenance tasks

**Examples:**
```
feat: add DeepFace integration

- Replace face_recognition with DeepFace
- Implement ArcFace model
- Add cosine similarity matching
- Update database schema

Closes #123
```

---

## 📏 Coding Standards

### Python Style Guide

Follow **PEP 8** with these specifics:

#### Formatting
- **Indentation**: 4 spaces (no tabs)
- **Line Length**: 100 characters max (120 for comments)
- **Imports**: Grouped and sorted
  ```python
  # Standard library
  import os
  import sys
  
  # Third-party
  import numpy as np
  from PIL import Image
  
  # Local
  from src.core.database import DatabaseManager
  ```

#### Naming Conventions
- **Classes**: `PascalCase` (e.g., `FaceProcessor`)
- **Functions/Methods**: `snake_case` (e.g., `process_faces`)
- **Constants**: `UPPER_SNAKE_CASE` (e.g., `DEFAULT_TOLERANCE`)
- **Private**: Prefix with `_` (e.g., `_internal_method`)

#### Documentation
All public classes and functions must have docstrings:

```python
def process_faces(self, limit: int = 50) -> int:
    """Process unprocessed photos for faces.
    
    Args:
        limit: Maximum number of photos to process
        
    Returns:
        Number of photos successfully processed
        
    Raises:
        DatabaseError: If database connection fails
    """
    pass
```

#### Type Hints
Use type hints for all function signatures:

```python
from typing import List, Dict, Optional

def get_similar_faces(
    self, 
    face_id: int, 
    tolerance: float = 0.6
) -> List[Dict[str, Any]]:
    pass
```

### Code Organization

#### File Structure
```python
#!/usr/bin/env python3
"""
Module description
"""

# Imports
import os
from typing import List

# Constants
DEFAULT_VALUE = 42

# Classes
class MyClass:
    """Class description"""
    pass

# Functions
def my_function():
    """Function description"""
    pass

# Main execution
if __name__ == "__main__":
    main()
```

#### Error Handling
Always use specific exception types:

```python
try:
    result = risky_operation()
except FileNotFoundError as e:
    logger.error(f"File not found: {e}")
    raise
except ValueError as e:
    logger.warning(f"Invalid value: {e}")
    return default_value
```

---

## 🧪 Testing

### Writing Tests

Create tests in `tests/` directory:

```python
import pytest
from src.core.face_processing import FaceProcessor

def test_face_detection():
    """Test face detection on sample image"""
    processor = FaceProcessor(db_manager, verbose=0)
    result = processor.process_faces(limit=1)
    assert result > 0

def test_similarity_calculation():
    """Test face similarity metric"""
    processor = FaceProcessor(db_manager, verbose=0)
    similarity = processor._calculate_cosine_similarity(enc1, enc2)
    assert 0.0 <= similarity <= 1.0
```

### Running Tests

```bash
# All tests
python -m pytest tests/

# Specific test file
python tests/test_face_recognition.py

# With coverage
pytest --cov=src tests/

# Verbose output
pytest -v tests/
```

### Test Guidelines

1. **Test Coverage**: Aim for >80% code coverage
2. **Test Names**: Descriptive names starting with `test_`
3. **Assertions**: Use clear assertion messages
4. **Fixtures**: Use pytest fixtures for setup/teardown
5. **Isolation**: Tests should not depend on each other

---

## 📚 Documentation

### What to Document

1. **Code Changes**: Update docstrings
2. **API Changes**: Update API documentation
3. **New Features**: Add to README and docs
4. **Breaking Changes**: Clearly mark in changelog
5. **Architecture**: Update ARCHITECTURE.md if needed

### Documentation Style

- Use Markdown for all documentation
- Include code examples
- Add diagrams where helpful
- Keep language clear and concise
- Update table of contents

### Files to Update

- `README.md`: User-facing documentation
- `docs/ARCHITECTURE.md`: Technical architecture
- `.notes/task_list.md`: Task tracking
- Inline comments: Complex logic explanation

---

## 🔀 Pull Request Process

### Before Submitting

- [ ] Code follows style guidelines
- [ ] All tests pass
- [ ] New tests added for new features
- [ ] Documentation updated
- [ ] No linting errors
- [ ] Commit messages are clear
- [ ] Branch is up to date with develop

### Submitting PR

1. **Push your branch**
```bash
git push origin feature/your-feature-name
```

2. **Create Pull Request**
   - Go to GitHub/GitLab
   - Click "New Pull Request"
   - Select your feature branch
   - Fill out PR template

3. **PR Title Format**
```
[Type] Short description

Examples:
[Feature] Add DeepFace integration
[Bug Fix] Fix face detection on rotated images
[Docs] Update architecture documentation
```

4. **PR Description Template**
```markdown
## Description
Brief description of changes

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

## Related Issues
Closes #123

## Testing
Describe testing performed

## Screenshots (if applicable)
Add screenshots

## Checklist
- [ ] Code follows style guidelines
- [ ] Tests added/updated
- [ ] Documentation updated
- [ ] All tests pass
```

### Review Process

1. **Automated Checks**: Must pass all CI/CD checks
2. **Code Review**: At least one approval required
3. **Discussion**: Address all review comments
4. **Updates**: Make requested changes
5. **Approval**: Merge after approval

### After Merge

1. Delete feature branch
2. Pull latest develop
3. Update local repository

---

## 🏗️ Project Structure

### Key Directories

```
src/
├── core/          # Business logic - most changes here
├── gui/           # GUI components - UI changes here
└── utils/         # Utilities - helper functions

tests/             # All tests go here

docs/              # User documentation
.notes/            # Developer notes
```

### Module Dependencies

```
gui → core → database
gui → utils
core → utils
```

**Rules:**
- Core modules should not import GUI modules
- Utils should not import core or GUI
- Avoid circular dependencies

---

## 💡 Tips for Contributors

### Finding Issues to Work On

- Look for `good first issue` label
- Check `.notes/task_list.md`
- Ask in discussions

### Getting Help

- Read documentation first
- Check existing issues
- Ask in discussions
- Contact maintainers

### Best Practices

1. **Start Small**: Begin with small changes
2. **One Feature**: One PR = one feature
3. **Test Early**: Write tests as you code
4. **Ask Questions**: Better to ask than assume
5. **Be Patient**: Reviews take time

---

## 🎯 Areas Needing Contribution

### High Priority
- DeepFace integration
- Test coverage improvement
- Performance optimization
- Documentation updates

### Medium Priority
- GUI improvements
- Additional search filters
- Export functionality
- Backup/restore features

### Low Priority
- Code refactoring
- Style improvements
- Additional themes
- Internationalization

---

## 📞 Contact

- **Issues**: GitHub Issues
- **Discussions**: GitHub Discussions
- **Email**: [Add email]

---

## 🙏 Recognition

Contributors will be:
- Listed in AUTHORS file
- Mentioned in release notes
- Thanked in documentation

---

## 📄 License

By contributing, you agree that your contributions will be licensed under the same license as the project.

---

**Thank you for contributing to PunimTag! 🎉**

Every contribution, no matter how small, makes a difference!

