package service

import (
	"errors"
	"strings"
	"time"
)

func (a *App) cachedDevices(host string) ([]Device, error) {
	host = strings.TrimSpace(host)
	if host == "" {
		host = a.settings.DefaultFlashHost
	}
	a.mu.RLock()
	snapshot, ok := a.deviceStore[host]
	a.mu.RUnlock()
	if !ok {
		return nil, nil
	}
	if strings.TrimSpace(snapshot.Err) != "" {
		return cloneDevices(snapshot.Devices), errors.New(snapshot.Err)
	}
	return cloneDevices(snapshot.Devices), nil
}

func (a *App) recordDevices(host string, devices []Device, err error) {
	host = strings.TrimSpace(host)
	if host == "" {
		host = a.settings.DefaultFlashHost
	}
	snapshot := deviceSnapshot{
		Devices:   cloneDevices(devices),
		CheckedAt: time.Now().UTC(),
	}
	if err != nil {
		snapshot.Err = err.Error()
	}
	a.mu.Lock()
	if existing, ok := a.deviceStore[host]; ok && len(snapshot.Devices) == 0 {
		snapshot.Devices = cloneDevices(existing.Devices)
	}
	a.deviceStore[host] = snapshot
	a.mu.Unlock()
}

func deviceScore(device Device) int {
	score := 0
	model := strings.ToLower(strings.TrimSpace(device.Model))
	switch {
	case strings.Contains(model, "microsd"), strings.Contains(model, "micro sd"):
		score += 60
	case strings.Contains(model, "sdxc"), strings.Contains(model, "sdhc"), strings.Contains(model, "sd "):
		score += 50
	case strings.Contains(model, "card"), strings.Contains(model, "reader"):
		score += 40
	}
	if device.Removable {
		score += 20
	}
	if device.Hotplug {
		score += 10
	}
	if device.Transport == "usb" {
		score += 5
	}
	if strings.HasPrefix(device.Name, "mmcblk") {
		score += 25
	}
	return score
}

func moveToFront(values []string, preferred string) []string {
	if preferred == "" || len(values) < 2 {
		return values
	}
	out := append([]string{}, values...)
	for idx, value := range out {
		if value != preferred {
			continue
		}
		copy(out[1:idx+1], out[:idx])
		out[0] = preferred
		return out
	}
	return out
}
