package collector

import (
	"os/exec"
	"strings"
)

type UpdateInfo struct {
	UpdateAvailable bool                `json:"update_available"`
	PendingCount    int                 `json:"pending_count"`
	SecurityCount   int                 `json:"security_count"`
	Updates         []PendingUpdateInfo `json:"updates"`
}

type PendingUpdateInfo struct {
	Package    string `json:"package"`
	Arch       string `json:"arch"`
	CurrentVer string `json:"current_version"`
	NewVer     string `json:"new_version"`
	Repository string `json:"repository"`
	Security   bool   `json:"security"`
}

func CollectUpdates() *UpdateInfo {
	updates := &UpdateInfo{
		UpdateAvailable: false,
		PendingCount:    0,
		SecurityCount:   0,
		Updates:         []PendingUpdateInfo{},
	}

	// apt list --upgradable, LC_ALL=C erzwingt englische Ausgabe
	cmd := exec.Command("/usr/bin/apt", "list", "--upgradable")
	cmd.Env = append(cmd.Env, "LC_ALL=C", "LANG=C", "PATH=/usr/bin:/bin")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return collectUpdatesAptCheck()
	}

	lines := strings.Split(string(output), "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "WARNING:") || strings.HasPrefix(line, "Listing...") {
			continue
		}

		// Format: package/suite new-version arch [upgradable from: old-version]
		// Beispiel: curl/focal-security 7.68.0-1ubuntu2.7 amd64 [upgradable from: 7.68.0-1ubuntu2.6]
		if !strings.Contains(line, "[upgradable from:") {
			continue
		}

		// Package-Name und Suite trennen
		parts := strings.SplitN(line, "/", 2)
		if len(parts) < 2 {
			continue
		}
		packageName := parts[0]

		remaining := parts[1]
		// Suite ist das erste Wort vor dem Leerzeichen
		suiteParts := strings.SplitN(remaining, " ", 2)
		suite := suiteParts[0]
		// Repository: letzter Teil der Suite (z.B. "focal-security/main" → "main")
		// oder einfach die Suite selbst
		repository := suite
		if idx := strings.LastIndex(suite, "/"); idx >= 0 {
			repository = suite[idx+1:]
		}

		// Security erkennen: Suite enthält "security"
		// Beispiel: bookworm-security, trixie-security, buster/updates
		suiteLower := strings.ToLower(suite)
		isSecurity := strings.Contains(suiteLower, "security") ||
			strings.HasSuffix(suiteLower, "/updates")

		// Rest nach Suite parsen: "new-version arch [upgradable from: old-version]"
		afterSuite := ""
		if len(suiteParts) > 1 {
			afterSuite = suiteParts[1]
		}

		beforeUpgradable := strings.SplitN(afterSuite, " [upgradable from:", 2)
		if len(beforeUpgradable) < 2 {
			continue
		}

		versionAndArch := strings.Fields(strings.TrimSpace(beforeUpgradable[0]))
		newVersion := ""
		arch := ""
		if len(versionAndArch) >= 1 {
			newVersion = versionAndArch[0]
		}
		if len(versionAndArch) >= 2 {
			arch = versionAndArch[1]
		}

		oldVersion := strings.TrimSuffix(strings.TrimSpace(beforeUpgradable[1]), "]")

		updates.Updates = append(updates.Updates, PendingUpdateInfo{
			Package:    packageName,
			Arch:       arch,
			CurrentVer: oldVersion,
			NewVer:     newVersion,
			Repository: repository,
			Security:   isSecurity,
		})
		if isSecurity {
			updates.SecurityCount++
		}
	}

	updates.PendingCount = len(updates.Updates)
	updates.UpdateAvailable = updates.PendingCount > 0

	return updates
}

// Fallback-Methode mit apt-check (Ubuntu/Debian)
func collectUpdatesAptCheck() *UpdateInfo {
	updates := &UpdateInfo{
		UpdateAvailable: false,
		PendingCount:    0,
		SecurityCount:   0,
		Updates:         []PendingUpdateInfo{},
	}

	cmd := exec.Command("/usr/lib/update-notifier/apt-check")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return collectUpdatesAptGetSimulate()
	}

	result := strings.TrimSpace(string(output))
	parts := strings.SplitN(result, ";", 2)

	if len(parts) >= 1 && parts[0] != "0" {
		updates.UpdateAvailable = true
		updates.PendingCount = 1
		updates.Updates = []PendingUpdateInfo{
			{
				Package:    "system-updates",
				Arch:       "",
				CurrentVer: "various",
				NewVer:     "available",
				Repository: "unknown",
				Security:   false,
			},
		}
	}

	return updates
}

// Letzter Fallback mit apt-get simulate
func collectUpdatesAptGetSimulate() *UpdateInfo {
	updates := &UpdateInfo{
		UpdateAvailable: false,
		PendingCount:    0,
		SecurityCount:   0,
		Updates:         []PendingUpdateInfo{},
	}

	cmd := exec.Command("/usr/bin/apt-get", "-s", "upgrade")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return updates
	}

	lines := strings.Split(string(output), "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "Inst ") {
			fields := strings.Fields(line)
			if len(fields) >= 3 {
				updates.Updates = append(updates.Updates, PendingUpdateInfo{
					Package:    fields[1],
					Arch:       "",
					CurrentVer: "unknown",
					NewVer:     "available",
					Repository: "unknown",
					Security:   false,
				})
			}
		}
	}

	updates.PendingCount = len(updates.Updates)
	updates.UpdateAvailable = updates.PendingCount > 0

	return updates
}
