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

// ZoomEyeSource implements recon.ReconSource against the ZoomEye /host/search
// API. It iterates provider keyword queries and emits a Finding for every match
// returned (device/service key exposure).
//
// A missing API key disables the source without error.
type ZoomEyeSource struct {
	APIKey   string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	client   *Client
}

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

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

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

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

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

	queries := BuildQueries(s.Registry, "zoomeye")
	kwIndex := zoomeyeKeywordIndex(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/host/search?query=%s&page=1",
			base, url.QueryEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("zoomeye: build request: %w", err)
		}
		req.Header.Set("API-KEY", s.APIKey)
		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 zoomeyeSearchResponse
		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("zoomeye://%s:%d", m.IP, m.PortInfo.Port),
				SourceType:   "recon:zoomeye",
				DetectedAt:   time.Now(),
			}
			select {
			case out <- f:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type zoomeyeSearchResponse struct {
	Matches []zoomeyeMatch `json:"matches"`
}

type zoomeyeMatch struct {
	IP       string          `json:"ip"`
	PortInfo zoomeyePortInfo `json:"portinfo"`
	Banner   string          `json:"banner"`
}

type zoomeyePortInfo struct {
	Port int `json:"port"`
}

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