package sources

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"regexp"
	"time"

	"golang.org/x/time/rate"

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

// EnvLeakSource probes for publicly accessible .env files on web servers.
// Many web frameworks (Laravel, Rails, Node/Express, Django) use .env files
// for configuration. Misconfigured servers frequently serve these files
// directly, exposing API keys and database credentials.
type EnvLeakSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// envKeyValuePattern matches KEY=VALUE lines typical of .env files.
var envKeyValuePattern = regexp.MustCompile(`(?im)^[A-Z_]*(API[_]?KEY|SECRET|TOKEN|PASSWORD|CREDENTIALS?)[A-Z_]*\s*=\s*\S+`)

// envFilePaths are common locations for exposed .env files.
var envFilePaths = []string{
	"/.env",
	"/.env.local",
	"/.env.production",
	"/.env.development",
	"/.env.backup",
	"/.env.example",
	"/app/.env",
	"/api/.env",
}

func (s *EnvLeakSource) 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, "dotenv")
	if len(queries) == 0 {
		return nil
	}

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

		for _, path := range envFilePaths {
			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 := fmt.Sprintf("%s%s", base, path)
			req, err := http.NewRequestWithContext(ctx, http.MethodGet, probeURL, nil)
			if err != nil {
				continue
			}

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

			body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024)) // 64KB max
			_ = resp.Body.Close()
			if err != nil {
				continue
			}

			if envKeyValuePattern.Match(body) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       probeURL,
					SourceType:   "recon:dotenv",
					Confidence:   "high",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
