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"
)

// BraveSource implements recon.ReconSource against the Brave Search API.
// It requires an API key (X-Subscription-Token) to be enabled.
type BraveSource struct {
	APIKey   string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	client   *Client
}

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

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

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

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

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

	queries := BuildQueries(s.Registry, "brave")
	kwIndex := braveKeywordIndex(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/res/v1/web/search?q=%s&count=20", base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("brave: build request: %w", err)
		}
		req.Header.Set("X-Subscription-Token", 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 braveSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

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

type braveSearchResponse struct {
	Web braveWebResults `json:"web"`
}

type braveWebResults struct {
	Results []braveWebItem `json:"results"`
}

type braveWebItem struct {
	URL         string `json:"url"`
	Title       string `json:"title"`
	Description string `json:"description"`
}

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