package sources

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"regexp"
	"time"

	"golang.org/x/time/rate"

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

// PyPISource searches pypi.org for packages matching provider keywords.
// Scrapes the HTML search page since PyPI has no public search JSON API.
// No credentials required. Emits findings tagged SourceType=recon:pypi.
type PyPISource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

// pypiProjectRE matches /project/{name}/ hrefs in search results.
var pypiProjectRE = regexp.MustCompile(`^/project/[^/]+/?$`)

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

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

	queries := BuildQueries(s.Registry, "pypi")
	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/?q=%s", base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			return fmt.Errorf("pypi: build req: %w", err)
		}

		resp, err := client.Do(ctx, req)
		if err != nil {
			return fmt.Errorf("pypi: fetch: %w", err)
		}

		hrefs, err := extractPyPIProjectLinks(resp.Body)
		_ = resp.Body.Close()
		if err != nil {
			return fmt.Errorf("pypi: parse html: %w", err)
		}

		for _, href := range hrefs {
			if err := ctx.Err(); err != nil {
				return err
			}
			absURL := base + href
			out <- recon.Finding{
				ProviderName: "",
				Source:       absURL,
				SourceType:   "recon:pypi",
				Confidence:   "low",
				DetectedAt:   time.Now(),
			}
		}
	}
	return nil
}

// extractPyPIProjectLinks extracts unique /project/{name}/ hrefs from HTML.
func extractPyPIProjectLinks(body io.Reader) ([]string, error) {
	return extractAnchorHrefs(body, pypiProjectRE)
}
