package sources

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

	"golang.org/x/time/rate"

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

// GoProxySource searches pkg.go.dev for Go modules matching provider keywords.
// pkg.go.dev returns HTML search results, so we parse anchor hrefs for module
// paths. No authentication required.
type GoProxySource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

// goProxyLinkRE matches Go module paths which always contain a domain with a
// dot (e.g. /github.com/user/repo). This filters out simple paths like /about.
var goProxyLinkRE = regexp.MustCompile(`^/[a-z][a-z0-9_-]*\.[a-z0-9./_-]+$`)

// Compile-time assertion that GoProxySource satisfies recon.ReconSource.
var _ recon.ReconSource = (*GoProxySource)(nil)

func (s *GoProxySource) Name() string          { return "goproxy" }
func (s *GoProxySource) RateLimit() rate.Limit { return rate.Every(2 * time.Second) }
func (s *GoProxySource) Burst() int            { return 2 }
func (s *GoProxySource) RespectsRobots() bool  { return false }

// Enabled always returns true: pkg.go.dev requires no credentials.
func (s *GoProxySource) Enabled(_ recon.Config) bool { return true }

// Sweep queries pkg.go.dev search for each provider keyword, parses the HTML
// response for module path links, and emits a Finding per result.
func (s *GoProxySource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://pkg.go.dev"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "goproxy")
	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
			}
		}

		endpoint := fmt.Sprintf("%s/search?q=%s&m=package", base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("goproxy: build request: %w", err)
		}

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

		links, parseErr := extractAnchorHrefs(resp.Body, goProxyLinkRE)
		_ = resp.Body.Close()
		if parseErr != nil {
			continue
		}

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