package sources

import (
	"context"
	"encoding/base64"
	"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"
)

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

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

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

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

// Sweep issues one FOFA search request per provider keyword and emits a
// Finding for every result row.
func (s *FOFASource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	if s.Email == "" || s.APIKey == "" {
		return nil
	}
	if s.client == nil {
		s.client = NewClient()
	}
	base := s.BaseURL
	if base == "" {
		base = "https://fofa.info"
	}

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

		qb64 := base64.StdEncoding.EncodeToString([]byte(q))
		endpoint := fmt.Sprintf("%s/api/v1/search/all?email=%s&key=%s&qbase64=%s&size=100",
			base, s.Email, s.APIKey, qb64)
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
		if err != nil {
			return fmt.Errorf("fofa: build request: %w", err)
		}
		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 fofaSearchResponse
		decErr := json.NewDecoder(resp.Body).Decode(&parsed)
		_ = resp.Body.Close()
		if decErr != nil {
			continue
		}

		provName := kwIndex[strings.ToLower(q)]
		for _, row := range parsed.Results {
			// Each row is [host, ip, port].
			if len(row) < 3 {
				continue
			}
			f := recon.Finding{
				ProviderName: provName,
				Confidence:   "low",
				Source:       fmt.Sprintf("fofa://%s:%s", row[1], row[2]),
				SourceType:   "recon:fofa",
				DetectedAt:   time.Now(),
			}
			select {
			case out <- f:
			case <-ctx.Done():
				return ctx.Err()
			}
		}
	}
	return nil
}

type fofaSearchResponse struct {
	Results [][]string `json:"results"`
	Size    int        `json:"size"`
}

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