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

// TerraformSource searches the Terraform Registry for modules matching
// provider keywords. Modules that reference LLM/AI provider credentials may
// contain hardcoded API keys in their variable defaults or examples.
//
// Emits one Finding per module result, tagged SourceType=recon:terraform.
type TerraformSource struct {
	// BaseURL defaults to https://registry.terraform.io. Tests override.
	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 TerraformSource satisfies recon.ReconSource.
var _ recon.ReconSource = (*TerraformSource)(nil)

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

// Enabled always returns true: Terraform Registry search is unauthenticated.
func (s *TerraformSource) Enabled(_ recon.Config) bool { return true }

// Sweep iterates provider keywords, searches Terraform Registry for matching
// modules, and emits a Finding for each result.
func (s *TerraformSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://registry.terraform.io"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

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

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

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

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

			sourceURL := fmt.Sprintf("https://registry.terraform.io/modules/%s/%s/%s",
				mod.Namespace, mod.Name, mod.Provider)
			if base != "https://registry.terraform.io" {
				sourceURL = fmt.Sprintf("%s/modules/%s/%s/%s",
					base, mod.Namespace, mod.Name, mod.Provider)
			}

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

type terraformSearchResponse struct {
	Modules []terraformModule `json:"modules"`
}

type terraformModule struct {
	ID          string `json:"id"`
	Namespace   string `json:"namespace"`
	Name        string `json:"name"`
	Provider    string `json:"provider"`
	Description string `json:"description"`
}
