# CuCu Note - Privacy-First Note-Taking Application

A modern, privacy-first note-taking application with AI-powered features, built with FastAPI (backend) and React (frontend).

## 🚀 Features

### Core Features
- **📝 Memo Management**: Create, edit, delete, and organize memos with rich markdown support
- **🔍 Semantic Search**: AI-powered semantic search using embeddings for finding related memos
- **🏷️ Tag System**: Organize memos with tags and tag-based filtering
- **🔗 Memo Relations**: Link related memos and visualize relationships with force graph
- **📎 Attachments**: Upload and manage file attachments
- **🌐 Multi-language Support**: Support for 30+ languages
- **🌓 Theme Support**: Light, dark, and system theme modes
- **📱 Responsive Design**: Works seamlessly on desktop and mobile devices

### AI Features
- **🤖 AI Chatbot**: Intelligent chatbot for note assistance
- **🧠 Embeddings**: Automatic memo embeddings for semantic search
- **🔑 User API Keys**: Users can input their own OpenAI API keys for personalized embeddings
- **💬 Conversation History**: Persistent chat history with pagination

### Security & Privacy
- **🔐 Clerk Authentication**: Secure authentication with Clerk
- **🔒 Encrypted API Keys**: User API keys are encrypted before storage
- **🛡️ Access Control**: User-specific memo visibility (Private, Protected, Public)
- **🔑 Encryption**: Fernet encryption for sensitive data

### Performance Optimizations
- **⚡ MongoDB Connection Pooling**: Optimized database connections
- **💾 Redis Caching**: Response and embedding caching
- **🚦 Rate Limiting**: Configurable rate limiting with Redis backend
- **📊 Database Indexes**: Automatic index creation for common queries
- **🔄 Query Optimization**: Optimized React Query staleTime and refetch behavior

### Extension
- **🌐 Chrome Extension**: Browser extension for quick note-taking

## 📋 Tech Stack

### Backend
- **FastAPI**: Modern Python web framework
- **MongoDB**: NoSQL database with Motor async driver
- **Redis**: Caching and rate limiting
- **OpenAI**: Embeddings and AI features
- **Clerk**: Authentication service
- **LangChain**: LLM orchestration
- **LangGraph**: Agent workflows

### Frontend
- **React 18**: UI framework
- **TypeScript**: Type safety
- **Vite**: Build tool
- **TanStack Query**: Data fetching and caching
- **Tailwind CSS**: Styling
- **Radix UI**: Accessible component primitives
- **React Router**: Routing
- **i18next**: Internationalization

## 🛠️ Installation

### Prerequisites
- Python 3.11+
- Node.js 18+
- MongoDB 6+
- Redis 6+ (optional but recommended)
- Docker & Docker Compose (for containerized deployment)

### Quick Start with Docker

1. **Clone the repository**
```bash
git clone https://github.com/Hoanganhvu123/cuccu_note.git
cd cuccu_note
```

2. **Set up environment variables**

Create `.env` files:

**Backend `.env`** (in `backend/` directory):
```bash
# MongoDB
MONGODB_URI=mongodb://mongodb:27017
MONGODB_DB_NAME=cucu_note

# Authentication
CLERK_SECRET_KEY=sk_test_your_clerk_secret_key
CLERK_JWKS_URL=https://your-clerk-instance.clerk.accounts.dev/.well-known/jwks.json
CLERK_ISSUER=https://your-clerk-instance.clerk.accounts.dev

# OpenAI
OPENAI_API_KEY=sk-your-openai-api-key

# Encryption (generate with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())")
ENCRYPTION_KEY=your-32-byte-base64-encoded-key

# Server
PORT=5000

# Redis (optional)
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_CACHE_URL=redis
RATE_STORAGE_URI=redis://redis:6379/0

# CORS
CORS_ORIGINS=http://localhost:3001,https://yourdomain.com
```

**Frontend `.env`** (in `frontend/` directory):
```bash
VITE_API_BASE_URL=http://localhost:5000
VITE_PORT=3001
```

3. **Run with Docker Compose**
```bash
docker-compose up -d
```

This will start:
- Backend API on `http://localhost:5000`
- Frontend on `http://localhost:3001`
- MongoDB on `mongodb://localhost:27017`
- Redis on `redis://localhost:6379`

### Manual Installation

#### Backend Setup

1. **Navigate to backend directory**
```bash
cd backend
```

2. **Create virtual environment**
```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

3. **Install dependencies**
```bash
pip install -r requirements.txt
```

4. **Set up environment variables**
```bash
cp ENV_VARIABLES.md .env
# Edit .env with your values
```

5. **Run the server**
```bash
# Development
python run.py

# Production with Gunicorn
gunicorn --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:5000 --timeout 120 server:app
```

#### Frontend Setup

1. **Navigate to frontend directory**
```bash
cd frontend
```

2. **Install dependencies**
```bash
npm install
# or
pnpm install
```

3. **Set up environment variables**
```bash
# Create .env file
echo "VITE_API_BASE_URL=http://localhost:5000" > .env
```

4. **Run development server**
```bash
npm run dev
# or
pnpm dev
```

5. **Build for production**
```bash
npm run build
# or
pnpm build
```

## 🔑 Environment Variables

### Backend Environment Variables

#### Required Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `MONGODB_URI` | MongoDB connection string | `mongodb://localhost:27017` |
| `MONGODB_DB_NAME` | Database name | `cucu_note` |
| `CLERK_SECRET_KEY` | Clerk secret key | `sk_test_...` |
| `CLERK_JWKS_URL` | Clerk JWKS URL | `https://...clerk.accounts.dev/.well-known/jwks.json` |
| `CLERK_ISSUER` | Clerk issuer URL | `https://...clerk.accounts.dev` |
| `OPENAI_API_KEY` | OpenAI API key | `sk-...` |
| `ENCRYPTION_KEY` | Fernet encryption key (32-byte base64) | Generate with: `python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"` |

#### Optional Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | Server port | `5000` |
| `MONGODB_MAX_POOL_SIZE` | MongoDB max pool size | `50` |
| `MONGODB_MIN_POOL_SIZE` | MongoDB min pool size | `10` |
| `MONGODB_MAX_IDLE_TIME_MS` | MongoDB max idle time (ms) | `45000` |
| `REDIS_HOST` | Redis host | `localhost` |
| `REDIS_PORT` | Redis port | `6379` |
| `REDIS_CACHE_URL` | Redis cache host | `localhost` |
| `REDIS_CACHE_DB` | Redis cache database | `2` |
| `CORS_ORIGINS` | CORS allowed origins (comma-separated) | `*` |
| `RATE_LIMIT_GUEST` | Daily message limit for guests | `10` |
| `RATE_LIMIT_USER` | Daily message limit for users | `100` |
| `RATE_STORAGE_URI` | Rate limit storage URI | `memory://` |
| `DISABLE_AUTH` | Disable authentication (dev only) | `false` |
| `GOOGLE_API_KEY` | Google API key (optional) | - |
| `GROQ_API_KEY` | Groq API key (optional) | - |
| `DEFAULT_MODEL` | Default AI model | `gpt-4o-mini` |
| `LANGFUSE_PUBLIC_KEY` | Langfuse public key (optional) | - |
| `LANGFUSE_SECRET_KEY` | Langfuse secret key (optional) | - |

For complete documentation, see [backend/ENV_VARIABLES.md](./backend/ENV_VARIABLES.md)

### Frontend Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `VITE_API_BASE_URL` | Backend API base URL | `http://localhost:5000` |
| `VITE_PORT` | Development server port | `3001` |
| `VITE_DEV_PROXY_SERVER` | Proxy server for Vite dev | Same as `VITE_API_BASE_URL` |

For complete documentation, see [frontend/ENV_VARIABLES.md](./frontend/ENV_VARIABLES.md)

## 🐳 Docker Deployment

### Docker Compose

A complete `docker-compose.yml` is provided for easy deployment:

```bash
docker-compose up -d
```

### Individual Dockerfiles

#### Backend Dockerfile

**Development** (`backend/Dockerfile.dev`):
```bash
docker build -f backend/Dockerfile.dev -t cuccu-backend-dev ./backend
docker run -p 5000:5000 --env-file backend/.env cuccu-backend-dev
```

**Production** (`backend/Dockerfile.prod`):
```bash
docker build -f backend/Dockerfile.prod -t cuccu-backend-prod ./backend
docker run -p 5000:5000 --env-file backend/.env cuccu-backend-prod
```

#### Frontend Dockerfile

**Development**:
```bash
docker build -f frontend/Dockerfile.dev -t cuccu-frontend-dev ./frontend
docker run -p 3001:3001 --env-file frontend/.env cuccu-frontend-dev
```

**Production**:
```bash
docker build -f frontend/Dockerfile.prod -t cuccu-frontend-prod ./frontend
docker run -p 80:80 cuccu-frontend-prod
```

## 📚 API Documentation

Once the backend is running, API documentation is available at:
- Swagger UI: `http://localhost:5000/docs`
- ReDoc: `http://localhost:5000/redoc`

### Main API Endpoints

#### Memos
- `GET /api/v1/memos` - List memos
- `POST /api/v1/memos` - Create memo
- `GET /api/v1/memos/{memo_id}` - Get memo
- `PATCH /api/v1/memos/{memo_id}` - Update memo
- `DELETE /api/v1/memos/{memo_id}` - Delete memo

#### Users
- `GET /api/v1/users` - List users
- `GET /api/v1/users/{user_id}` - Get user
- `GET /api/v1/users/{user_id}/openai-key` - Get user's OpenAI key (masked)
- `PUT /api/v1/users/{user_id}/openai-key` - Update user's OpenAI key
- `DELETE /api/v1/users/{user_id}/openai-key` - Delete user's OpenAI key

#### Chatbot
- `POST /chat` - Chat with AI assistant
- `GET /history/{user_id}` - Get chat history

For complete API documentation, see [backend/readme.md](./backend/readme.md)

## 🏗️ Project Structure

```
cuccu_note/
├── backend/                 # FastAPI backend
│   ├── api/                # API routes
│   │   ├── memos/          # Memo endpoints
│   │   └── chatbot/        # Chatbot endpoints
│   ├── common/              # Shared utilities
│   │   ├── memos_core/     # Memo core logic
│   │   ├── embedding_service.py
│   │   ├── encryption.py   # Encryption utilities
│   │   └── ...
│   ├── agent/              # AI agent logic
│   ├── config.py           # Configuration
│   ├── server.py           # FastAPI app
│   ├── requirements.txt    # Python dependencies
│   ├── Dockerfile.prod     # Production Dockerfile
│   └── docker-compose.yml  # Docker Compose config
├── frontend/               # React frontend
│   ├── src/
│   │   ├── components/     # React components
│   │   ├── pages/          # Page components
│   │   ├── hooks/          # React hooks
│   │   ├── service/        # API client
│   │   └── ...
│   ├── package.json        # Node dependencies
│   └── vite.config.mts     # Vite config
├── extension/              # Chrome extension
│   └── src/                # Extension source
└── docker-compose.yml      # Root Docker Compose
```

## 🔒 Security Best Practices

1. **Never commit `.env` files** - Add to `.gitignore`
2. **Use strong encryption keys** - Generate `ENCRYPTION_KEY` properly
3. **Restrict CORS origins** - Don't use `*` in production
4. **Enable authentication** - Set `DISABLE_AUTH=false` in production
5. **Use Redis for rate limiting** - Don't use `memory://` in production
6. **Rotate API keys regularly** - Especially for production
7. **Use HTTPS** - Always use HTTPS in production
8. **Monitor logs** - Set up logging and monitoring

## 🚀 Production Deployment

### Checklist

Before deploying to production:

- [ ] Set `MONGODB_URI` with production MongoDB
- [ ] Configure Clerk authentication
- [ ] Set `ENCRYPTION_KEY` (generate new key)
- [ ] Set `CORS_ORIGINS` to specific domains (not `*`)
- [ ] Configure Redis for caching and rate limiting
- [ ] Set `RATE_STORAGE_URI` to Redis (not `memory://`)
- [ ] Set `DISABLE_AUTH=false`
- [ ] Set all required API keys
- [ ] Use HTTPS/SSL certificates
- [ ] Set up monitoring and logging
- [ ] Configure backup for MongoDB
- [ ] Set up CI/CD pipeline
- [ ] Test all features thoroughly

### Recommended Production Setup

1. **Use reverse proxy** (Nginx/Traefik) for SSL termination
2. **Use managed MongoDB** (MongoDB Atlas) for database
3. **Use managed Redis** (Redis Cloud/ElastiCache) for caching
4. **Use container orchestration** (Kubernetes/Docker Swarm)
5. **Set up monitoring** (Prometheus/Grafana)
6. **Configure logging** (ELK stack or similar)

## 🧪 Testing

### Backend Tests
```bash
cd backend
pytest
```

### Frontend Tests
```bash
cd frontend
npm run test:e2e
```

## 📖 Documentation

- [Backend README](./backend/readme.md) - Backend API documentation
- [Backend ENV Variables](./backend/ENV_VARIABLES.md) - Environment variables
- [Frontend ENV Variables](./frontend/ENV_VARIABLES.md) - Frontend environment variables
- [Extension README](./extension/README.md) - Chrome extension setup

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📝 License

This project is licensed under the MIT License.

## 🙏 Acknowledgments

- Built with [FastAPI](https://fastapi.tiangolo.com/)
- Frontend powered by [React](https://react.dev/)
- UI components from [Radix UI](https://www.radix-ui.com/)
- Icons from [Lucide](https://lucide.dev/)

## 📞 Support

For issues and questions:
- GitHub Repository: [https://github.com/Hoanganhvu123/cuccu_note](https://github.com/Hoanganhvu123/cuccu_note)
- GitHub Issues: [https://github.com/Hoanganhvu123/cuccu_note/issues](https://github.com/Hoanganhvu123/cuccu_note/issues)

## 📦 Deployment

For detailed deployment instructions, see [DEPLOYMENT.md](./DEPLOYMENT.md)

### Quick Deploy

```bash
# Clone repository
git clone https://github.com/Hoanganhvu123/cuccu_note.git
cd cuccu_note

# Set up environment variables (see Environment Variables section above)
# Then deploy with Docker Compose
docker-compose up -d
```

---

**Made with ❤️ by the CuCu Note team**

