package sources

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

	"golang.org/x/time/rate"

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

// MavenSource searches Maven Central for artifacts matching provider keywords.
// Maven Central exposes a Solr-based JSON search API that requires no
// authentication.
type MavenSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// Enabled always returns true: Maven Central requires no credentials.
func (s *MavenSource) Enabled(_ recon.Config) bool { return true }

// Sweep queries Maven Central's Solr search for each provider keyword and
// emits a Finding per matching artifact.
func (s *MavenSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://search.maven.org"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "maven")
	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/solrsearch/select?q=%s&rows=20&wt=json",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("maven: build request: %w", err)
		}
		req.Header.Set("Accept", "application/json")

		resp, err := client.Do(ctx, req)
		if err != nil {
			continue // non-fatal: skip keyword on HTTP error
		}

		var parsed mavenSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

		for _, doc := range parsed.Response.Docs {
			if err := ctx.Err(); err != nil {
				return err
			}
			src := fmt.Sprintf("https://search.maven.org/artifact/%s/%s/%s/jar",
				doc.Group, doc.Artifact, doc.LatestVersion)
			select {
			case out <- recon.Finding{
				Source:     src,
				SourceType: "recon:maven",
				Confidence: "low",
				DetectedAt: time.Now(),
			}:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type mavenSearchResponse struct {
	Response mavenResponseBody `json:"response"`
}

type mavenResponseBody struct {
	Docs []mavenDoc `json:"docs"`
}

type mavenDoc struct {
	Group         string `json:"g"`
	Artifact      string `json:"a"`
	LatestVersion string `json:"latestVersion"`
}
