# Troubleshooting Guide

This document provides common issues, their solutions, and debugging procedures for the MPV.Rocks Installer project.

## Table of Contents

- [Common Issues](#common-issues)
- [Windows Issues](#windows-issues)
- [Linux Issues](#linux-issues)
- [macOS Issues](#macos-issues)
- [Debugging Procedures](#debugging-procedures)
- [Getting Help](#getting-help)

---

## Common Issues

### Installer Crashes on Startup

**Symptoms:**
- Application crashes immediately on launch
- No log file created
- No error messages displayed

**Possible Causes:**
1. CPU instruction incompatibility (x86-64-v4 binary on v2 CPU)
2. Logging initialization failure
3. Missing dependencies

**Solutions:**

**1. Check CPU Compatibility**
```bash
# Windows: Check CPU features
wmic cpu get Name, MaxClockSpeed, NumberOfCores, Architecture

# Linux: Check CPU features
lscpu | grep "flags" | grep -o avx\|avx2\|avx512
```

**2. Enable Debug Mode**
```bash
# Enable debug logging
./mpv-manager --debug

# This shows initialization steps to stderr
```

**3. Check Dependencies**
```bash
# Go version
go version  # Should be 1.27.0 or later

# Make version
make --version
```

---

### Configuration Not Saving

**Symptoms:**
- Configuration changes not persisted
- Language preferences reset after restart
- HWA settings not applied

**Possible Causes:**
1. File permission denied
2. Config directory doesn't exist
3. Disk full
4. Concurrent write conflicts

**Solutions:**

**1. Check File Permissions**
```bash
# Windows
icacls "$USERPROFILE\.config\mpv"

# Linux/macOS
ls -la ~/.config/mpv/
```

**2. Check Disk Space**
```bash
# Windows
wmic logicaldisk get size,freespace,caption

# Linux/macOS
df -h ~/.config/mpv/
```

**3. Enable Debug Logging**
```bash
# Run with verbose mode
./mpv-manager --verbose

# Check log file
cat ~/.config/mpv/mpv-manager.log  # Linux/macOS
cat "$USERPROFILE\mpv\portable_config\mpv-manager.log"  # Windows
```

**4. Check for Concurrent Writes**
- Only one instance of installer should be running
- Close any other terminal windows or browser tabs

---

### Update Installation Fails

**Symptoms:**
- Download gets stuck or fails
- Update progress bar doesn't advance
- Error: "Failed to download update"

**Possible Causes:**
1. Network connectivity issues
2. Firewall blocking download
3. Server temporarily down
4. Invalid BLAKE3 checksum

**Solutions:**

**1. Check Network Connectivity**
```bash
# Ping release server
ping gitgud.io

# Check DNS
nslookup gitgud.io

# Test the signed public release manifest used by the manager
curl -I https://mpv.rocks/api/releases.json
```

**2. Check Firewall**
```bash
# Windows Firewall
# Control Panel → Windows Defender Firewall → Allowed apps
# Add mpv-manager.exe if not present

# Third-party antivirus
# May need to add to exceptions
```

**3. Verify BLAKE3 Checksum**
```bash
# Checksum verification happens automatically
# See log for: "BLAKE3 verification passed" or "failed"
```

---

### Update Recovery Requires Manual Attention

If startup reports an unauthenticated journal, missing authentication key, or
unavailable rollback backup, the manager retains the journal and available
files. Keep these artifacts until the interrupted operation is reconciled.
Do not run a backup executable simply because a local JSON file names it.

Self-update journal schema 2 authenticates recovery intent using
`.mpv-manager-update-journal.key` in the manager's user configuration directory.
The key must remain private to its owner (Unix mode `0600`; a protected Windows
DACL is applied at creation). Preserve it across updates. Verification never
regenerates a missing key, since doing so cannot authenticate an existing
journal. Changing users or configuration directories can therefore require
manual recovery. If the key was readable by another user, treat it as exposed;
changing permissions alone does not restore trust in existing journals.

Journals from earlier builds lack this authentication and are preserved for
manual inspection. A clean replacement from a verified release can restore the
manager; reconcile the recorded targets and retained configuration backups
before removing old transaction artifacts. Shared writable install directories
are refused for self-update; use a directory owned and controlled by the
current user or an administrator.

Installer recovery also stops when a required backup is missing. This can mean
the original was never moved or that an older recovery already restored it.
The current files are preserved because the journal alone cannot distinguish
those cases safely.

### GPU Detection Fails

**Symptoms:**
- GPU information not displayed
- Codec list shows "unknown"
- Hardware acceleration options incorrect

**Possible Causes:**
1. GPU detection command timeout
2. GPU not in database
3. Platform-specific detection fails

**Solutions:**

**1. Enable Debug Logging**
```bash
./mpv-manager --debug

# Check log for GPU detection steps
```

**2. Run GPU Detection Manually**
```bash
# Linux: Test glxinfo
glxinfo -B | grep "Device"

# Linux: Test vulkaninfo
vulkaninfo --summary | grep deviceName

# Windows: Test PowerShell
powershell -Command "Get-WmiObject Win32_VideoController | Select-Object Name, DriverVersion"

# macOS: Test system_profiler
system_profiler SPHardwareDataType
```

**3. Check GPU Database**
- Ensure GPU model is in lookup tables
- Check for alternative GPU names
- Verify GPU vendor is supported

---

## Windows Issues

### Silent Crashes on Windows

**Symptoms:**
- Application crashes before showing window
- Exception code: 0xc0000005 (ACCESS_VIOLATION)
- Works in QEMU VM but not on real hardware

**Cause:** Binary built with AVX-512 (x86-64-v4) but CPU only supports AVX2 (x86-64-v2)

**Solution:**
- Ensure Makefile has `GOAMD64=v2` for all Windows builds
- Rebuild binary with explicit baseline

```makefile
build-win-x86_64: generate-windows-resources
	@echo "Building for windows/amd64 (x86-64-v2)..."
	@mkdir -p dist
	GOOS=windows GOARCH=amd64 GOAMD64=v2 go build $(LDFLAGS) -o dist/$(BINARY_NAME)-win-x86_64.exe ./cmd/mpv-manager
```

**Verification:**
```bash
# Download v2 build
# Should work on Ryzen 1000-2000 series and Intel Core 2nd gen+

# Test on target machine
# Verify no crashes
```

---

### UAC Prompt Issues

**Symptoms:**
- File association operations fail
- Uninstall fails silently
- No UAC prompt appears

**Possible Causes:**
1. Not running as administrator
2. Batch file not elevated
3. PowerShell elevation fails

**Solutions:**

**1. Run as Administrator**
```powershell
# Right-click → Run as administrator
# Or press Ctrl+Shift while clicking
```

**2. Enable Debug Mode**
```bash
# Check for UAC-related errors in logs
./mpv-manager --debug

# Look for: "access denied", "elevation required"
```

**3. Verify UAC Status**
```powershell
# Check if running as admin
([Security.Principal.WindowsPrincipal]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
```

---

### Console Size Issues

**Symptoms:**
- Menu items cut off
- Success messages not visible
- Only 2 lines visible in TUI

**Cause:** Default cmd window size (80x25)

**Solution:**
- Installer now auto-resizes to 120x40
- Should happen automatically on startup

**Manual Resize:**
```powershell
# PowerShell resize
mode 120,40

# CMD resize (temporary)
powershell -Command "$host.UI.RawUI.SuppressOutput() = $true; mode 120,40"
```

---

## Linux Issues

### Permission Denied

**Symptoms:**
- "Permission denied" errors
- Installation fails
- Configuration not saved

**Possible Causes:**
1. Not running with appropriate permissions
2. SELinux blocking operations
3. Filesystem mounted read-only

**Solutions:**

**1. Check and Fix Permissions**
```bash
# Check file permissions
ls -la ~/.config/mpv/

# Fix permissions (if writable)
chmod 755 ~/.config/mpv/
```

**2. Run with Appropriate Permissions**
```bash
# Try with sudo (for testing only)
sudo ./mpv-manager

# Check if SELinux is blocking
getenforce 0
```

**3. Check Read-Only Filesystem**
```bash
# Check if filesystem is mounted read-only
mount | grep -i read-only
```

---

### Package Manager Issues

**Symptoms:**
- Package installation fails
- Version not detected correctly
- Dependency issues

**Possible Causes:**
1. Package manager not installed
2. Package database not updated
3. Wrong package manager used

**Solutions:**

**1. Verify Package Manager**
```bash
# APT
which apt-cache
apt-cache policy mpv

# Flatpak
which flatpak
flatpak info io.mpv.Mpv

# Snap
which snap
snap list | grep mpv

# Homebrew (macOS)
which brew
brew list | grep mpv
```

**2. Update Package Database**
```bash
# APT
sudo apt update

# Flatpak
flatpak update

# Snap
snap refresh
```

**3. Check Available Packages**
```bash
# Search available packages
apt-cache search mpv
flatpak search mpv
snap search mpv
```

---

### GPU Detection Issues

**Symptoms:**
- GPU not detected
- Wrong GPU information
- Codec list incomplete

**Possible Causes:**
1. Missing GPU detection tools (vainfo, vdpauinfo, glxinfo)
2. Tools installed but not in PATH
3. Driver issues

**Solutions:**

**1. Install GPU Detection Tools**
```bash
# Ubuntu/Debian
sudo apt install vainfo vdpauinfo mesa-utils glxinfo

# Fedora/RHEL
sudo dnf install mesa-utils mesa-dri-utils vulkan-tools

# Arch
sudo pacman -S mesa-utils vulkan-tools
```

**2. Test GPU Detection Tools**
```bash
# Test vainfo
vainfo

# Test glxinfo
glxinfo -B | grep "Device"

# Test vulkaninfo
vulkaninfo --summary
```

**3. Check GPU Drivers**
```bash
# Check NVIDIA driver
nvidia-smi

# Check AMD driver
/opt/amdgpu-pro/amdgpu_pro_cli --showproductname

# Check Intel driver
sudo dmesg | grep i915
```

---

## macOS Issues

### Code Signing Issues

**Symptoms:**
- "App is damaged" message
- "Unidentified developer" message
- Installation blocked

**Possible Causes:**
1. Code signing certificate expired
2. Application not signed (macOS requirement)
3. Quarantine attribute on downloaded file

**Solutions:**

**1. Check Gatekeeper Status**
```bash
# Check if app is quarantined
xattr -l mpv-manager

# Remove quarantine attribute
xattr -d com.apple.quarantine mpv-manager
```

**2. Enable App from Anywhere**
```bash
# System Settings → Security & Privacy → Allow Anywhere
# Add terminal to exceptions if needed
```

**3. Re-download with Secure Connection**
```bash
# Download from official source
# Use HTTPS
# Verify certificate in Keychain
```

---

### Apple Silicon Issues

**Symptoms:**
- Installer crashes on M1/M2 Macs
- Rosetta errors
- Performance issues

**Possible Causes:**
1. Wrong architecture binary (x86_64 vs arm64)
2. Running under Rosetta
3. Missing VideoToolbox frameworks

**Solutions:**

**1. Use Correct Binary**
```bash
# Check architecture
uname -m
# Should return: arm64 for Apple Silicon

# Download arm64 binary
# Not: mpv-manager-darwin-x86_64 (Intel)
```

**2. Check VideoToolbox**
```bash
# Verify VideoToolbox framework is available
system_profiler SPFrameworksDataType | grep -i videotoolbox

# If missing, reinstall Xcode Command Line Tools
xcode-select --install
```

**3. Disable Rosetta**
```bash
# Check if running under Rosetta
arch
# Should show: arm64 (not x86_64)

# If running under Rosetta, uninstall and run native binary
```

---

## Debugging Procedures

### Enable Debug Mode

```bash
# Enable debug logging (shows all initialization steps)
./mpv-manager --debug

# Enable verbose mode (logs to console)
./mpv-manager --verbose

# Enable both
./mpv-manager --debug --verbose
```

### Check Log Files

**Windows:**
```powershell
# Portable config location
type "$env:USERPROFILE\mpv\portable_config\mpv-manager.log"

# Fallback location (if primary fails)
type .\mpv-manager.log
```

**Linux/macOS:**
```bash
# Config location
cat ~/.config/mpv/mpv-manager.log

# Watch log in real-time
tail -f ~/.config/mpv/mpv-manager.log
```

### Run Diagnostic Tests

**Windows:**
```powershell
# Run diagnostic binary (if available)
.\test-minimal.exe
.\test-log.exe
.\test-platform.exe
```

**Linux:**
```bash
# Run with strace (advanced)
strace -e trace=open,openat,read,write ./mpv-manager
```

### Generate Core Dump

**Windows:**
```powershell
# Enable WER (Windows Error Reporting)
# Control Panel → System → About → Advanced System Settings
# Select: "Write debugging information"
```

**Linux:**
```bash
# Enable core dumps
ulimit -c unlimited

# Run with gdb
gdb -ex core ./mpv-manager
```

### Memory Profiling

```bash
# Run with memory profile
./mpv-manager --memprofile=mem.prof

# Analyze profile
go tool pprof mem.prof
```

---

## Getting Help

### Collect Information

Before reporting an issue, collect:

1. **System Information:**
   - OS version and architecture
   - CPU model and features
   - GPU model and driver version
   - Available memory

2. **Issue Description:**
   - What were you doing when it happened?
   - What error message did you see (if any)?
   - Can you reproduce the issue?

3. **Log Files:**
   - Attach installer log file
   - Attach system logs if relevant

4. **Steps to Reproduce:**
   - Detailed step-by-step instructions

5. **Expected vs Actual:**
   - What did you expect to happen?
   - What actually happened?

### Reporting Channels

1. **GitLab issues:** Report bugs at https://gitgud.io/mike/mpv-manager/-/issues
2. **Project activity:** Check existing issues and release notes in the GitLab project
3. **Documentation:** Check existing documentation first
4. **Community:** Ask in community channels

### Useful Commands for Bug Reports

```bash
# Get version
./mpv-manager --version

# Get system info
./mpv-manager --debug 2>&1 | head -50

# Check log file location
cat ~/.config/mpv/mpv-manager.log

# Get installed apps config
cat ~/.config/mpv/installed_apps.json
```

---

## Preventative Measures

### Before Installation

1. [ ] Close other applications (especially media players)
2. [ ] Update operating system and drivers
3. [ ] Disable antivirus temporarily
4. [ ] Ensure adequate disk space (100+ MB)
5. [ ] Backup existing MPV configuration

### During Installation

1. [ ] Don't interrupt installation process
2. [ ] Wait for completion messages
3. [ ] Read error messages carefully
4. [ ] Keep debug log handy if issues occur

### After Installation

1. [ ] Test basic MPV playback
2. [ ] Check configuration applied correctly
3. [ ] Verify file associations work
4. [ ] Report any issues promptly

---

## Known Issues

### Platform-Specific Known Issues

**Windows:**
- OneDrive folder redirection may cause config issues
- Windows Defender may slow initial scan
- Some corporate policies block UAC elevation

**Linux:**
- Flatpak may have portal issues (user approval required)
- AppImages may take time to index
- Some distros have older package versions

**macOS:**
- Gatekeeper may delay first launch
- Code signing requires Apple Developer account
- VideoToolbox framework version dependencies

### Workarounds

**OneDrive Issues:**
```bash
# Disable OneDrive for MPV config
# Use local file path instead of OneDrive path
```

**Windows Defender:**
```powershell
# Add installer to exclusions
# Or temporarily disable real-time protection
```

---

## Quick Reference

### Common Error Messages

| Error | Cause | Solution |
|--------|---------|----------|
| "Permission denied" | File permissions | Run as admin/sudo, fix permissions |
| "Access denied" | UAC required | Run as administrator |
| "File not found" | Missing dependency | Install missing package/tool |
| "Connection refused" | Network/firewall | Check network, disable firewall |
| "Checksum failed" | Corrupted download | Re-download file |
| "Configuration not saved" | Disk full/permissions | Check disk space, fix permissions |
| "Unknown GPU" | GPU not in database | Report GPU model, enable debug |

### Exit Codes

| Code | Meaning | Action |
|-------|-----------|--------|
| 0 | Success | N/A |
| 1 | General error | Check logs, report issue |
| 2 | Misuse | Check command syntax |
| 127 | Command not found | Install missing dependencies |

---

## Conclusion

This troubleshooting guide provides solutions to the most common issues encountered with the MPV.Rocks Installer. For issues not covered here, check:
- [Architecture](ARCHITECTURE.md) - System architecture and design
- [Testing Guide](TESTING.md) - Testing procedures and checklists
- [Atlas Tracker](../TRACKING.md) - Current known work and release blockers

For unresolved issues, please report them with comprehensive information including system details, logs, and reproduction steps.
