# EPOLaw AI Assistant - Feature Documentation

## Overview
The EPOLaw AI Assistant is a conversational interface that helps users interact with their cases and documents using natural language. It features intelligent intent parsing powered by GPT-4o and provides instant access to case information, document analysis, and image analysis.

## How to Access
- **Click**: Purple robot button in bottom-right corner of any page
- **Keyboard**: Press `Alt+A` to open/close the assistant

## Features

### 1. Case Management
**Commands:**
- `"Summarize case 1"` - Get full case summary with documents, notes, team members
- `"Tell me about case 1234"` - Same as summarize
- `"Show my cases"` or `"What cases do I have?"` - List your accessible cases
- `"Find cases about Smith"` - Search across case names, clients, descriptions

**What You Get:**
- Case details (number, status, client, attorney, practice area)
- Full document list with IDs and analysis status
- Recent notes
- Team member list
- Access respects permissions (confidential cases, team membership)

### 2. Image Analysis (NEW!)
**Commands:**
- `"Analyze IMG_20250713_233516.jpg"` - Analyze by filename
- `"Analyze picture 10 in case 1"` - Analyze by ID
- Just type the filename: `"IMG_123.jpg"`

**How It Works:**
- Searches across ALL your accessible cases to find the file
- Uses GPT-4o Vision API for instant analysis
- Shows existing analysis if already done
- Performs new analysis if requested
- Handles: JPG, JPEG, PNG, GIF, TIF, TIFF, BMP

**Response Includes:**
- Legal analysis from neutral perspective
- What's visible in the image
- Potential legal relevance
- Link to full analysis if available

### 3. Document Summarization (NEW!)
**Commands:**
- `"Summarize contract.pdf"` - Summarize by filename
- `"Summarize document 5 in case 1"` - Summarize by ID

**How It Works:**
- Searches for document by filename across cases
- Shows existing summary if available
- Shows existing analysis if summary not available
- Guides user to create new summary if needed

### 4. Document Analysis
**Commands:**
- `"Analyze document.pdf"`
- `"Analyze document 5 in case 1234"`

**Response:**
- Existing analysis if available (first 1500 chars)
- Analysis metadata (perspective, date, etc.)
- Link to full analysis page

### 5. Search & Discovery
**Commands:**
- `"Find cases about contracts"`
- `"Search for Smith"`

**Search Scope:**
- Case names
- Client names
- Case descriptions
- Case numbers

### 6. Help System
**Commands:**
- `"help"` - Show full command list
- Unknown queries automatically show helpful suggestions

## Technical Architecture

### Backend (`assistant_routes.py`)
- **Intent Parsing**: GPT-4o analyzes user input and extracts:
  - Intent type (summarize_case, analyze_image, etc.)
  - Case ID if mentioned
  - Document ID if mentioned
  - Filename if mentioned
  - Search query if applicable

- **Document Lookup**:
  - Filename-based search (case-insensitive)
  - Scoped to user's accessible cases
  - Respects case permissions
  - Optional case ID filter

- **Image Analysis**:
  - Reuses existing `analyze_image_with_openai()` from app.py
  - GPT-4 Vision API with legal context
  - Neutral perspective for quick analysis

- **Conversation History**:
  - Stored in `assistant_conversations` table
  - Each message tracked in `assistant_messages` table
  - Includes action metadata for analytics

### Database Models
```sql
assistant_conversations:
  - conversation_uuid (unique identifier)
  - user_id, company_id (multi-tenant)
  - title (auto-generated from first message)
  - created_at, updated_at

assistant_messages:
  - conversation_id (FK)
  - message_type (user/assistant)
  - message_text (full content)
  - action_type (what assistant did)
  - entity_type, entity_id (what was acted upon)
  - msg_metadata (JSON for additional data)
```

### Frontend (`base_layout.html`)
- **Floating UI**: Fixed position, responsive design
- **Real-time Chat**: Async fetch to `/assistant/chat`
- **Markdown Support**: Basic formatting (bold, line breaks)
- **Typing Indicators**: Visual feedback during processing
- **Auto-scroll**: New messages scroll into view
- **Mobile Responsive**: Adapts to smaller screens

## API Endpoints

### POST `/assistant/chat`
**Request:**
```json
{
  "message": "user question here",
  "conversation_id": "uuid-or-null"
}
```

**Response:**
```json
{
  "success": true,
  "conversation_id": "conversation-uuid",
  "response": "assistant response text",
  "intent": "analyzed_intent",
  "metadata": {
    "action_type": "action_taken",
    "entity_type": "entity_type",
    "entity_id": "entity_id"
  }
}
```

### GET `/assistant/history?conversation_id=uuid`
Returns message history for a conversation

### GET `/assistant/history`
Returns list of user's recent conversations

### POST `/assistant/new`
Starts a new conversation

## Future Enhancements (Easy to Add)

### Print Functionality
- `"Print case 1 summary"` - Generate printable PDF
- Format: Cover page, case details, document list, notes
- Implementation: Use existing PDF libraries

### Email Reports
- `"Email me case 1 summary"` - Send formatted email
- Use existing email service from app.py
- Attach PDF or inline HTML

### Bulk Operations
- `"Summarize all documents in case 1"`
- `"Analyze all images in case 5"`
- Queue processing jobs automatically

### Smart Suggestions
- Context-aware follow-up questions
- "Would you like me to also..."
- Based on current conversation state

### Voice Input
- Browser speech recognition API
- `"Hey EPOLaw, summarize case 1"`

### Export Options
- `"Export case 1 to PDF/DOCX"`
- Include all documents, analyses, notes
- Professional legal memorandum format

### Calendar Integration
- `"What deadlines do I have this week?"`
- `"Schedule a reminder for case 1"`

### Document Comparison
- `"Compare document A and document B"`
- Highlight differences
- Show changes if versions exist

## Usage Analytics

Track via `assistant_messages` table:
- Most common intents
- Average response time
- Success vs error rates
- Popular features
- User engagement patterns

## Security & Privacy

- **Session-based auth**: Inherits from Flask session
- **Company isolation**: Users only see their company's data
- **Case permissions**: Respects confidential flags, team membership
- **No data leakage**: Document search scoped to accessible cases
- **Audit trail**: All interactions logged with user_id, company_id

## Performance Considerations

- **Caching**: Consider caching frequent case summaries
- **Rate limiting**: Inherit from app-level rate limits
- **Async processing**: Large operations (bulk analysis) should queue
- **Token usage**: Monitor OpenAI API costs for intent parsing + analysis

## Troubleshooting

**Assistant not responding:**
- Check `/var/log/epolaw/error.log`
- Verify OpenAI API key is set
- Test `/assistant/chat` endpoint directly

**Documents not found:**
- Filename search is case-insensitive but must match
- Check user has access to the case
- Verify document exists in database

**Analysis not working:**
- Ensure file exists at `file_path`
- Check file permissions (www-data readable)
- Verify image file format is supported

## Development Tips

**Adding new intents:**
1. Update `parse_user_intent()` system prompt
2. Add handler in `chat()` route
3. Update help text
4. Test with various phrasings

**Adding new entity extraction:**
1. Add extraction function (like `extract_filename()`)
2. Update intent parser to return new field
3. Use in handler logic

**Custom responses:**
1. Create helper function for complex operations
2. Return formatted markdown string
3. Set appropriate `entity_type` and `entity_id`

## Credits

Built on:
- Flask (web framework)
- OpenAI GPT-4o (intent parsing + vision)
- SQLAlchemy (database ORM)
- Bootstrap 5 (UI components)
