package sources

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

	"golang.org/x/time/rate"

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

// APKMirrorSource searches APKMirror for mobile app metadata (descriptions,
// changelogs, file listings) that may contain leaked API keys. This is a
// metadata scanner -- it does not decompile APKs. Full decompilation via
// apktool/jadx would require local binary dependencies and is out of scope
// for a network-based ReconSource.
type APKMirrorSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

func (s *APKMirrorSource) Sweep(ctx context.Context, query string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://www.apkmirror.com"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

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

		searchURL := fmt.Sprintf(
			"%s/?post_type=app_release&searchtype=apk&s=%s",
			base, url.QueryEscape(q),
		)
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}

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

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

		if ciLogKeyPattern.Match(body) {
			out <- recon.Finding{
				ProviderName: q,
				Source:       searchURL,
				SourceType:   "recon:apkmirror",
				Confidence:   "medium",
				DetectedAt:   time.Now(),
			}
		}
	}
	return nil
}
