package nvidia

import (
	"bufio"
	"strings"

	"git.mchus.pro/mchus/logpile/internal/models"
)

// ParseOutputLog parses output.log file which contains dmidecode output
func ParseOutputLog(content []byte, result *models.AnalysisResult) error {
	scanner := bufio.NewScanner(strings.NewReader(string(content)))

	inSystemInfo := false

	for scanner.Scan() {
		line := scanner.Text()
		trimmed := strings.TrimSpace(line)

		// Detect "System Information" section
		if strings.Contains(trimmed, "System Information") {
			inSystemInfo = true
			continue
		}

		// Exit section when we hit another Handle or empty section
		if inSystemInfo && strings.HasPrefix(trimmed, "Handle ") {
			inSystemInfo = false
			continue
		}

		// Parse fields in System Information section
		if inSystemInfo && strings.Contains(line, ":") {
			parts := strings.SplitN(trimmed, ":", 2)
			if len(parts) != 2 {
				continue
			}

			field := strings.TrimSpace(parts[0])
			value := strings.TrimSpace(parts[1])

			if value == "" {
				continue
			}

			switch field {
			case "Manufacturer":
				result.Hardware.BoardInfo.Manufacturer = value
			case "Product Name":
				result.Hardware.BoardInfo.ProductName = value
			case "Serial Number":
				result.Hardware.BoardInfo.SerialNumber = value
			case "Version":
				// Store version in part number if needed
				if result.Hardware.BoardInfo.PartNumber == "" {
					result.Hardware.BoardInfo.PartNumber = value
				}
			case "UUID":
				// Store UUID somewhere if needed (we don't have a field for it yet)
				// Could add to FRU or as a custom field
			case "Family":
				// Could store family info if needed
			}
		}
	}

	return scanner.Err()
}
