package sources

import (
	"context"
	"encoding/json"
	"net/http"
	"regexp"
	"time"

	"golang.org/x/time/rate"

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

// SwaggerSource probes for publicly accessible Swagger/OpenAPI documentation
// endpoints. Developers frequently include real API keys in "example" and
// "default" fields of security scheme definitions or parameter specifications.
type SwaggerSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

var _ recon.ReconSource = (*SwaggerSource)(nil)

func (s *SwaggerSource) Name() string              { return "swagger" }
func (s *SwaggerSource) RateLimit() rate.Limit      { return rate.Every(3 * time.Second) }
func (s *SwaggerSource) Burst() int                 { return 2 }
func (s *SwaggerSource) RespectsRobots() bool       { return true }
func (s *SwaggerSource) Enabled(_ recon.Config) bool { return true }

// swaggerDocPaths are common locations for Swagger/OpenAPI documentation.
var swaggerDocPaths = []string{
	"/swagger.json",
	"/openapi.json",
	"/api-docs",
	"/v2/api-docs",
	"/swagger/v1/swagger.json",
	"/docs/openapi.json",
}

// swaggerKeyPattern matches potential API keys in example/default fields of
// Swagger JSON. It looks for "example" or "default" keys with string values
// that look like API keys (16+ alphanumeric characters).
var swaggerKeyPattern = regexp.MustCompile(`"(?:example|default)"\s*:\s*"([a-zA-Z0-9_\-]{16,})"`)

func (s *SwaggerSource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		return nil
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

	queries := BuildQueries(s.Registry, "swagger")
	if len(queries) == 0 {
		return nil
	}

	for _, q := range queries {
		if err := ctx.Err(); err != nil {
			return err
		}

		for _, path := range swaggerDocPaths {
			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
				}
			}

			probeURL := base + path
			req, err := http.NewRequestWithContext(ctx, http.MethodGet, probeURL, nil)
			if err != nil {
				continue
			}
			req.Header.Set("Accept", "application/json")

			resp, err := client.Do(ctx, req)
			if err != nil {
				continue
			}

			// Try to parse as JSON to verify it's a valid Swagger doc.
			var doc map[string]interface{}
			if err := json.NewDecoder(resp.Body).Decode(&doc); err != nil {
				_ = resp.Body.Close()
				continue
			}
			_ = resp.Body.Close()

			// Re-marshal to search for example/default fields with key patterns.
			raw, err := json.Marshal(doc)
			if err != nil {
				continue
			}

			if swaggerKeyPattern.Match(raw) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       probeURL,
					SourceType:   "recon:swagger",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
