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

// KubernetesSource searches Artifact Hub for Kubernetes operators and manifests
// matching provider keywords. This discovers publicly published K8s packages
// that may embed API keys in their manifests or values files.
//
// Emits one Finding per package result, tagged SourceType=recon:k8s.
type KubernetesSource 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 KubernetesSource satisfies recon.ReconSource.
var _ recon.ReconSource = (*KubernetesSource)(nil)

func (s *KubernetesSource) Name() string          { return "k8s" }
func (s *KubernetesSource) RateLimit() rate.Limit { return rate.Every(3 * time.Second) }
func (s *KubernetesSource) Burst() int            { return 1 }
func (s *KubernetesSource) RespectsRobots() bool  { return true }

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

// Sweep iterates provider keywords, searches Artifact Hub for Kubernetes
// operators (kind=6), and emits a Finding for each result.
func (s *KubernetesSource) 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, "k8s")
	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 left empty to search across all Kubernetes-related package types.
		endpoint := fmt.Sprintf("%s/api/v1/packages/search?ts_query_web=%s&limit=20",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("k8s: build req: %w", err)
		}
		req.Header.Set("Accept", "application/json")

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

		var parsed k8sSearchResponse
		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 := ""
			if pkg.Repository.Name != "" {
				repoName = pkg.Repository.Name
			}

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

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

type k8sSearchResponse struct {
	Packages []k8sPackage `json:"packages"`
}

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

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

// k8sKindPath maps Artifact Hub kind integers to URL path segments.
func k8sKindPath(kind int) string {
	switch kind {
	case 0:
		return "helm"
	case 6:
		return "kube-operator"
	case 7:
		return "kubectl"
	default:
		return "other"
	}
}
