# WatchLLM Project Policy & Rule Book

## Project Overview
WatchLLM is a Next.js/TypeScript-based Brand Intelligence and Discovery Platform. This project follows strict UI/UX guidelines with a centralized component-based design system.

## 🚨 CRITICAL UI/UX RULES
1. **ALWAYS use components from `/components/ui/`** - NO EXCEPTIONS
2. **NEVER use inline styles** or create custom CSS
3. **ONLY use Tailwind utilities** for styling
4. **FOLLOW the UI/UX Foundation document** (`/Docs/UI_UX_FOUNDATION.md`)
5. **Use cn() utility** for all conditional classes
6. **CRUD modules MUST use data tables** - NO CARD GRIDS for listings
7. **Keep UI COMPACT** - Inline stats, minimal padding, no hero sections
8. **Filters must be INLINE** - No large filter cards or sections
9. **Table Sorting is MANDATORY** - All data columns must be sortable with ArrowUpDown icon
10. **Pagination REQUIREMENTS**:
    - Default: 50 rows per page
    - Options: 10, 25, 50, 100, 250
    - Show range: "Showing X-Y of Z"
11. **Column Visibility Control** - Icon-only button (no text) positioned with filters above table
12. **Consistent Heights** - ALL buttons/inputs in headers/filters MUST be `h-8` (32px)
13. **Layout Structure**:
    - Header: Title + stats (left), Add button (right)
    - Filters: Search + dropdowns (left), Column selector icon (right)
14. **Inline Stats Pattern** - ALWAYS show 4 stats: Total, Active, Related Metric, This Month
    - Color coding: Active (green-600), This Month (blue-600)
    - Use `<strong>` tags for numbers

## 🔐 Route Protection & Authentication (Next.js 16)

### CRITICAL: Use `proxy.ts` NOT `middleware.ts`
- **NEVER create `middleware.ts`** - It breaks the app in Next.js 16
- **ALWAYS use `proxy.ts`** in the project root for route protection
- Uses NextAuth's `auth()` wrapper for session checking

### Route Protection Structure
```typescript
// proxy.ts - Located at project root
import { NextResponse } from "next/server";
import { auth } from "@/config/auth";

const publicRoutes = ["/", "/login", "/signup", "/forgot-password", "/contact", "/terms"];
const authRoutes = ["/login", "/signup", "/forgot-password"];

export default auth((req) => {
  // Route protection logic here
});
```

### Protected Routes (Require Login)
- `/admin/*` - Admin dashboard and all sub-routes
- `/dashboard/*` - User dashboard and all sub-routes
- `/practice-manager/*` - Practice manager routes
- `/practitioner/*` - Practitioner routes

### Public Routes (No Login Required)
- `/` - Home page
- `/login` - Login page
- `/signup` - Registration page
- `/forgot-password` - Password recovery
- `/contact` - Contact page
- `/terms` - Terms and conditions

### Auth Behavior
- Unauthenticated users accessing protected routes → Redirect to `/login`
- Authenticated users accessing `/login` or `/signup` → Redirect to `/dashboard`

## Core Development Principles

### 1. Task Management
- **Task Division**: Break all work into small, manageable tasks (max 2-4 hours each)
- **Task Numbering**: Use sequential numbering (task-001, task-002, etc.)
- **Subtask Definition**: Each task must have clearly defined subtasks
- **Documentation**: Store all task documentation in `/docs/tasks/` folder
- **Task Tracking**: Use TodoWrite tool to track progress on all tasks

### 2. Development Workflow (Mandatory for Each Task)

#### Phase 1: Analysis & Planning
- **Requirements Analysis**: Thoroughly analyze task requirements
- **Implementation Plan**: Create detailed implementation strategy
- **Impact Assessment**: Document which files/modules will be affected
- **Dependencies**: Identify all dependencies and integrations

#### Phase 2: Implementation
- **Modular Code**: Write clean, modular, reusable code
- **Code Standards**: Follow Python PEP 8 and project conventions
- **Type Hints**: Include type hints for all functions and methods
- **Error Handling**: Implement comprehensive error handling
- **Logging**: Add appropriate logging for debugging

#### Phase 3: Testing & Validation
- **Unit Tests**: Write unit tests for all new functions
- **Integration Tests**: Create tests for API endpoints and integrations
- **Use Case Scripts**: Develop practical usage examples
- **Test Coverage**: Maintain minimum 80% code coverage
- **Bug Fixes**: Run all tests and fix issues before proceeding

#### Phase 4: Documentation & Commit
- **Code Documentation**: Add docstrings to all functions/classes
- **Task Documentation**: Update task document with results
- **Git Commit**: Create detailed commit with task reference
- **Status Report**: Provide completion status and testing steps

### 3. Code Quality Standards

#### TypeScript/React Standards (PRIMARY)
- Use TypeScript strict mode
- Define interfaces for all component props
- Use meaningful component and variable names
- Implement proper error boundaries
- Add JSDoc comments for complex functions
- Follow React best practices and hooks rules

#### Python Standards (If applicable)
- Follow PEP 8 style guide
- Maximum line length: 100 characters
- Use meaningful variable and function names
- Implement proper exception handling
- Add type hints for all function parameters and returns

#### Code Organization
- Keep functions small and focused (max 50 lines)
- One class per file for major components
- Group related functionality in modules
- Maintain clear separation of concerns
- Use dependency injection where appropriate

#### UI/UX Standards (CRITICAL - MUST FOLLOW)
- **ALWAYS use centralized UI components** from `/components/ui/`
- **NEVER use inline styles** (e.g., `style={{ padding: '20px' }}`)
- **NEVER create custom CSS** or style sheets
- **ONLY use Tailwind utilities** for styling
- **ALWAYS use cn() utility** for conditional classes
- **ONLY use Lucide React** for icons
- **FOLLOW the UI/UX Foundation document** at `/Docs/UI_UX_FOUNDATION.md`
- **CRUD pages MUST use data tables** not card grids
- **Keep stats INLINE and COMPACT** not in large cards
- **Filters must be INLINE** not in separate sections
- **NO HERO sections** in CRUD pages
- **Maximize data density** while maintaining readability

#### React/TypeScript Standards
- Use functional components with hooks
- Implement proper TypeScript types for all props
- Use `'use client'` directive for client components
- Handle loading and error states properly
- Implement proper form validation
- Use semantic HTML elements

#### Performance Guidelines
- Optimize for readability first, performance second
- Profile code for performance bottlenecks
- Use appropriate data structures
- Implement caching where beneficial
- Avoid premature optimization

### 4. Testing Requirements

#### Test Categories
- **Unit Tests**: Test individual functions/methods
- **Integration Tests**: Test component interactions
- **End-to-End Tests**: Test complete workflows
- **Performance Tests**: Test response times and resource usage

#### Test Standards
- Test file naming: `test_<module_name>.py`
- Use pytest framework for all tests
- Mock external dependencies
- Test both success and failure cases
- Include edge cases and boundary conditions

### 5. Documentation Standards

#### Code Documentation
- Docstrings for all modules, classes, and functions
- Include parameter descriptions and return values
- Add usage examples for complex functions
- Document any assumptions or limitations

#### Task Documentation Template
```markdown
# Task-XXX: [Task Title]

## Overview
[Brief description of the task]

## Objectives
- [ ] Objective 1
- [ ] Objective 2

## Subtasks
1. [ ] Subtask 1
2. [ ] Subtask 2

## Implementation Details
[Technical approach and decisions]

## Testing
- Unit tests: [List of test files]
- Integration tests: [List of test scenarios]
- Manual testing steps: [Step-by-step guide]

## Results
[Summary of what was accomplished]

## Known Issues
[Any limitations or future improvements]
```

### 6. Git Workflow

#### Branch Strategy
- Main branch: `main` (production-ready code)
- Feature branches: `feature/task-XXX-description`
- Bugfix branches: `bugfix/task-XXX-description`
- Never commit directly to main

#### Commit Guidelines
- Commit message format: `[Task-XXX] Brief description`
- Include detailed description in commit body
- Reference related issues or tasks
- Ensure all tests pass before committing
- Squash commits before merging to main

#### Pre-commit Checklist
- [ ] All tests passing
- [ ] Code follows style guidelines
- [ ] Documentation updated
- [ ] No sensitive data in code
- [ ] Performance impact assessed

#### UI/UX Checklist (MANDATORY)
- [ ] All components imported from `/components/ui/`
- [ ] No inline styles used anywhere
- [ ] Only Tailwind utilities for styling
- [ ] cn() utility used for conditional classes
- [ ] Lucide React icons only (no other icon libraries)
- [ ] CRUD pages use data tables (NOT card grids)
- [ ] Stats are inline and compact (NOT large cards)
- [ ] Filters are inline (NOT in separate cards)
- [ ] UI is compact with minimal vertical space
- [ ] Loading states implemented
- [ ] Error states handled
- [ ] Empty states designed
- [ ] Responsive on all breakpoints
- [ ] Follows patterns in UI/UX Foundation doc

### 7. Project Structure

```
src/
├── components/           # Reusable UI components
│   ├── ui/              # Basic UI components
│   ├── forms/           # Form components
│   └── common/          # Common components
├── pages/               # Page components
├── layouts/             # Layout components
├── hooks/               # Custom React hooks
├── store/               # Redux store and slices
├── services/            # API services
├── lib/                 # Utility libraries
├── types/               # TypeScript type definitions
├── constants/           # Application constants
├── i18n/                # Internationalization
│   └── locales/         # Language files
├── assets/              # Static assets
└── styles/              # Global styles
```

### 8. Security Guidelines

- Never commit sensitive data (API keys, passwords, tokens)
- Use environment variables for configuration
- Implement input validation for all user inputs
- Follow OWASP guidelines for web security
- Regular dependency updates for security patches

### 9. Performance Standards

- API response time: < 200ms for 95% of requests
- Memory usage: Optimize for minimal memory footprint
- Database queries: Use indexes and optimize queries
- Caching: Implement where appropriate
- Monitor and log performance metrics

### 10. Review Process

Before marking any task as complete:
1. Code review checklist completed
2. All tests passing
3. Documentation updated
4. Performance impact assessed
5. Security considerations addressed
6. Manual testing completed

## Quick Reference Commands

```bash
# Run tests
pytest tests/

# Run with coverage
pytest --cov=src tests/

# Format code
black src/ tests/

# Lint code
flake8 src/ tests/

# Type checking
mypy src/
```

## Important Reminders

- Always use TodoWrite tool for task tracking
- Read this policy before starting any new task
- Focus on quality over speed
- Ask for clarification if requirements are unclear
- Document decisions and rationale
- Test early and test often

---
Last Updated: [Current Date]
Version: 1.0