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

// DockerHubSource searches Docker Hub for public images matching provider
// keywords. Unauthenticated search is rate-limited but freely accessible.
//
// Emits one Finding per repository result, tagged SourceType=recon:dockerhub.
type DockerHubSource struct {
	// BaseURL defaults to https://hub.docker.com. 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 DockerHubSource satisfies recon.ReconSource.
var _ recon.ReconSource = (*DockerHubSource)(nil)

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

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

// Sweep iterates provider keywords, searches Docker Hub for matching
// repositories, and emits a Finding for each result.
func (s *DockerHubSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://hub.docker.com"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

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

		resp, err := client.Do(ctx, req)
		if err != nil {
			// Non-fatal: skip this keyword on transient errors.
			continue
		}

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

		for _, repo := range parsed.Results {
			if err := ctx.Err(); err != nil {
				return err
			}
			sourceURL := fmt.Sprintf("https://hub.docker.com/r/%s", repo.RepoName)
			if base != "https://hub.docker.com" {
				sourceURL = fmt.Sprintf("%s/r/%s", base, repo.RepoName)
			}
			f := recon.Finding{
				ProviderName: "",
				Source:       sourceURL,
				SourceType:   "recon:dockerhub",
				Confidence:   "low",
				DetectedAt:   time.Now(),
			}
			select {
			case out <- f:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type dockerHubSearchResponse struct {
	Results []dockerHubRepo `json:"results"`
}

type dockerHubRepo struct {
	RepoName    string `json:"repo_name"`
	Description string `json:"description"`
	IsOfficial  bool   `json:"is_official"`
}
