package inspur

import (
	"regexp"
	"strings"

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

var (
	hostnameJSONRegex = regexp.MustCompile(`"_HOSTNAME"\s*:\s*"([^"]+)"`)
)

func inferBoardSerialFromFallbackLogs(files []parser.ExtractedFile) string {
	// Prefer FRU dump when present.
	if f := parser.FindFileByName(files, "fru.txt"); f != nil {
		fruList := ParseFRU(f.Content)
		for _, fru := range fruList {
			serial := strings.TrimSpace(fru.SerialNumber)
			if serial == "" || serial == "0" {
				continue
			}
			desc := strings.ToLower(strings.TrimSpace(fru.Description))
			if strings.Contains(desc, "builtin") || strings.Contains(desc, "fru device") {
				return serial
			}
		}
	}

	// Fallback to explicit hostname file.
	if f := parser.FindFileByName(files, "hostname"); f != nil {
		if serial := sanitizeCandidateSerial(firstNonEmptyLine(string(f.Content))); serial != "" {
			return serial
		}
	}

	// Last-resort fallback from structured journal logs.
	if f := parser.FindFileByName(files, "maintenance_json.log"); f != nil {
		if m := hostnameJSONRegex.FindSubmatch(f.Content); len(m) == 2 {
			if serial := sanitizeCandidateSerial(string(m[1])); serial != "" {
				return serial
			}
		}
	}

	return ""
}

func inferBoardModelFromFallbackLogs(files []parser.ExtractedFile) string {
	// Prefer FRU dump when present.
	if f := parser.FindFileByName(files, "fru.txt"); f != nil {
		fruList := ParseFRU(f.Content)
		for _, fru := range fruList {
			model := sanitizeCandidateModel(fru.ProductName)
			if model == "" {
				continue
			}
			desc := strings.ToLower(strings.TrimSpace(fru.Description))
			if strings.Contains(desc, "builtin") || strings.Contains(desc, "fru device") {
				return model
			}
		}
	}

	return ""
}

func firstNonEmptyLine(s string) string {
	for _, line := range strings.Split(s, "\n") {
		line = strings.TrimSpace(line)
		if line != "" {
			return line
		}
	}
	return ""
}

func sanitizeCandidateSerial(s string) string {
	s = strings.TrimSpace(s)
	if s == "" || strings.EqualFold(s, "localhost") || strings.ContainsAny(s, " \t") {
		return ""
	}
	return s
}

func sanitizeCandidateModel(s string) string {
	s = strings.TrimSpace(s)
	if s == "" || strings.EqualFold(s, "null") || s == "0" {
		return ""
	}
	return s
}
