package sources

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

	"golang.org/x/time/rate"

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

// ShodanSource implements recon.ReconSource against the Shodan /shodan/host/search
// REST API. It iterates provider keyword queries and emits a Finding for every
// match returned (exposed LLM endpoints, API keys in banners, etc.).
//
// A missing API key disables the source -- Sweep returns nil and Enabled reports
// false.
type ShodanSource struct {
	APIKey   string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	client   *Client
}

// Compile-time assertion.
var _ recon.ReconSource = (*ShodanSource)(nil)

// NewShodanSource constructs a ShodanSource with the shared retry client.
func NewShodanSource(apiKey string, reg *providers.Registry, lim *recon.LimiterRegistry) *ShodanSource {
	return &ShodanSource{
		APIKey:   apiKey,
		BaseURL:  "https://api.shodan.io",
		Registry: reg,
		Limiters: lim,
		client:   NewClient(),
	}
}

func (s *ShodanSource) Name() string          { return "shodan" }
func (s *ShodanSource) RateLimit() rate.Limit { return rate.Every(1 * time.Second) }
func (s *ShodanSource) Burst() int            { return 1 }
func (s *ShodanSource) RespectsRobots() bool  { return false }

// Enabled returns true only when APIKey is configured.
func (s *ShodanSource) Enabled(_ recon.Config) bool { return s.APIKey != "" }

// Sweep issues one /shodan/host/search request per provider keyword and emits
// a Finding for every match returned.
func (s *ShodanSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	if s.APIKey == "" {
		return nil
	}
	base := s.BaseURL
	if base == "" {
		base = "https://api.shodan.io"
	}

	queries := BuildQueries(s.Registry, "shodan")
	kwIndex := shodanKeywordIndex(s.Registry)

	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/shodan/host/search?key=%s&query=%s",
			base, url.QueryEscape(s.APIKey), url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("shodan: build request: %w", err)
		}
		req.Header.Set("Accept", "application/json")
		req.Header.Set("User-Agent", "keyhunter-recon")

		resp, err := s.client.Do(ctx, req)
		if err != nil {
			if errors.Is(err, ErrUnauthorized) {
				return err
			}
			if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
				return err
			}
			continue
		}

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

		provName := kwIndex[strings.ToLower(q)]
		for _, m := range parsed.Matches {
			f := recon.Finding{
				ProviderName: provName,
				Confidence:   "low",
				Source:       fmt.Sprintf("shodan://%s:%d", m.IPStr, m.Port),
				SourceType:   "recon:shodan",
				DetectedAt:   time.Now(),
			}
			select {
			case out <- f:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type shodanSearchResponse struct {
	Matches []shodanMatch `json:"matches"`
}

type shodanMatch struct {
	IPStr string `json:"ip_str"`
	Port  int    `json:"port"`
	Data  string `json:"data"`
}

// shodanKeywordIndex maps lowercased keywords to provider names.
func shodanKeywordIndex(reg *providers.Registry) map[string]string {
	m := make(map[string]string)
	if reg == nil {
		return m
	}
	for _, p := range reg.List() {
		for _, k := range p.Keywords {
			kl := strings.ToLower(strings.TrimSpace(k))
			if kl == "" {
				continue
			}
			if _, exists := m[kl]; !exists {
				m[kl] = p.Name
			}
		}
	}
	return m
}
