package sources

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"

	"golang.org/x/time/rate"

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

// RedditSource searches Reddit's public JSON API for posts containing leaked
// API keys. Developers frequently share code snippets with credentials in
// subreddits like r/learnprogramming, r/openai, and r/machinelearning.
type RedditSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

var _ recon.ReconSource = (*RedditSource)(nil)

func (s *RedditSource) Name() string               { return "reddit" }
func (s *RedditSource) RateLimit() rate.Limit       { return rate.Every(2 * time.Second) }
func (s *RedditSource) Burst() int                  { return 2 }
func (s *RedditSource) RespectsRobots() bool        { return false }
func (s *RedditSource) Enabled(_ recon.Config) bool { return true }

// redditListingResponse represents the Reddit JSON API search response.
type redditListingResponse struct {
	Data redditListingData `json:"data"`
}

type redditListingData struct {
	Children []redditChild `json:"children"`
}

type redditChild struct {
	Data redditPost `json:"data"`
}

type redditPost struct {
	Selftext  string `json:"selftext"`
	Permalink string `json:"permalink"`
	Title     string `json:"title"`
}

func (s *RedditSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://www.reddit.com"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "reddit")
	if len(queries) == 0 {
		return nil
	}

	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
			}
		}

		searchURL := fmt.Sprintf("%s/search.json?q=%s&sort=new&limit=25&restrict_sr=false",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("Accept", "application/json")
		// Reddit blocks requests with default User-Agent.
		req.Header.Set("User-Agent", "keyhunter-recon/1.0 (API key scanner)")

		resp, err := client.Do(ctx, req)
		if err != nil {
			continue
		}

		body, err := io.ReadAll(io.LimitReader(resp.Body, 256*1024))
		_ = resp.Body.Close()
		if err != nil {
			continue
		}

		var result redditListingResponse
		if err := json.Unmarshal(body, &result); err != nil {
			continue
		}

		for _, child := range result.Data.Children {
			if ciLogKeyPattern.MatchString(child.Data.Selftext) {
				postURL := fmt.Sprintf("https://www.reddit.com%s", child.Data.Permalink)
				out <- recon.Finding{
					ProviderName: q,
					Source:       postURL,
					SourceType:   "recon:reddit",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
