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

// HelmSource searches Artifact Hub for Helm charts (kind=0) matching provider
// keywords. Helm charts that reference LLM/AI services may contain API keys
// in their default values.yaml files.
//
// Emits one Finding per chart result, tagged SourceType=recon:helm.
type HelmSource struct {
	// BaseURL defaults to https://artifacthub.io. Tests override with httptest URL.
	BaseURL string
	// Registry drives the keyword query list via BuildQueries.
	Registry *providers.Registry
	// Limiters is the shared recon.LimiterRegistry.
	Limiters *recon.LimiterRegistry
	// Client is the shared retry HTTP wrapper. If nil, a default is used.
	Client *Client
}

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

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

// Enabled always returns true: Artifact Hub search is unauthenticated.
func (s *HelmSource) Enabled(_ recon.Config) bool { return true }

// Sweep iterates provider keywords, searches Artifact Hub for Helm charts
// (kind=0), and emits a Finding for each result.
func (s *HelmSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://artifacthub.io"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

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

		// kind=0 filters to Helm charts only.
		endpoint := fmt.Sprintf("%s/api/v1/packages/search?ts_query_web=%s&kind=0&limit=20",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("helm: build req: %w", err)
		}
		req.Header.Set("Accept", "application/json")

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

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

		for _, pkg := range parsed.Packages {
			if err := ctx.Err(); err != nil {
				return err
			}

			repoName := pkg.Repository.Name
			sourceURL := fmt.Sprintf("https://artifacthub.io/packages/helm/%s/%s",
				repoName, pkg.NormalizedName)
			if base != "https://artifacthub.io" {
				sourceURL = fmt.Sprintf("%s/packages/helm/%s/%s",
					base, repoName, pkg.NormalizedName)
			}

			f := recon.Finding{
				ProviderName: "",
				Source:       sourceURL,
				SourceType:   "recon:helm",
				Confidence:   "low",
				DetectedAt:   time.Now(),
			}
			select {
			case out <- f:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type artifactHubSearchResponse struct {
	Packages []artifactHubPackage `json:"packages"`
}

type artifactHubPackage struct {
	PackageID      string          `json:"package_id"`
	Name           string          `json:"name"`
	NormalizedName string          `json:"normalized_name"`
	Repository     artifactHubRepo `json:"repository"`
}

type artifactHubRepo struct {
	Name string `json:"name"`
	Kind int    `json:"kind"`
}
