# Architecture

This document provides comprehensive information about the MPV.Rocks Installer system architecture, package organization, and design patterns.

## Table of Contents

- [Package Organization](#package-organization)
- [Key Packages](#key-packages)
- [Design Patterns](#design-patterns)
- [Data Flow](#data-flow)
- [Component Interaction](#component-interaction)

---

## Package Organization

```
mpv-manager/
├── cmd/
│   ├── mpv-manager/          # Main TUI application
│   ├── generate-info/         # Release JSON generator
│   └── gen-checksums/        # BLAKE3 checksum generator
├── pkg/
│   ├── platform/             # Platform detection (reusable)
│   │   ├── platform.go       # Detect(), OS/arch/distro checks
│   │   ├── cpu.go           # AVX2 support detection
│   │   └── linux.go         # Linux-specific detection
│   │
│   ├── constants/            # Single source of truth
│   │   ├── constants.go      # Method IDs, paths, commands, permissions
│   │   └── paths.go        # Config paths, backup utilities
│   │
│   ├── config/             # App configuration
│   │   └── config.go       # Load/Save, installed apps tracking
│   │
│   ├── version/            # Version management
│   │   ├── version.go       # Version info, self-update
│   │   └── updates.go      # Update detection for managed apps
│   │
│   ├── log/                # Logging infrastructure
│   │   └── logger.go       # Thread-safe logging to file
│   │
│   ├── installer/          # Installation logic
│   │   ├── common.go       # Shared utilities (backup, restore, paths)
│   │   ├── package_manager.go # Package manager abstraction
│   │   ├── installer.go     # Base installer and ReleaseInfo types
│   │   ├── command_runner.go # Command execution with output streaming
│   │   ├── windows.go      # Windows-specific installation
│   │   ├── linux.go        # Linux-specific installation
│   │   └── macos.go        # macOS-specific installation
│   │
│   ├── locale/             # Language preferences data
│   │   ├── locale.go       # 123+ languages with regions
│   │   ├── selection.go    # Language filtering and selection
│   │   └── flag_map.go     # Language code to flag emoji mapping
│   │
│   └── tui/               # Terminal UI (Bubbletea)
│       ├── models.go       # Core constants and Model struct
│       ├── models_types.go # Message types and list items
│       ├── models_init.go  # Constructor and setters
│       ├── models_messages.go # tea.Cmd wrappers
│       ├── models_update.go # Update() method
│       ├── models_views.go  # All View methods
│       └── language_preferences.go # Language preference feature
│
├── internal/
│   └── assets/             # Embedded configuration files (mpv.conf)
├── Makefile                # Build automation
├── go.mod                  # Go module definition
└── PROJECT_PLAN.md          # Detailed project roadmap
```

---

## Key Packages

### pkg/platform

**Purpose:** Platform detection and hardware information gathering

**Key Functions:**
- `Detect()` - Main entry point for platform detection
- `GetOS()` - Returns OS type (Windows, Linux, Darwin)
- `GetArch()` - Returns system architecture
- `GetDistro()` - Returns Linux distribution
- `GetDistroFamily()` - Returns distro family (debian, rhel, arch, etc.)
- `GetCPUInfo()` - Returns CPU details (model, features, cores)
- `GetGPU()` - Returns GPU information (model, vendor, VRAM)
- `DetectCodecs()` - Detects supported video codecs (AV1, HEVC, VP9, etc.)

**Platform-Specific Detection:**
- **Linux:** glxinfo, vulkaninfo, lspci, sysfs DRM
- **Windows:** wmic, PowerShell GPU commands
- **macOS:** system_profiler, CGO-based VideoToolbox API

### pkg/constants

**Purpose:** Single source of truth for all constant values

**Key Categories:**
- **Config Keys:** MPV configuration keys (alang, slang, hwdec, vo, scale)
- **Method IDs:** Installation method identifiers
- **HTTP Constants:** Content types, methods, status codes
- **Log Prefixes:** API, SSE, Installer prefixes
- **Modal Types:** Shutdown, update, uninstall, reset, etc.
- **Query Parameters:** API query parameter names
- **Status Values:** Success, failure, shutdown messages

**Example Constants:**
```go
const (
    ConfigKeyAudioLanguage    = "alang"
    ConfigKeySubtitleLanguage = "slang"
    ConfigKeyHardwareDecoder  = "hwdec"
    ConfigKeyVideoOutput      = "vo"
    ConfigKeyScaleFilter      = "scale"
    ConfigKeyDitherAlgorithm  = "dither-depth-convert"
    
    ContentTypeJSON = "application/json"
    ContentTypeHTML = "text/html"
    
    LogPrefixAPI = "[API]"
    LogPrefixSSE = "[SSE]"
)
```

### pkg/config

**Purpose:** Configuration management for installed apps and settings

**Key Functions:**
- `Load()` - Loads configuration from file
- `Save()` - Saves configuration to file
- `GetConfigValue()` - Reads MPV config value (alang, slang, hwdec, etc.)
- `SetConfigValue()` - Writes MPV config value with backup
- `GetInstalledApps()` - Returns list of installed applications
- `AddInstalledApp()` - Adds app to installed apps list
- `RemoveInstalledApp()` - Removes app from installed apps list
- `GetInstallPath()` - Returns installation directory

**Config Locations:**
- **Windows:** `~/mpv/portable_config/`
- **Linux/macOS:** `~/.config/mpv/`
- **Backups:** `conf_backups/` subdirectory

### pkg/version

**Purpose:** Version management and update detection

**Key Functions:**
- `GetCurrentVersion()` - Returns current installer version
- `GetLatestVersion()` - Fetches latest version from release server
- `CheckForUpdate()` - Compares versions, returns update availability
- `UpdateSelf()` - Self-updates the installer binary
- `UpdateSelfWithProgress()` - Self-updates with progress tracking
- `DownloadFileWithProgress()` - Downloads file with progress callback

**Features:**
- Automatic update checking on startup
- Visual progress bars for downloads
- 3-retry logic with exponential backoff
- BLAKE3 checksum verification
- PATH update after successful update

### pkg/installer

**Purpose:** Cross-platform installation logic

**Key Interfaces:**
- `InstallationHandler` - Interface for platform-specific installers
- `WindowsInstaller` - Windows implementation
- `LinuxInstaller` - Linux implementation
- `MacOSInstaller` - macOS implementation

**Key Functions:**
- `Install()` - Main installation entry point
- `Uninstall()` - Uninstallation logic
- `InstallMPVConfigWithOutput()` - Installs MPV configuration with streaming output
- `RestoreConfigWithOutput()` - Restores configuration backup
- `SetupFileAssociationsWithOutput()` - Sets MPV as default for video files
- `RemoveFileAssociationsWithOutput()` - Removes MPV file associations
- `CreateInstallerShortcutWithOutput()` - Creates desktop/menu shortcuts

**Command Runner:**
- `StartStreamingCommand()` - Starts command with SSE event streaming
- Output streamed via channels for real-time TUI display
- Support for stdout and stderr streaming

### pkg/web

**Purpose:** Web UI server and API endpoints

**Key Components:**
- **Server** - HTTP server with templates and static assets
- **API Handlers** - RESTful API endpoints for config, install, uninstall, updates
- **SSE** - Server-Sent Events for real-time output streaming
- **Package Detection** - Detects package manager versions (apt, flatpak, snap, brew)

**API Endpoints:**
- `GET /api/` - Server information
- `POST /api/install` - Install MPV client
- `POST /api/uninstall` - Uninstall app
- `POST /api/config/apply` - Apply configuration settings
- `GET /api/languages/load` - Load language preferences
- `POST /api/languages/save` - Save language preferences
- `GET /api/check-updates` - Check for updates
- `POST /api/modal` - Get modal configuration
- `POST /api/shutdown` - Shutdown server

**Features:**
- Embedded templates and static assets
- Input validation on all endpoints
- SSE streaming for installation output
- Modal system for confirmations
- App card widgets for consistent styling

### pkg/locale

**Purpose:** Language and regional data management

**Key Functions:**
- `GetLanguage()` - Returns language info by code
- `GetMajorLanguages()` - Returns common/major languages (33 languages)
- `GetRegionalVariants()` - Returns regional variants for a language
- `GetAllLanguages()` - Returns all 123+ languages

**Data Structures:**
```go
type Language struct {
    Code        string    // ISO 639-1 language code (en, zh, es)
    EnglishName string    // English name (English, Chinese, Spanish)
    NativeName  string    // Native name (English, 中文, Español)
    Region      string    // Region/country (US, CN, ES)
    Direction   string    // Text direction (ltr, rtl)
}

type RegionalVariant struct {
    Code        string // Regional code (en-US, zh-CN, es-ES)
    Language    string // Base language code
    Region      string // Region name (United States, China, Spain)
    NativeName  string // Native regional name
}
```

**Flag Mapping:**
- Language code to country flag emoji
- Supports 33 major languages
- Extended mapping for Czech, Danish, Greek, Hebrew, Swedish, Filipino

### pkg/tui

**Purpose:** Terminal User Interface (Bubbletea)

**Key Components:**
- **Model** - Main state container
- **Views** - View rendering functions
- **Messages** - Tea message types and commands
- **Update Handlers** - State transition logic

**Views:**
- `mainMenuView` - Main menu display
- `platformInfoView` - System information display
- `appsView` - MPV Player Apps selection
- `updatesView` - Updates menu display
- `hwaOptionsView` - Hardware acceleration options
- `configOptionsView` - Configuration options
- `languagePrefsView` - Language preferences interface

**State Machine:**
```go
const (
    StateMainMenu State = iota
    StatePlatformInfo
    StateApps
    StateUpdates
    StateConfigOptions
    StateHWAOptions
    StateLanguagePrefs
    StateInstalling
    StateFileAssociationsMenu
    StateRestoreConfig
    // ... more states
)
```

---

## Design Patterns

### InstallationHandler Interface

Platform-specific installers implement a common interface:

```go
type InstallationHandler interface {
    Install(methodID string, installPath string) (*InstallationResult, error)
    Uninstall(appName string, installPath string) error
    InstallMPVConfigWithOutput(config string, outputChan chan<- string) error
    SetupFileAssociationsWithOutput(installPath string, outputChan chan<- string) error
    RemoveFileAssociationsWithOutput(installPath string, outputChan chan<- string) error
    CreateInstallerShortcutWithOutput(installPath string, appName string, outputChan chan<- string) error
}
```

**Benefits:**
- Consistent API across platforms
- Easy to add new platforms
- Type-safe implementations
- Testable interfaces

### Command Output Streaming

Commands are executed with output streaming to TUI:

```go
func StartStreamingCommand(cmd *exec.Cmd, outputChan chan<- string) error {
    stdout, err := cmd.StdoutPipe()
    stderr, err := cmd.StderrPipe()
    // Stream lines to outputChan
    go streamOutput(stdout, outputChan)
    go streamOutput(stderr, outputChan)
    return cmd.Start()
}
```

**Benefits:**
- Real-time output display
- No buffering
- Separate stdout/stderr
- Non-blocking

### SSE Event Streaming

Server-Sent Events for real-time installation updates:

```go
func (s *Server) handleInstallSSE(w http.ResponseWriter, r *http.Request) {
    // Set SSE headers
    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    // Create event channel
    eventChan := make(chan SSEEvent)

    // Stream events
    for event := range eventChan {
        fmt.Fprintf(w, "event: %s\n", event.Type)
        fmt.Fprintf(w, "data: %s\n\n", event.Data)
        flusher.Flush()
    }
}
```

**Event Types:**
- `start` - Installation started
- `stdout` - Standard output line
- `stderr` - Error output line
- `success` - Installation completed successfully
- `error` - Installation failed
- `done` - Installation finished

### Input Validation

Comprehensive validation on all API endpoints:

```go
func ValidateConfigValue(key, value string) error
func ValidateMethodID(methodID string) error
func ValidateAppName(appName string) error
func ValidateAppType(appType string) error
func ValidateLanguageCode(code string) error
func ValidateHWAValue(method string) error
func ValidateInstallMethod(methodID string, isWindows, isDarwin, isLinux bool) error
```

**Benefits:**
- Prevents invalid data
- Clear error messages
- Platform-specific validation
- Type-safe validation

### Retry Pattern

Consistent retry logic with exponential backoff:

```go
func saveWithRetry(maxRetries int) error {
    delays := []time.Duration{1*time.Second, 2*time.Second, 3*time.Second}
    var errors []string

    for attempt := 0; attempt < maxRetries; attempt++ {
        if attempt > 0 {
            time.Sleep(delays[attempt-1])
        }

        err := performOperation()
        if err == nil {
            return nil // Success
        }

        errors = append(errors, err.Error())
    }

    return fmt.Errorf("failed after %d attempts: %s", maxRetries, strings.Join(errors, "; "))
}
```

**Benefits:**
- Handles transient failures
- Exponential backoff
- Accumulated error tracking
- Clear error messages

---

## Data Flow

### Installation Flow

```
User selects app and method
    ↓
Validate method ID and platform compatibility
    ↓
Get install path from config or user input
    ↓
Create platform-specific InstallationHandler
    ↓
Install(methodID, installPath)
    ↓
Streaming command execution with SSE events
    ↓
Output displayed in TUI/Web UI
    ↓
InstallationResult with success/error
    ↓
Add to installed_apps config if success
    ↓
Return to menu
```

### Configuration Flow

```
User opens language preferences
    ↓
Load from mpv.conf (GetConfigValue)
    ↓
Display current selections
    ↓
User modifies selections
    ↓
Click "Save" button
    ↓
Validate language codes
    ↓
Save with retry logic (SetConfigValue)
    ↓
Backup created on first write
    ↓
mpv.conf updated
    ↓
Success message displayed
```

### Update Check Flow

```
App startup / User clicks "Check for Updates"
    ↓
GetCurrentVersion()
    ↓
GetLatestVersion() from release server
    ↓
Compare versions
    ↓
If new version available:
    ├─ Display update notification
    └─ Add to Updates menu
    ↓
If user clicks "Update Installer":
    ├─ DownloadFileWithProgress() with progress tracking
    ├─ BLAKE3 verification
    ├─ Replace binary
    └─ Update PATH and quit
```

---

## Component Interaction

### TUI and Web UI

**TUI (Terminal UI):**
- Uses Bubbletea framework
- Direct calls to config, installer, version packages
- Keyboard navigation
- Command output streaming via channels

**Web UI:**
- HTTP server with embedded assets
- REST API for config and install operations
- SSE for real-time installation output
- HTML templates with Tailwind CSS styling

**Shared Components:**
- pkg/config - Configuration management
- pkg/constants - Shared constants
- pkg/installer - Installation logic
- pkg/locale - Language data
- pkg/version - Version management

### Cross-Platform Support

**Platform Detection:**
- pkg/platform detects OS, architecture, distribution
- Platform-specific installers selected at runtime
- Hardware-acceleration methods filtered by platform

**Hardware Detection:**
- GPU detection with codec support
- CPU feature detection (AVX2, AVX512, NEON)
- Platform-specific detection methods (vainfo, wmic, system_profiler)

### Configuration Management

**MPV Configuration:**
- Single source of truth in ~/.config/mpv/mpv.conf
- Backup creation before writes
- ConfigPreservationHandler pattern for automatic backups
- Language preferences with retry logic

**Installer Configuration:**
- Installed apps tracked in config file
- Install path saved per app
- Version tracking for updates

---

## Code Conventions

### File Organization

**Package Size:**
- Keep packages focused and single-purpose
- Split large files when exceeding 500 lines
- Related functionality grouped together

**Naming Conventions:**
- Package names: lowercase, single word (platform, config, installer)
- Interface names: Descriptive + "Handler" suffix (InstallationHandler)
- Struct names: Descriptive (InstallationResult, ReleaseInfo)
- Functions: PascalCase for exported (GetInstallPath, ValidateConfigValue)

### Code Style

- Follow Go conventions (`go fmt ./...`)
- Use meaningful variable names
- Add comments for public APIs
- Keep functions focused and small
- Prefer composition over inheritance

### Error Handling

- Always return errors, never panic
- Provide context with errors (fmt.Errorf)
- Use sentinel errors for known conditions
- Log errors with stack traces when useful

---

## Testing Considerations

### Unit Testing

- Test functions in isolation
- Mock external dependencies (HTTP, file system)
- Test error paths and edge cases
- Maintain 80%+ test coverage

### Integration Testing

- Test package interactions
- Test platform-specific code on target platforms
- Test installation/uninstallation flows
- Test configuration persistence

### Manual Testing

- Test on all supported platforms (Windows, Linux, macOS)
- Test with various hardware configurations
- Test error recovery and retry logic
- User acceptance testing

---

## Performance Considerations

### Startup Performance

- Lazy loading of platform-specific data
- Cached platform detection results
- Parallel HTTP requests where possible

### Runtime Performance

- Streaming output for immediate display
- Minimal memory allocations
- Efficient string operations
- Goroutine pool for concurrent operations

### Build Time

- Minimal dependencies
- Fast compilation with Go toolchain
- Cross-compilation support for all platforms

---

## Security Considerations

### Input Validation

- Validate all user inputs
- Sanitize file paths
- Validate method IDs against whitelist
- Platform compatibility checks

### File Operations

- Use atomic writes for config files
- Create backups before modifications
- Validate file permissions
- Secure temporary file handling

### Network Operations

- Validate HTTPS certificates
- Validate download checksums
- Rate limiting for API calls
- Timeout on network operations

---

## Future Enhancements

### Architecture Improvements

1. **Plugin System:** Add extensibility for third-party installers
2. **Multi-Language UI:** Full internationalization support
3. **Modular UI Components:** Reusable UI widgets library
4. **Event Bus:** Decoupled component communication

### Platform Support

1. **BSD Support:** Add FreeBSD, OpenBSD support
2. **ARM64 Windows:** Native Windows ARM64 support
3. **Embedded Linux:** Support for embedded distros

### Performance Improvements

1. **Lazy Loading:** On-demand asset loading
2. **Caching:** Persistent cache for API responses
3. **Streaming:** Progressive loading for large operations
4. **Parallelism:** Increased concurrent operations
