# Cursor AI Rules for PunimTag

## Project Context
This is a modern web-based photo management application with facial recognition capabilities. The project uses a monorepo structure with FastAPI backend, React admin frontend, and Next.js viewer frontend.

## Code Style

### Python (Backend)
- Follow PEP 8 strictly
- Use type hints for all function signatures
- Maximum line length: 100 characters
- Use 4 spaces for indentation (never tabs)
- Add docstrings to all public classes and methods

### TypeScript/JavaScript (Frontend)
- Use TypeScript for all new code
- Follow ESLint rules
- Use functional components with hooks
- Prefer named exports over default exports
- Maximum line length: 100 characters

## Import Organization

### Python
```python
# Standard library imports
import os
import sys

# Third-party imports
import numpy as np
from PIL import Image
from fastapi import APIRouter

# Local imports
from backend.db.session import get_db
from backend.services.face_service import FaceService
```

### TypeScript
```typescript
// Third-party imports
import React from 'react';
import { useQuery } from '@tanstack/react-query';

// Local imports
import { apiClient } from '@/api/client';
import { Layout } from '@/components/Layout';
```

## Naming Conventions
- **Python Classes**: PascalCase (e.g., `FaceProcessor`)
- **Python Functions/methods**: snake_case (e.g., `process_faces`)
- **Python Constants**: UPPER_SNAKE_CASE (e.g., `DEFAULT_TOLERANCE`)
- **Python Private members**: prefix with underscore (e.g., `_internal_method`)
- **TypeScript/React Components**: PascalCase (e.g., `PhotoViewer`)
- **TypeScript Functions**: camelCase (e.g., `processFaces`)
- **TypeScript Constants**: UPPER_SNAKE_CASE or camelCase (e.g., `API_URL` or `defaultTolerance`)

## Project Structure (Monorepo)
```
punimtag/
├── backend/              # FastAPI backend
│   ├── api/             # API routers
│   ├── db/              # Database models and session
│   ├── schemas/         # Pydantic models
│   ├── services/        # Business logic services
│   ├── constants/       # Constants and configuration
│   ├── utils/           # Utility functions
│   ├── app.py          # FastAPI application
│   └── worker.py       # RQ worker for background jobs
├── admin-frontend/      # React admin interface
│   ├── src/
│   │   ├── api/        # API client
│   │   ├── components/ # React components
│   │   ├── context/    # React contexts (Auth)
│   │   ├── hooks/      # Custom hooks
│   │   └── pages/      # Page components
│   └── package.json
├── viewer-frontend/     # Next.js viewer interface
│   ├── app/            # Next.js app router
│   ├── components/     # React components
│   ├── lib/            # Utilities and database
│   └── prisma/         # Prisma schemas
├── src/                 # Legacy utilities (if any)
├── tests/               # Test suite
├── docs/                # Documentation
├── scripts/             # Utility scripts
└── deploy/              # Deployment configurations
```

## Key Technologies

### Backend
- **Python 3.12+**
- **FastAPI** - Web framework
- **PostgreSQL** - Database (required, not SQLite)
- **SQLAlchemy 2.0** - ORM
- **DeepFace** - Face recognition (migrated from face_recognition)
- **Redis + RQ** - Background job processing
- **JWT** - Authentication

### Frontend
- **React 18 + TypeScript** - Admin interface
- **Next.js 16** - Viewer interface
- **Vite** - Build tool for admin
- **Tailwind CSS** - Styling
- **React Query** - Data fetching
- **Prisma** - Database client for viewer

## Import Paths

### Python Backend
Always use absolute imports from backend:
```python
from backend.db.session import get_db
from backend.services.face_service import FaceService
from backend.api.photos import router as photos_router
```

### TypeScript Frontend
Use path aliases configured in tsconfig.json:
```typescript
import { apiClient } from '@/api/client';
import { Layout } from '@/components/Layout';
```

## Database
- **PostgreSQL** is required (not SQLite)
- Use SQLAlchemy ORM for all database operations
- Use context managers for database sessions
- Always use prepared statements (SQLAlchemy handles this)
- Two databases: `punimtag` (main) and `punimtag_auth` (auth)

## Error Handling
- Use specific exception types
- Log errors appropriately
- Provide user-friendly error messages in API responses
- Never silently catch exceptions
- Use FastAPI HTTPException for API errors
- Use try-catch in React components with proper error boundaries

## Testing
- Write tests for all new features
- Use pytest for Python backend tests
- Use Vitest/Jest for frontend tests
- Place tests in `tests/` directory
- Aim for >80% code coverage

## Documentation
- Update docstrings when changing code
- Keep README.md current
- Update docs/ARCHITECTURE.md for architectural changes
- Document complex algorithms inline
- Update API documentation (FastAPI auto-generates from docstrings)

## Git Commit Messages
Format: `<type>: <subject>`

Types:
- feat: New feature
- fix: Bug fix
- docs: Documentation
- style: Formatting
- refactor: Code restructuring
- test: Tests
- chore: Maintenance

## Current Focus
- Web-based architecture (migrated from desktop)
- DeepFace integration (completed)
- PostgreSQL migration (completed)
- Monorepo structure (completed)
- Production deployment preparation

## Avoid
- Circular imports
- Global state (except configuration)
- Hard-coded file paths
- SQL injection vulnerabilities (use SQLAlchemy ORM)
- Mixing business logic with API/UI code
- Storing sensitive data in code (use environment variables)

## Prefer
- Type hints (Python) and TypeScript
- List/dict comprehensions over loops
- Context managers for resources
- f-strings for formatting (Python)
- Template literals for formatting (TypeScript)
- Pathlib over os.path (Python)
- Environment variables for configuration

## When Adding Features
1. **Design**: Plan the feature and update architecture docs
2. **Database**: Update schema if needed (SQLAlchemy models)
3. **Backend**: Implement API endpoints and services
4. **Frontend**: Add UI components and API integration
5. **Tests**: Write test cases for backend and frontend
6. **Docs**: Update documentation

## Performance Considerations
- Cache face encodings in database
- Use database indices
- Batch database operations
- Lazy load large datasets
- Use React Query caching for frontend
- Profile before optimizing
- Use background jobs (RQ) for long-running tasks

## Security
- Validate all user inputs (Pydantic schemas for API)
- Sanitize file paths
- Use SQLAlchemy ORM (prevents SQL injection)
- Don't store sensitive data in plain text
- Use bcrypt for password hashing
- JWT tokens for authentication
- CORS configuration for production
- Environment variables for secrets

## Development Environment

### Dev Server
- **Host**: 10.0.10.121
- **User**: appuser
- **Password**: C0caC0la

### Dev PostgreSQL
- **Host**: 10.0.10.181
- **Port**: 5432
- **User**: ladmin
- **Password**: C0caC0la

## Deployment
- Use deployment scripts in package.json
- Build frontends before deployment
- Set up environment variables on server
- Configure PostgreSQL connection strings
- Set up Redis for background jobs
- Use process managers (systemd, PM2) for production

