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

// GoogleDorkSource implements recon.ReconSource against the Google Custom
// Search JSON API. It iterates provider keyword queries (via BuildQueries)
// and emits a recon.Finding for every search result item returned.
//
// Both APIKey and CX (custom search engine ID) must be set for the source to
// be enabled. Missing credentials disable the source without error.
type GoogleDorkSource struct {
	APIKey   string
	CX       string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	client   *Client
}

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

// NewGoogleDorkSource constructs a GoogleDorkSource with the shared retry client.
func NewGoogleDorkSource(apiKey, cx string, reg *providers.Registry, lim *recon.LimiterRegistry) *GoogleDorkSource {
	return &GoogleDorkSource{
		APIKey:   apiKey,
		CX:       cx,
		BaseURL:  "https://www.googleapis.com",
		Registry: reg,
		Limiters: lim,
		client:   NewClient(),
	}
}

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

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

// Sweep issues one Custom Search request per provider keyword and emits a
// Finding for every result item.
func (s *GoogleDorkSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	if s.APIKey == "" || s.CX == "" {
		return nil
	}
	base := s.BaseURL
	if base == "" {
		base = "https://www.googleapis.com"
	}

	queries := BuildQueries(s.Registry, "google")
	kwIndex := googleKeywordIndex(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/customsearch/v1?key=%s&cx=%s&q=%s&num=10",
			base, url.QueryEscape(s.APIKey), url.QueryEscape(s.CX), url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("google: build request: %w", err)
		}
		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 googleSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

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

type googleSearchResponse struct {
	Items []googleSearchItem `json:"items"`
}

type googleSearchItem struct {
	Title   string `json:"title"`
	Link    string `json:"link"`
	Snippet string `json:"snippet"`
}

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

// extractGoogleKeyword reverses the dork query format to recover the keyword.
func extractGoogleKeyword(q string) string {
	// Format: site:pastebin.com OR site:github.com "keyword"
	idx := strings.LastIndex(q, `"`)
	if idx <= 0 {
		return q
	}
	inner := q[:idx]
	start := strings.LastIndex(inner, `"`)
	if start < 0 {
		return q
	}
	return inner[start+1:]
}
