package sources

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

	"golang.org/x/time/rate"

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

// CensysSource implements recon.ReconSource against the Censys v2 /hosts/search
// API. It iterates provider keyword queries and emits a Finding for every hit
// returned (exposed services leaking API keys).
//
// Missing API credentials disable the source without error.
type CensysSource struct {
	APIId     string
	APISecret string
	BaseURL   string
	Registry  *providers.Registry
	Limiters  *recon.LimiterRegistry
	client    *Client
}

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

// NewCensysSource constructs a CensysSource with the shared retry client.
func NewCensysSource(apiId, apiSecret string, reg *providers.Registry, lim *recon.LimiterRegistry) *CensysSource {
	return &CensysSource{
		APIId:     apiId,
		APISecret: apiSecret,
		BaseURL:   "https://search.censys.io/api",
		Registry:  reg,
		Limiters:  lim,
		client:    NewClient(),
	}
}

func (s *CensysSource) Name() string          { return "censys" }
func (s *CensysSource) RateLimit() rate.Limit { return rate.Every(2500 * time.Millisecond) }
func (s *CensysSource) Burst() int            { return 1 }
func (s *CensysSource) RespectsRobots() bool  { return false }

// Enabled returns true only when both APIId and APISecret are configured.
func (s *CensysSource) Enabled(_ recon.Config) bool {
	return s.APIId != "" && s.APISecret != ""
}

// Sweep issues one POST /v2/hosts/search request per provider keyword and
// emits a Finding for every hit returned.
func (s *CensysSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	if s.APIId == "" || s.APISecret == "" {
		return nil
	}
	base := s.BaseURL
	if base == "" {
		base = "https://search.censys.io/api"
	}

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

		payload, _ := json.Marshal(map[string]any{
			"q":        q,
			"per_page": 25,
		})

		endpoint := fmt.Sprintf("%s/v2/hosts/search", base)
		req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
		if err != nil {
			return fmt.Errorf("censys: build request: %w", err)
		}
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Accept", "application/json")
		req.Header.Set("User-Agent", "keyhunter-recon")
		req.SetBasicAuth(s.APIId, s.APISecret)

		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 censysSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

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

type censysSearchResponse struct {
	Result censysResult `json:"result"`
}

type censysResult struct {
	Hits []censysHit `json:"hits"`
}

type censysHit struct {
	IP       string          `json:"ip"`
	Services []censysService `json:"services"`
}

type censysService struct {
	Port        int    `json:"port"`
	ServiceName string `json:"service_name"`
}

// censysKeywordIndex maps lowercased keywords to provider names.
func censysKeywordIndex(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
}
