package sources

import (
	"context"
	"encoding/json"
	"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"
)

// BingDorkSource implements recon.ReconSource against the Bing Web Search
// API v7. It iterates provider keyword queries and emits a Finding per result.
//
// A missing API key disables the source without error.
type BingDorkSource struct {
	APIKey   string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	client   *Client
}

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

// NewBingDorkSource constructs a BingDorkSource with the shared retry client.
func NewBingDorkSource(apiKey string, reg *providers.Registry, lim *recon.LimiterRegistry) *BingDorkSource {
	return &BingDorkSource{
		APIKey:   apiKey,
		BaseURL:  "https://api.bing.microsoft.com",
		Registry: reg,
		Limiters: lim,
		client:   NewClient(),
	}
}

func (s *BingDorkSource) Name() string          { return "bing" }
func (s *BingDorkSource) RateLimit() rate.Limit { return rate.Every(500 * time.Millisecond) }
func (s *BingDorkSource) Burst() int            { return 2 }
func (s *BingDorkSource) RespectsRobots() bool  { return false }

// Enabled returns true only when APIKey is configured.
func (s *BingDorkSource) Enabled(_ recon.Config) bool { return s.APIKey != "" }

// Sweep issues one Bing Web Search request per provider keyword and emits a
// Finding for every webPages.value result.
func (s *BingDorkSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	if s.APIKey == "" {
		return nil
	}
	base := s.BaseURL
	if base == "" {
		base = "https://api.bing.microsoft.com"
	}

	queries := BuildQueries(s.Registry, "bing")
	kwIndex := bingKeywordIndex(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/v7.0/search?q=%s&count=50", base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("bing: build request: %w", err)
		}
		req.Header.Set("Ocp-Apim-Subscription-Key", s.APIKey)
		req.Header.Set("Accept", "application/json")
		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 bingSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

		provName := kwIndex[strings.ToLower(extractGoogleKeyword(q))]
		for _, it := range parsed.WebPages.Value {
			f := recon.Finding{
				ProviderName: provName,
				Confidence:   "low",
				Source:       it.URL,
				SourceType:   "recon:bing",
				DetectedAt:   time.Now(),
			}
			select {
			case out <- f:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type bingSearchResponse struct {
	WebPages bingWebPages `json:"webPages"`
}

type bingWebPages struct {
	Value []bingWebResult `json:"value"`
}

type bingWebResult struct {
	Name    string `json:"name"`
	URL     string `json:"url"`
	Snippet string `json:"snippet"`
}

// bingKeywordIndex maps lowercased keywords to provider names.
func bingKeywordIndex(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
}
