package sources

import (
	"context"
	"encoding/xml"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strings"
	"time"

	"golang.org/x/time/rate"

	"github.com/salvacybersec/keyhunter/pkg/providers"
	"github.com/salvacybersec/keyhunter/pkg/recon"
)

// YandexSource implements recon.ReconSource against the Yandex XML Search API.
// It requires both a User and APIKey to be enabled.
type YandexSource struct {
	User     string
	APIKey   string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	client   *Client
}

// Compile-time assertion.
var _ recon.ReconSource = (*YandexSource)(nil)

// NewYandexSource constructs a YandexSource with the shared retry client.
func NewYandexSource(user, apiKey string, reg *providers.Registry, lim *recon.LimiterRegistry) *YandexSource {
	return &YandexSource{
		User:     user,
		APIKey:   apiKey,
		BaseURL:  "https://yandex.com",
		Registry: reg,
		Limiters: lim,
		client:   NewClient(),
	}
}

func (s *YandexSource) Name() string          { return "yandex" }
func (s *YandexSource) RateLimit() rate.Limit { return rate.Every(1 * time.Second) }
func (s *YandexSource) Burst() int            { return 1 }
func (s *YandexSource) RespectsRobots() bool  { return false }

// Enabled returns true only when both User and APIKey are configured.
func (s *YandexSource) Enabled(_ recon.Config) bool {
	return s.User != "" && s.APIKey != ""
}

// Sweep issues one Yandex XML search request per provider keyword and emits a
// Finding for every <url> element in the response.
func (s *YandexSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	if s.User == "" || s.APIKey == "" {
		return nil
	}
	base := s.BaseURL
	if base == "" {
		base = "https://yandex.com"
	}

	queries := BuildQueries(s.Registry, "yandex")
	kwIndex := yandexKeywordIndex(s.Registry)

	for _, q := range queries {
		if err := ctx.Err(); err != nil {
			return err
		}
		if s.Limiters != nil {
			if err := s.Limiters.Wait(ctx, s.Name(), s.RateLimit(), s.Burst(), false); err != nil {
				return err
			}
		}

		endpoint := fmt.Sprintf("%s/search/xml?user=%s&key=%s&query=%s&l10n=en&sortby=rlv&filter=none&groupby=%s",
			base,
			url.QueryEscape(s.User),
			url.QueryEscape(s.APIKey),
			url.QueryEscape(q),
			url.QueryEscape(`attr="".mode=flat.groups-on-page=50`))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("yandex: build request: %w", err)
		}
		req.Header.Set("User-Agent", "keyhunter-recon")

		resp, err := s.client.Do(ctx, req)
		if err != nil {
			if errors.Is(err, ErrUnauthorized) {
				return err
			}
			if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
				return err
			}
			continue
		}

		var parsed yandexSearchResponse
		decErr := xml.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

		provName := kwIndex[strings.ToLower(extractGoogleKeyword(q))]
		for _, grp := range parsed.Response.Results.Grouping.Groups {
			for _, doc := range grp.Docs {
				if doc.URL == "" {
					continue
				}
				f := recon.Finding{
					ProviderName: provName,
					Confidence:   "low",
					Source:       doc.URL,
					SourceType:   "recon:yandex",
					DetectedAt:   time.Now(),
				}
				select {
				case out <- f:
				case <-ctx.Done():
					return ctx.Err()
				}
			}
		}
	}
	return nil
}

// XML response structures for Yandex XML Search API.
type yandexSearchResponse struct {
	XMLName  xml.Name       `xml:"yandexsearch"`
	Response yandexResponse `xml:"response"`
}

type yandexResponse struct {
	Results yandexResults `xml:"results"`
}

type yandexResults struct {
	Grouping yandexGrouping `xml:"grouping"`
}

type yandexGrouping struct {
	Groups []yandexGroup `xml:"group"`
}

type yandexGroup struct {
	Docs []yandexDoc `xml:"doc"`
}

type yandexDoc struct {
	URL string `xml:"url"`
}

// yandexKeywordIndex maps lowercased keywords to provider names.
func yandexKeywordIndex(reg *providers.Registry) map[string]string {
	m := make(map[string]string)
	if reg == nil {
		return m
	}
	for _, p := range reg.List() {
		for _, k := range p.Keywords {
			kl := strings.ToLower(strings.TrimSpace(k))
			if kl == "" {
				continue
			}
			if _, exists := m[kl]; !exists {
				m[kl] = p.Name
			}
		}
	}
	return m
}
