# Change Log - AI Study Assistant

## 📝 VERSION HISTORY

---

## [Unreleased]

### Added
- **Teacher Materials Page (Upload Conteúdo)** - Nova tela dedicada para upload de materiais para a IA
  - Novo ficheiro: `lib/features/materials/presentation/pages/teacher_materials_page.dart`
  - Acedida através do card "Upload Conteúdo" no dashboard do professor (usando `Navigator.push`)
  - **Funcionalidades:**
    - Visualização de materiais já enviados via `StreamBuilder` do Firestore
    - Lista com ícones do tipo (PDF = vermelho, Imagem = azul)
    - Formato de data: dd/MM/yyyy HH:mm
    - Estados: loading, empty, error
  - **Upload de ficheiros:**
    - FloatingActionButton "Adicionar" com bottom sheet de opções
    - PDF: seleção via `file_selector` (packages: `file_selector: ^1.0.3`)
    - Imagem da Galeria: via `image_picker` (ImageSource.gallery)
    - Foto da Câmara: via `image_picker` (ImageSource.camera)
  - **Firebase Integration:**
    - Upload para Firebase Storage: `materials/{teacherId}/{timestamp}_{filename}`
    - Documento Firestore na coleção `materials` com campos: `teacherId`, `fileName`, `fileUrl`, `type`, `createdAt`, `storagePath`
    - Query filtrada por `teacherId` e ordenada por `createdAt` descendente
  - **UX:**
    - Snackbars de feedback (sucesso verde, erro vermelho)
    - Loading indicator no FAB durante upload
    - Design consistente com o dashboard (AppBar teal #82C9BD, gradiente)

- **Student Classes List (ETAPA 5)** - Students can now view their enrolled classes on the home page
  - New `StudentClassesListWidget` at `/lib/features/dashboard/presentation/widgets/student_classes_list_widget.dart`
  - Query: `.collection('enrollments').where('studentId', isEqualTo: currentUser.uid).orderBy('joinedAt', descending: true)`
  - For each enrollment, fetches corresponding class document from `classes` collection using `classId`
  - Layout: Same horizontal 2-row scroll pattern as `TeacherClassesListWidget`
  - Cards display: Class name + Class code
  - Loading state: `CircularProgressIndicator` (centered in card while loading class data)
  - Empty state: Text "Ainda não entraste em nenhuma turma."
  - Widget inserted in `StudentDashboardPage` after QuickAccessWidget
  - Visual design: White cards (#FFFFFF), teal icon background (#82C9BD with 10% opacity), rounded corners (16px), subtle shadows
  - Title: "As Minhas Turmas" (same style as teacher dashboard)
  - System now bidirectional: Teachers see students, Students see classes

- **Join Class Feature (ETAPA 4)** - Students can now join classes using class codes
  - New `JoinClassPage` screen at `/lib/features/classes/presentation/pages/join_class_page.dart`
  - TextField for entering 6-character class code (uppercase, centered, letter-spacing)
  - "Entrar na Turma" button with loading state and visual feedback
  - Firestore query: `.collection('classes').where('code', isEqualTo: enteredCode).limit(1)`
  - Validation: checks if code exists, if student already enrolled
  - On success: creates document in `enrollments` collection with `classId`, `studentId`, `studentName`, `joinedAt`
  - Success feedback: green SnackBar "Entraste na turma com sucesso!"
  - Error feedback: red SnackBar for invalid code, duplicate enrollment, or auth errors
  - Auto-returns to student home after successful join
  - Visual design: teal AppBar (#82C9BD), centered icon, clean input field with rounded corners
  - New "Entrar numa Turma" card in Student Dashboard Quick Access section
  - Card design: horizontal layout with `Icons.group_add`, white background, rounded corners

- **Class Students View (ETAPA 3)** - Teachers can now view enrolled students in each class
  - New `ClassStudentsPage` screen at `/lib/features/classes/presentation/pages/class_students_page.dart`
  - StreamBuilder query on `enrollments` collection with filter by `classId`
  - ListTile layout showing student name and join date
  - Loading state with `CircularProgressIndicator`
  - Empty state message when no students enrolled
  - Date formatting using `intl` package (dd/MM/yyyy format)
  - Consistent styling with existing app design (teal colors, rounded cards)
  - Navigation via `MaterialPageRoute` from class card tap

- **Class Creation Feature (ETAPA 1)** - Teachers can now create classes from the dashboard
  - New "Criar Turma" button in Teacher Dashboard Quick Actions
  - Simple dialog interface for entering class name
  - Automatic generation of 6-character unique class codes (A-Z, 0-9)
  - Firestore integration saving class data (name, teacherId, code, timestamp)
  - Visual feedback with loading indicator and success/error messages

- **Classes List Display (ETAPA 2)** - Teachers can now view their created classes
  - New "As Minhas Turmas" section in Teacher Dashboard
  - Real-time StreamBuilder to fetch classes from Firestore
  - **CORREÇÃO**: O erro anterior foi tentar usar `GridView` horizontal para um layout que exige colunas fixas
  - **SOLUÇÃO**: Usar `ListView.builder` com `scrollDirection: Axis.horizontal`
  - Cada item do ListView é uma `Column` contendo 2 cards (índice * 2 e índice * 2 + 1)
  - Cards mantêm exatamente o mesmo tamanho e estilo da lista vertical original
  - Layout: Card 1, 3, 5... (top row) | Card 2, 4, 6... (bottom row)
  - Scroll horizontal para visualizar todas as turmas
  - Visual cards showing class name and access code
  - Empty state message when no classes exist
  - Loading state with CircularProgressIndicator

### Fixed
- **Settings Profile Card UI** - Fixed white background and duplicate email display
  - Background now uses Theme.of(context).colorScheme.surface instead of hardcoded white
  - User info displays displayName (bold, larger) on top, email (smaller) below
  - File: lib/features/settings/presentation/pages/profile_edit_page.dart

- **Signup Page Input Field Theming** - Fixed dark backgrounds in light mode
  - Input fields now use conditional background based on theme brightness
  - Light mode: surface color, Dark mode: surfaceContainerHighest
  - Applied to name, email, and password fields
  - File: lib/features/auth/presentation/pages/signup_page.dart

- **Dashboard Progress Container Theming** - Fixed dark background in light mode
  - "Ótimo progresso!" container now uses conditional background
  - Light mode: surface color, Dark mode: surfaceContainerHighest
  - File: lib/features/dashboard/presentation/widgets/profile_section_widget.dart

- **Authentication Navigation** - Enhanced back button behavior
  - Removed AppBar from login and signup pages
  - Added PopScope for Android back button navigation to role-selection
  - Added custom positioned back button with aesthetic design
  - Positioned at top: 50 to avoid notification bar overlap
  - Files: lib/features/auth/presentation/pages/login_page.dart, signup_page.dart

- **Unified Quick Action Cards Text Style**
  - "Upload Conteúdo" and "Criar Quiz" cards now match "Criar Turma" text alignment
  - All cards use `Column` with `crossAxisAlignment: CrossAxisAlignment.start` for text section
  - Subtitle text supports 2 lines with `maxLines: 2` and `height: 1.2`
  - Consistent typography: title fontSize 16, subtitle fontSize 12
  - "Criar Quiz" subtitle changed to "Avaliações interativas"

- **Pixel Overflow in Classes List Widget**
  - **Causa**: Tentativa de usar `GridView` horizontal para layout de colunas fixas
  - **Solução**: Substituir por `ListView.builder` com `scrollDirection: Axis.horizontal`
  - Cada item do ListView é uma `Column` com 2 cards (índice * 2 e índice * 2 + 1)
  - Cards mantêm tamanho original da lista vertical (sem constraints artificiais)
  - Altura do SizedBox: 280 pixels (suficiente para 2 cards + spacing)

- **Pixel Overflow in Teacher Dashboard Cards**
  - Replaced fixed height constraints with flexible `BoxConstraints(minHeight: 135, maxHeight: 160)`
  - Fixed overflow issues in "Upload Conteúdo" and "Criar Turma" cards
  - Cards now properly adapt to different screen sizes and content

### Planned Features
- Voice interaction capabilities
- Advanced analytics dashboard
- Multi-language support expansion
- Offline mode enhancements
- Integration with learning management systems

### Bug Fixes
- Fixed memory leak in chat interface
- Improved error handling in quiz submission
- Optimized image loading performance
- Enhanced security token validation

---

## [1.0.0] - 2026-05-06

### 🎉 Initial Release

#### Major Features
- **AI-Powered Tutoring System**
  - Multiple interaction modes (Explanation, Tutor, Exploration, Remedial)
  - Context-aware responses using RAG technology
  - Real-time feedback and rating system
  - Support for mathematics, science, and language learning

- **Interactive Quiz System**
  - Multiple question types (Multiple Choice, True/False, Fill in the Blank)
  - Adaptive difficulty adjustment
  - Immediate feedback and explanations
  - Progress tracking and analytics

- **Comprehensive Content Management**
  - Support for PDF, DOCX, video, and audio files
  - Automatic content processing and chunking
  - Metadata extraction and classification
  - Teacher-controlled content approval workflow

- **Advanced Learning Analytics**
  - Concept mastery tracking
  - Spaced repetition scheduling
  - Personalized learning recommendations
  - Detailed progress reports for students and teachers

- **Modern User Interface**
  - Clean, modern design with EPVC school colors
  - Responsive design for mobile, tablet, and web
  - Smooth animations and transitions
  - Accessibility features and dark mode support

#### Technical Implementation
- **Frontend**: Flutter 3.41.0 with Riverpod state management
- **Backend**: Firebase Cloud Functions with TypeScript
- **Database**: Firestore with comprehensive security rules
- **AI/ML**: RAG engine with vector search and LLM integration
- **Authentication**: Firebase Auth with multi-provider support
- **Storage**: Firebase Storage with automatic optimization

#### Security Features
- End-to-end encryption for sensitive data
- Role-based access control (Student, Teacher, Admin)
- Comprehensive audit logging
- GDPR and FERPA compliance
- Rate limiting and DDoS protection

#### Performance Optimizations
- Lazy loading for images and content
- Efficient caching strategies
- Optimized database queries with proper indexing
- Memory management and garbage collection
- API response time optimization

#### Platform Support
- **Mobile**: Android (API 21+) and iOS (iOS 12+)
- **Web**: Modern browsers with CanvasKit rendering
- **Desktop**: Progressive Web App support
- **Offline**: Limited offline functionality with caching

---

## 📋 Development Milestones

### Phase 1: Foundation (Weeks 1-4)
- ✅ Project setup and architecture
- ✅ Firebase configuration
- ✅ Authentication system
- ✅ Basic UI components
- ✅ Core data models

### Phase 2: Core Features (Weeks 5-8)
- ✅ AI tutoring system
- ✅ Quiz functionality
- ✅ Content management
- ✅ Learning analytics
- ✅ Performance optimization

### Phase 3: Enhancement (Weeks 9-12)
- ✅ Advanced UI/UX improvements
- ✅ Security hardening
- ✅ Testing and quality assurance
- ✅ Documentation completion
- ✅ Production deployment

---

## 🔧 Technical Specifications

### Dependencies

#### Flutter Dependencies
```yaml
flutter:
  sdk: '>=3.11.5 <4.0.0'
  
dependencies:
  flutter_riverpod: ^2.4.9
  go_router: ^12.1.3
  firebase_core: ^2.24.2
  firebase_auth: ^4.15.3
  cloud_firestore: ^4.13.6
  firebase_storage: ^11.5.6
  firebase_analytics: ^10.7.4
  firebase_crashlytics: ^3.4.8
  cached_network_image: ^3.3.0
  google_fonts: ^6.1.0
  flutter_animate: ^4.2.0+1
```

#### Backend Dependencies
```json
{
  "dependencies": {
    "@google-cloud/firestore": "^6.7.0",
    "@google-cloud/storage": "^6.11.0",
    "firebase-admin": "^11.10.1",
    "firebase-functions": "^4.4.1",
    "openai": "^4.20.1",
    "anthropic": "^0.6.3",
    "sentence-transformers": "^0.0.1",
    "faiss-node": "^0.5.1",
    "express": "^4.18.2",
    "cors": "^2.8.5",
    "helmet": "^7.0.0"
  }
}
```

#### RAG Engine Dependencies
```python
dependencies = [
    "numpy>=1.21.0",
    "faiss-cpu>=1.7.4",
    "sentence-transformers>=2.2.2",
    "torch>=1.12.0",
    "openai>=1.0.0",
    "anthropic>=0.3.0",
    "nltk>=3.7",
    "spacy>=3.4.0",
]
```

### System Requirements

#### Mobile Requirements
- **Android**: API 21+ (Android 5.0+)
- **iOS**: iOS 12.0+
- **RAM**: Minimum 2GB, Recommended 4GB
- **Storage**: Minimum 100MB free space
- **Network**: Internet connection required for full functionality

#### Web Requirements
- **Browser**: Chrome 90+, Firefox 88+, Safari 14+, Edge 90+
- **RAM**: Minimum 4GB
- **JavaScript**: Enabled
- **Cookies**: Enabled for authentication
- **HTTPS**: Required for secure connections

#### Backend Requirements
- **Node.js**: Version 18.x LTS
- **Python**: Version 3.9+
- **Firebase**: Latest version
- **Memory**: Minimum 2GB RAM
- **Storage**: Minimum 10GB available

---

## 🔄 Migration Guide

### From Previous Versions

#### Version 0.9.x to 1.0.0
- **Breaking Changes**: None
- **New Features**: All features listed above
- **Migration Steps**: No migration required for new installations
- **Data Migration**: Automatic for existing users

#### Configuration Updates
```bash
# Update Flutter dependencies
flutter pub get

# Update Firebase configuration
firebase deploy --only functions

# Clear cache
flutter clean
```

---

## 🐛 Known Issues

### Current Issues
- **Issue**: Memory usage increases with prolonged chat sessions
  - **Status**: Under investigation
  - **Workaround**: Restart app periodically
  - **Fix Planned**: Version 1.1.0

- **Issue**: Some PDF files may not process correctly
  - **Status**: Investigating
  - **Workaround**: Convert to DOCX or use alternative format
  - **Fix Planned**: Version 1.0.1

### Resolved Issues
- ✅ Fixed: Login issues on some Android devices
- ✅ Fixed: Quiz submission failures
- ✅ Fixed: Image loading performance
- ✅ Fixed: Memory leak in content viewer

---

## 🚀 Upcoming Features

### Version 1.1.0 (Planned: Q3 2026)
- **Voice Interaction**: Voice input and output for accessibility
- **Advanced Analytics**: More detailed learning insights
- **Offline Mode**: Enhanced offline functionality
- **Multi-Language**: Support for additional languages
- **Integration**: LMS integration capabilities

### Version 1.2.0 (Planned: Q4 2026)
- **Collaborative Learning**: Study groups and peer tutoring
- **Gamification**: Points, badges, and leaderboards
- **Parent Portal**: Parent access to student progress
- **Advanced AI**: More sophisticated tutoring algorithms
- **Video Chat**: Live video tutoring sessions

---

## 📊 Usage Statistics

### Platform Adoption
- **Total Users**: 0 (Launch day)
- **Active Schools**: 1 (Escola Profissional de Vila do Conde)
- **Content Uploaded**: 0 documents
- **Questions Asked**: 0
- **Quizzes Completed**: 0

### Performance Metrics
- **Average Response Time**: Target < 500ms
- **App Load Time**: Target < 3 seconds
- **Uptime**: Target > 99.5%
- **Error Rate**: Target < 1%

---

## 🤝 Contributing to Change Log

### How to Contribute
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Update this change log
5. Submit a pull request

### Change Log Format
```markdown
## [Version] - YYYY-MM-DD

### [Category]
- **Description of change**
- **Issue**: #123 (if applicable)
- **Breaking**: Yes/No (if applicable)
```

### Categories
- **Added**: New features
- **Changed**: Modifications to existing features
- **Deprecated**: Features marked for removal
- **Removed**: Features removed
- **Fixed**: Bug fixes
- **Security**: Security-related changes

---

## 📞 Support

### Reporting Issues
- **GitHub Issues**: [Create new issue](https://github.com/your-org/teachit/issues)
- **Email**: support@teachit.app
- **In-App**: Use the feedback feature

### Feature Requests
- **GitHub Discussions**: [Start discussion](https://github.com/your-org/teachit/discussions)
- **Email**: features@teachit.app
- **User Voice**: In-app feature request system

### Security Issues
- **Email**: security@teachit.app
- **PGP Key**: Available on request
- **Response Time**: Within 24 hours

---

## 📚 Documentation Updates

### Related Documentation
- [User Guide](USER_GUIDE.md)
- [API Documentation](API_DOCUMENTATION.md)
- [Security Guide](SECURITY_GUIDE.md)
- [Performance Guide](PERFORMANCE_GUIDE.md)
- [Development Setup](DEVELOPMENT_SETUP.md)

### Documentation Changes
- **2026-05-06**: Initial documentation creation
- **2026-05-06**: Updated with comprehensive guides

---

## 📈 Release Schedule

### Release Cadence
- **Major Releases**: Every 6 months
- **Minor Releases**: Every month
- **Patch Releases**: As needed for critical fixes

### Release Process
1. **Development**: Feature development in feature branches
2. **Testing**: Comprehensive testing in staging
3. **Review**: Code review and security audit
4. **Deployment**: Gradual rollout with monitoring
5. **Monitoring**: Post-release performance monitoring

### Version Numbering
- **Major**: X.0.0 - Significant new features
- **Minor**: X.Y.0 - New features and improvements
- **Patch**: X.Y.Z - Bug fixes and security updates

---

## 🏆 Recognition

### Development Team
- **Frontend Team**: Flutter development and UI/UX
- **Backend Team**: Firebase functions and API development
- **AI Team**: RAG engine and LLM integration
- **QA Team**: Testing and quality assurance
- **DevOps Team**: Deployment and infrastructure

### Special Thanks
- **Escola Profissional de Vila do Conde**: Beta testing partner
- **Firebase Team**: Platform and support
- **Flutter Community**: Tools and libraries
- **OpenAI**: AI model integration
- **Anthropic**: AI model integration

---

## 📄 License

### Software License
- **Type**: MIT License
- **Copyright**: 2026 AI Study Assistant Team
- **Permissions**: Commercial use, modification, distribution
- **Conditions**: Include license and copyright notice

### Third-Party Licenses
- **Flutter**: BSD 3-Clause License
- **Firebase**: Google Terms of Service
- **OpenAI**: OpenAI Terms of Use
- **Anthropic**: Anthropic Terms of Service

---

## 🔮 Future Vision

### Long-term Goals
- **Global Reach**: Support for schools worldwide
- **AI Advancement**: State-of-the-art educational AI
- **Personalization**: Hyper-personalized learning experiences
- **Accessibility**: Universal design for learning
- **Innovation**: Continuous improvement and innovation

### Strategic Initiatives
- **Research Partnership**: Educational research collaborations
- **Open Source**: Community-driven development
- **Ecosystem**: Integration with educational tools
- **Sustainability**: Long-term platform sustainability
- **Impact**: Measurable educational outcomes

---

*Last Updated: 2026-05-06*
*Version: 1.0.0*
*Release Team: Product & Engineering*
