package sources

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"

	"golang.org/x/time/rate"

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

// URLhausSource searches the abuse.ch URLhaus API for malicious URLs that
// contain API key patterns. Threat actors often embed stolen API keys in
// malware C2 URLs, phishing pages, and credential-harvesting infrastructure.
// URLhaus is free and unauthenticated — no API key required.
type URLhausSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// urlhausResponse represents the URLhaus API response for tag/payload lookups.
type urlhausResponse struct {
	QueryStatus string         `json:"query_status"`
	URLs        []urlhausEntry `json:"urls"`
}

// urlhausEntry is a single URL record from URLhaus.
type urlhausEntry struct {
	URL       string   `json:"url"`
	URLStatus string   `json:"url_status"`
	Tags      []string `json:"tags"`
	Reporter  string   `json:"reporter"`
}

func (s *URLhausSource) Sweep(ctx context.Context, query string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://urlhaus-api.abuse.ch/v1"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

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

	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
			}
		}

		// Try tag lookup first.
		tagURL := fmt.Sprintf("%s/tag/%s/", base, url.PathEscape(q))
		req, err := http.NewRequestWithContext(ctx, http.MethodPost, tagURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

		resp, err := client.Do(ctx, req)
		if err != nil {
			// Fallback to payload endpoint on tag lookup failure.
			resp, err = s.payloadFallback(ctx, client, base, q)
			if err != nil {
				continue
			}
		}

		data, err := io.ReadAll(io.LimitReader(resp.Body, 512*1024))
		_ = resp.Body.Close()
		if err != nil {
			continue
		}

		var result urlhausResponse
		if err := json.Unmarshal(data, &result); err != nil {
			continue
		}

		// If tag lookup returned no results, try payload fallback.
		if result.QueryStatus != "ok" || len(result.URLs) == 0 {
			resp, err = s.payloadFallback(ctx, client, base, q)
			if err != nil {
				continue
			}

			data, err = io.ReadAll(io.LimitReader(resp.Body, 512*1024))
			_ = resp.Body.Close()
			if err != nil {
				continue
			}

			if err := json.Unmarshal(data, &result); err != nil {
				continue
			}
		}

		for _, entry := range result.URLs {
			// Stringify the record and check for key patterns.
			record := fmt.Sprintf("url=%s status=%s tags=%v reporter=%s",
				entry.URL, entry.URLStatus, entry.Tags, entry.Reporter)
			if ciLogKeyPattern.MatchString(record) || ciLogKeyPattern.MatchString(entry.URL) {
				out <- recon.Finding{
					ProviderName: q,
					Source:       entry.URL,
					SourceType:   "recon:urlhaus",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}

// payloadFallback tries the URLhaus payload endpoint as a secondary search method.
func (s *URLhausSource) payloadFallback(ctx context.Context, client *Client, base, tag string) (*http.Response, error) {
	payloadURL := fmt.Sprintf("%s/payload/", base)
	body := fmt.Sprintf("md5_hash=&sha256_hash=&tag=%s", url.QueryEscape(tag))
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, payloadURL, strings.NewReader(body))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	return client.Do(ctx, req)
}
