# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

MYP (Manage Your Printers) is a comprehensive 3D printer management system for Mercedes-Benz, designed to run on Debian/Linux systems (especially Raspberry Pi) in HTTPS kiosk mode. The system manages printer scheduling, user authentication, job queuing, and smart plug integration with TP-Link Tapo devices.

## Essential Commands

### Development
```bash
# Install dependencies
pip install -r requirements.txt --break-system-packages
npm install

# Build CSS (TailwindCSS)
npm run build:css
npm run watch:css  # For development with auto-reload

# Run development server (HTTP on port 5000)
python app.py --debug

# Run production server (HTTPS on port 443)
sudo python app.py
```

### Testing & Validation
```bash
# Lint Python code
flake8 .
black . --check
isort . --check

# Run tests
pytest
pytest -v --cov=.  # With coverage

# Test SSL certificates
python -c "from utils.ssl_config import ensure_ssl_certificates; ensure_ssl_certificates('.', True)"

# Test database connection
python -c "from models import init_database; init_database()"
```

### Deployment & Services
```bash
# Full installation (use setup.sh)
sudo ./setup.sh

# Service management
sudo systemctl status myp-https
sudo systemctl restart myp-https
sudo systemctl enable myp-kiosk  # For kiosk mode

# View logs
sudo journalctl -u myp-https -f
tail -f logs/app/app.log
```

### Database Operations
```bash
# Initialize database
python -c "from models import init_database; init_database()"

# Create backup
python -c "from utils.backup_manager import BackupManager; BackupManager().create_backup()"

# Clean up database
python utils/database_cleanup.py
```

## Architecture Overview

### Core Structure
The application follows a Flask blueprint architecture with clear separation of concerns:

- **app.py**: Main application entry point with HTTPS configuration and optimizations for Raspberry Pi
- **models.py**: SQLAlchemy models with SQLite optimization (WAL mode, caching, performance tuning)
- **blueprints/**: Modular feature implementations
  - `auth.py`: Authentication and session management
  - `admin.py` & `admin_api.py`: Administrative interfaces and APIs
  - `printers.py`: Printer management and smart plug integration
  - `jobs.py`: Job queue management
  - `guest.py`: Guest access with OTP system
  - `calendar.py`: Scheduling with conflict management
  - `users.py` & `user.py`: User management and profiles

### Key Design Patterns

1. **Database Sessions**: Uses scoped sessions with proper cleanup
   ```python
   with get_db_session() as session:
       # Database operations
   ```

2. **Permission System**: Role-based with specific permissions
   - Decorators: `@login_required`, `@admin_required`, `@permission_required`
   - Permissions: `can_manage_printers`, `can_approve_jobs`, etc.

3. **Conflict Management**: Smart printer assignment based on:
   - Availability windows
   - Priority levels (urgent, high, normal, low)
   - Job duration compatibility
   - Real-time conflict detection

4. **Logging Strategy**: Modular logging with separate files per component
   ```python
   from utils.logging_config import get_logger
   logger = get_logger("component_name")
   ```

### Frontend Architecture

- **TailwindCSS**: Utility-first CSS with custom optimizations for Raspberry Pi
- **Vanilla JavaScript**: No heavy frameworks, optimized for performance
- **Progressive Enhancement**: Works without JavaScript, enhanced with it
- **Service Workers**: For offline capability and performance

### Security Considerations

- **SSL/TLS**: Self-signed certificates with automatic generation
- **CSRF Protection**: Enabled globally with Flask-WTF
- **Session Security**: Secure cookies, HTTPOnly, SameSite=Lax
- **Rate Limiting**: Built-in for API endpoints
- **Input Validation**: WTForms for all user inputs

### Performance Optimizations

1. **Raspberry Pi Specific**:
   - Reduced animations and glassmorphism effects
   - Minified assets with gzip compression
   - Optimized SQLite settings for SD cards
   - Memory-efficient session handling

2. **Caching Strategy**:
   - Static file caching (1 year)
   - Database query caching
   - Session-based caching for expensive operations

3. **Database Optimizations**:
   - WAL mode for concurrent access
   - Proper indexing on foreign keys
   - Connection pooling with StaticPool
   - Automatic cleanup of old records

### Integration Points

1. **TP-Link Tapo Smart Plugs**: 
   - PyP100 library for device control
   - Status monitoring and scheduling
   - Automatic power management

2. **Email Notifications**:
   - Guest request notifications
   - Job completion alerts
   - System status updates

3. **File Uploads**:
   - Support for STL, OBJ, 3MF, AMF, GCODE
   - Secure file handling with validation
   - Organized storage in uploads/ directory

### Common Development Tasks

When adding new features:

1. **New Blueprint**: Create in `blueprints/`, register in `app.py`
2. **Database Model**: Add to `models.py`, create migration if needed
3. **Frontend Assets**: 
   - CSS in `static/css/components.css`
   - JavaScript in `static/js/` 
   - Run `npm run build:css` after CSS changes
4. **Logging**: Use `get_logger("component_name")` for consistent logging
5. **Permissions**: Add new permissions to `UserPermission` model

### Debugging Tips

- Check logs in `logs/` directory for component-specific issues
- Use `--debug` flag for development server
- Database locked errors: Check for WAL files (`*.db-wal`, `*.db-shm`)
- SSL issues: Regenerate certificates with `utils/ssl_config.py`
- Performance issues: Check `/api/stats` endpoint for metrics