# Known Issues and Solutions

**Last Updated**: July 1, 2025 - Current Session  
**Purpose**: Comprehensive list of current bugs, their status, and solutions

---

## 🚨 Critical Issues (Blocks Core Functionality)

### ⚠️ **ACTIVE**: Jellyfin Library API 500 Error
**Status**: 🔄 **IN PROGRESS** - July 1, 2025  
**Severity**: Critical  
**Impact**: Cannot load library data after authentication

**Error Message**:
```
[HTTP 500] /api/jellyfin/library
AttributeError: 'str' object has no attribute 'get'
```

**Root Cause**: 
Artist data processing expects dict but sometimes receives string values

**Current Fix Applied**:
```python
# Safer artist data handling in jellyfin_service.py
artist = track.get('Artists', [{}])
if isinstance(artist, list) and len(artist) > 0:
    artist_name = artist[0].get('Name', 'Unknown Artist') if isinstance(artist[0], dict) else str(artist[0])
else:
    artist_name = str(artist) if artist else 'Unknown Artist'
```

**Next Steps**: Test authentication flow and verify library loading

### ⚠️ **ACTIVE**: Navigation Conflicts Between Top/Bottom Nav
**Status**: 🔄 **PARTIALLY FIXED** - July 1, 2025  
**Severity**: High  
**Impact**: Inconsistent tab switching, potential event listener conflicts

**Symptoms**:
- Both top and bottom navigation exist but may conflict
- Event listeners may be duplicated or override each other
- Bottom nav sometimes unclickable

**Progress**:
- ✅ Fixed z-index and pointer-events CSS
- ✅ Consolidated event listeners in single function
- ✅ Added hover effects and visual feedback
- 🔄 Need to test both navigation systems work together

**Current Status**: Both navs visible, need end-to-end testing

### ❌ **RESOLVED**: JavaScript Uninitialized Variable Error
**Status**: ✅ **FIXED** - July 1, 2025 05:10  
**Severity**: Critical  
**Impact**: Prevented library loading completely

**Error Message**:
```
[Error] Library loading error:
ReferenceError: Cannot access uninitialized variable.
(anonymous function) — localhost:3262
```

**Root Cause**: 
Duplicate `const libraryCount` declarations in two JavaScript functions:
- `loadLibrary()` function (line 3212)
- `loadLibraryData()` function (line 3248)

**Solution Applied**:
```javascript
// BEFORE (broken):
function loadLibraryData() {
    const libraryContent = document.getElementById('libraryContent');
    const libraryCount = document.getElementById('libraryCount');  // DUPLICATE!
    // ...
    libraryCount.textContent = `${data.total} songs`;  // ERROR HERE
}

// AFTER (fixed):
function loadLibraryData() {
    const libraryContent = document.getElementById('libraryContent');
    // ...
    const libraryCount = document.getElementById('libraryCount');  // LOCAL SCOPE
    libraryCount.textContent = `${data.total} songs`;
}
```

**Prevention**: Always check for variable scope conflicts in nested functions

---

## 🔧 High Priority Issues (Affects Main Features)

### ⚠️ **ACTIVE**: Jellyfin Authentication localStorage Mismatch
**Status**: 🔍 **INVESTIGATING**  
**Severity**: High  
**Impact**: Library cannot connect to Jellyfin server

**Symptoms**:
- Library tab shows "Connect to your Music Server" message
- Authentication requests fail with server URL errors
- localStorage contains incorrect server URL

**Root Cause**: 
Previous testing cached wrong server URL in browser localStorage:
- **Cached**: `https://jellyfin.sammgmt.com` (incorrect)
- **Correct**: `https://jellyfin.samcloud.ca` (from environment)

**Immediate Workaround**:
1. Go to Settings tab
2. Click red "Reset Settings" button
3. Enter correct credentials:
   - Server URL: `https://jellyfin.samcloud.ca`
   - Username: [your actual username]
   - Password: [your actual password]
4. Click "Test Connection"
5. Click "Save Settings" if successful

**Technical Details**:
```javascript
// Problematic localStorage entries:
localStorage.getItem('musicServerUrl')        // Wrong URL cached
localStorage.getItem('musicServerUsername')   // May be incorrect
localStorage.getItem('musicServerPassword')   // May be incorrect
localStorage.getItem('musicServerConnected')  // False due to wrong URL
```

**Permanent Solution** (Implemented):
- Default server URL now uses environment value
- Reset Settings button clears all cached data
- Auto-populate with correct defaults

**Testing Status**: Needs verification in browser

---

## 🔍 Medium Priority Issues (Quality of Life)

### ⚠️ **ACTIVE**: Missing Socket.IO Source Maps
**Status**: 🔍 **COSMETIC**  
**Severity**: Low  
**Impact**: Console 404 errors (no functional impact)

**Error Messages**:
```
[Error] Failed to load resource: the server responded with a status of 404 (NOT FOUND) (socket.io.min.js.map, line 0)
[Error] Failed to load resource: the server responded with a status of 404 (NOT FOUND) (socket.io.js.map, line 0)
```

**Cause**: 
Using minified Socket.IO library without corresponding source map files

**Solutions**:
1. **Option A**: Use non-minified Socket.IO version
2. **Option B**: Add source map files to static directory
3. **Option C**: Disable source map loading in production

**Current Impact**: 
- ✅ Functionality works perfectly
- ❌ Console shows 404 errors
- ❌ Debugging slightly harder

**Priority**: Low (cosmetic only)

---

## ✅ Recently Resolved Issues

### ✅ **RESOLVED**: No Backup System
**Fixed**: July 1, 2025 05:08  
**Issue**: Risk of losing working code during development
**Solution**: Complete backup system implemented
- **Location**: `/Volumes/SamMgmt/Containers/SpotSpot/Backup/SamCloud_Music_20250701_050806`
- **Content**: Full project with documentation
- **Recovery**: Detailed instructions available

### ✅ **RESOLVED**: No Documentation Structure  
**Fixed**: July 1, 2025 05:09  
**Issue**: Scripts and documentation scattered throughout project
**Solution**: Organized folder structure created
```
docs/
├── development/     # Progress tracking
├── technical/       # System documentation
├── troubleshooting/ # Problem solving guides
├── scripts/         # Utility scripts
└── backups/         # Backup procedures
```

### ✅ **RESOLVED**: Container Instability
**Fixed**: Previous sessions  
**Issue**: Docker container failing to start or crashing
**Solution**: Fixed environment variables and dependencies
**Status**: Container now stable with 15-second restart time

---

## 🔄 Pending Investigation

### 🔍 **INVESTIGATE**: Complete Workflow Testing
**Status**: 🧪 **NEEDS TESTING**  
**Priority**: High  
**Description**: End-to-end workflow from Settings → Library → Music Player

**Test Scenarios Needed**:
1. **Fresh Install Workflow**:
   - Clear all localStorage
   - Configure Jellyfin settings  
   - Authenticate successfully
   - Load library items
   - Play music track

2. **Reset Workflow**:
   - Use Reset Settings button
   - Reconfigure with correct credentials
   - Verify library loads properly

3. **Music Player Workflow**:
   - Select track from library
   - Verify audio streams properly
   - Test player controls (play/pause/next/previous)
   - Confirm progress bar updates

### 🔍 **INVESTIGATE**: Performance with Large Libraries
**Status**: 🧪 **NEEDS TESTING**  
**Priority**: Medium  
**Description**: How the app handles libraries with 1000+ tracks

**Potential Issues**:
- Library loading timeout
- UI responsiveness with many items
- Memory usage during library browsing
- Search performance within library

**Test Plan**:
1. Connect to large Jellyfin library
2. Monitor loading times
3. Test search and filtering
4. Check browser memory usage

---

## 🚫 Known Limitations

### Browser Compatibility
**Tested**: Chrome, Safari, Firefox (latest versions)
**Untested**: Internet Explorer, older mobile browsers
**Requirements**: Modern browser with WebSocket support

### Container Resource Requirements
**Minimum**: 1 CPU, 512MB RAM
**Recommended**: 2 CPU, 1GB RAM
**Storage**: Depends on download volume
**Network**: Stable internet for Spotify/Jellyfin APIs

### External Service Dependencies
**Spotify API**: Required for search functionality
- Rate limits: 100 requests per minute
- Availability: 99.9% (Spotify's responsibility)

**Jellyfin Server**: Required for library functionality
- User-hosted: Availability depends on user setup
- Network access: Must be reachable from container

### Download Limitations
**Concurrent Downloads**: Limited to 5 simultaneous
**Audio Quality**: Maximum 320kbps MP3
**Source**: Depends on YouTube-DL backend availability
**Geographic**: Some content may be region-restricted

---

## 🛠️ Troubleshooting Procedures

### Quick Diagnostics

#### **Step 1: Container Health Check**
```bash
cd "/Volumes/SamMgmt/Containers/SamCloud Music"
docker-compose ps                    # Check container status
docker-compose logs --tail=20       # Check recent logs
curl http://localhost:6544           # Test web interface
```

**Expected Results**:
- Container status: "Up"
- Logs: No error messages in last 20 lines
- Curl: Returns HTML content

#### **Step 2: WebSocket Connection Test**
1. Open browser to `http://localhost:6544`
2. Open Developer Tools → Console
3. Look for connection messages:
   ```
   ✅ WebSocket connected successfully
   Socket ID: "xxxxx"
   ```

**If WebSocket fails**:
- Check firewall settings
- Verify port 6544 is available
- Restart container: `docker-compose restart`

#### **Step 3: API Endpoint Test**
```bash
# Test Jellyfin authentication
curl -X POST "http://localhost:6544/api/jellyfin/auth" \
  -H "Content-Type: application/json" \
  -d '{"server_url": "https://jellyfin.samcloud.ca", "username": "test", "password": "test"}'

# Expected: {"success": false, "error": "Authentication failed - Invalid username or password"}
# This confirms the endpoint works and server is reachable
```

### Advanced Diagnostics

#### **Container Debug Mode**
```bash
# Access container shell
docker-compose exec samcloud-music /bin/bash

# Check Python environment
python --version
pip list | grep -E "(flask|socketio|spotdl)"

# Check file permissions
ls -la /data /temp /config
```

#### **Network Connectivity**
```bash
# From container, test external services
docker-compose exec samcloud-music ping -c 3 google.com
docker-compose exec samcloud-music curl -s https://jellyfin.samcloud.ca/system/info/public
```

#### **Memory and CPU Usage**
```bash
# Monitor container resources
docker stats samcloud-music

# Check for memory leaks
docker-compose logs | grep -i "memory\|oom"
```

### Recovery Procedures

#### **Level 1: Soft Reset**
```bash
# Restart container only
docker-compose restart
```
**Use When**: Minor glitches, WebSocket connection issues

#### **Level 2: Full Rebuild**
```bash
# Rebuild container from scratch
docker-compose down
docker-compose up --build
```
**Use When**: Configuration changes, dependency updates

#### **Level 3: Complete Reset**
```bash
# Stop and remove everything
docker-compose down --volumes --remove-orphans

# Clear browser localStorage
# Go to browser Dev Tools → Application → localStorage → Clear All

# Rebuild and restart
docker-compose up --build
```
**Use When**: Persistent authentication issues, corrupted state

#### **Level 4: Backup Restoration**
```bash
# Stop current deployment
cd "/Volumes/SamMgmt/Containers/SamCloud Music"
docker-compose down

# Restore from backup
cd "/Volumes/SamMgmt/Containers"
rm -rf "SamCloud Music"
cp -R "SpotSpot/Backup/SamCloud_Music_20250701_050806" "SamCloud Music"

# Restart with restored code
cd "SamCloud Music"
docker-compose up --build
```
**Use When**: Code changes break functionality, need to revert to working state

---

## 📞 Support Information

### Error Reporting Template
When reporting new issues, include:

```markdown
**Error Description**: Brief description of the problem

**Steps to Reproduce**:
1. Step 1
2. Step 2
3. Step 3

**Expected Behavior**: What should happen

**Actual Behavior**: What actually happens

**Environment**:
- Browser: [Chrome/Safari/Firefox + version]
- Container Status: [Up/Down/Restarting]
- Recent Changes: [Any configuration or code changes]

**Console Errors**: 
[Copy any JavaScript errors from browser console]

**Container Logs**:
[Output from `docker-compose logs --tail=20`]

**Screenshot/Video**: [If applicable]
```

### Common Questions

**Q: Library tab shows "Connect to your Music Server" even after authentication**  
**A**: This is usually a localStorage cache issue. Use the "Reset Settings" button in Settings tab and reconfigure.

**Q: Downloads start but never complete**  
**A**: Check container logs for SpotDL errors. May be network, API rate limiting, or source availability issues.

**Q: WebSocket connection keeps dropping**  
**A**: Usually indicates container instability or network issues. Try container restart first.

**Q: Music player doesn't play tracks from library**  
**A**: Verify Jellyfin server accessibility and check that stream URLs are valid in network tab of browser dev tools.

---

**Document Version**: 1.0.0  
**Next Review**: After resolving authentication issues  
**Maintainer**: Development team
