package assets

import (
	"context"
	"fmt"
	"strings"

	"tm/pkg/logger"
)

// Service defines business logic for flag operations
type Service interface {
	// Get flag as SVG content only
	GetFlagSVG(ctx context.Context, countryCode string) string
}

// flagService implements the Service interface
type flagService struct {
	logger    logger.Logger
	flagsPath string
}

// NewService creates a new flag service
func NewService(logger logger.Logger, flagsPath string) Service {
	return &flagService{
		logger:    logger,
		flagsPath: flagsPath,
	}
}

// GetFlagSVG retrieves only the SVG content for a flag
func (s *flagService) GetFlagSVG(ctx context.Context, countryCode string) string {
	s.logger.Info("Getting flag SVG for country", map[string]interface{}{
		"country_code": countryCode,
	})

	// Normalize country code
	countryCode = strings.ToUpper(countryCode)

	defaultFlag, err := GetFlagAsset(s.flagsPath, "eu")
	if err != nil {
		s.logger.Error("Failed to get default flag SVG", map[string]interface{}{
			"country_code": countryCode,
			"error":        err.Error(),
		})
		return s.getDefaultFlag()
	}

	// Get ISO code
	isoCode := GetISOCode(countryCode)

	// Get SVG data
	svgData, err := s.getFlagSVG(isoCode)
	if err != nil {
		s.logger.Error("Failed to get flag SVG", map[string]interface{}{
			"country_code": countryCode,
			"iso_code":     isoCode,
			"error":        err.Error(),
		})
		return string(defaultFlag)
	}

	s.logger.Info("Successfully retrieved flag SVG", map[string]interface{}{
		"country_code": countryCode,
		"iso_code":     isoCode,
	})

	return svgData
}

// getFlagSVG retrieves the SVG content for a given ISO code
func (s *flagService) getFlagSVG(isoCode string) (string, error) {
	// Try to get from filesystem
	svgData, err := GetFlagAsset(s.flagsPath, isoCode)
	if err == nil {
		return string(svgData), nil
	}

	// If not found in filesystem, return error
	s.logger.Warn("Flag not found in filesystem", map[string]interface{}{
		"iso_code": isoCode,
		"path":     s.flagsPath,
	})

	return "", fmt.Errorf("failed to get flag SVG, %v from %v", isoCode, s.flagsPath)
}

// getDefaultFlag returns a default flag SVG when all fallbacks fail
func (s *flagService) getDefaultFlag() string {
	// Return a simple default flag SVG
	return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 30">
  <rect width="60" height="30" fill="#012169"/>
  <text x="30" y="20" text-anchor="middle" fill="white" font-family="Arial" font-size="12">EU</text>
</svg>`
}
