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

// NetlasSource implements recon.ReconSource against the Netlas internet
// intelligence API. It iterates provider keyword queries and emits a Finding
// per result item.
//
// A missing API key disables the source without error.
type NetlasSource struct {
	APIKey   string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	client   *Client
}

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

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

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

// Sweep issues one Netlas search request per provider keyword and emits a
// Finding for every result item.
func (s *NetlasSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	if s.APIKey == "" {
		return nil
	}
	if s.client == nil {
		s.client = NewClient()
	}
	base := s.BaseURL
	if base == "" {
		base = "https://app.netlas.io"
	}

	queries := BuildQueries(s.Registry, "netlas")
	kwIndex := netlasKeywordIndex(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/api/responses/?q=%s&start=0&indices=",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("netlas: build request: %w", err)
		}
		req.Header.Set("X-API-Key", s.APIKey)
		req.Header.Set("Accept", "application/json")

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

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

type netlasSearchResponse struct {
	Items []netlasItem `json:"items"`
}

type netlasItem struct {
	Data netlasData `json:"data"`
}

type netlasData struct {
	IP   string `json:"ip"`
	Port int    `json:"port"`
}

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