package ingest

import (
	"bytes"
	"fmt"
	"strings"

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

type Service struct{}

type RedfishSourceMetadata struct {
	TargetHost     string
	SourceTimezone string
	Filename       string
}

func NewService() *Service {
	return &Service{}
}

func (s *Service) AnalyzeArchivePayload(filename string, payload []byte) (*models.AnalysisResult, string, error) {
	p := parser.NewBMCParser()
	if err := p.ParseFromReader(bytes.NewReader(payload), filename); err != nil {
		return nil, "", err
	}
	return p.Result(), p.DetectedVendor(), nil
}

func (s *Service) AnalyzeRedfishRawPayloads(rawPayloads map[string]any, meta RedfishSourceMetadata) (*models.AnalysisResult, string, error) {
	result, err := collector.ReplayRedfishFromRawPayloads(rawPayloads, nil)
	if err != nil {
		return nil, "", err
	}
	if result == nil {
		return nil, "", fmt.Errorf("redfish replay returned nil result")
	}
	if strings.TrimSpace(result.Protocol) == "" {
		result.Protocol = "redfish"
	}
	if strings.TrimSpace(result.SourceType) == "" {
		result.SourceType = models.SourceTypeAPI
	}
	if strings.TrimSpace(result.TargetHost) == "" {
		result.TargetHost = strings.TrimSpace(meta.TargetHost)
	}
	if strings.TrimSpace(result.SourceTimezone) == "" {
		result.SourceTimezone = strings.TrimSpace(meta.SourceTimezone)
	}
	if strings.TrimSpace(result.Filename) == "" {
		if strings.TrimSpace(meta.Filename) != "" {
			result.Filename = strings.TrimSpace(meta.Filename)
		} else if target := strings.TrimSpace(result.TargetHost); target != "" {
			result.Filename = "redfish://" + target
		} else {
			result.Filename = "redfish://snapshot"
		}
	}
	return result, "redfish", nil
}
