package sources

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

	"golang.org/x/time/rate"

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

// CircleCISource scrapes CircleCI build logs for leaked API keys.
// CircleCI exposes build logs via its API; a personal API token is required
// to access build artifacts and logs. Misconfigured pipelines often leak
// secrets in build output.
type CircleCISource struct {
	Token    string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

func (s *CircleCISource) Name() string         { return "circleci" }
func (s *CircleCISource) RateLimit() rate.Limit { return rate.Every(3 * time.Second) }
func (s *CircleCISource) Burst() int            { return 2 }
func (s *CircleCISource) RespectsRobots() bool  { return false }

// Enabled requires a CircleCI API token.
func (s *CircleCISource) Enabled(_ recon.Config) bool { return s.Token != "" }

// circleciPipelineResponse represents the CircleCI v2 pipeline search result.
type circleciPipelineResponse struct {
	Items []circleciPipeline `json:"items"`
}

type circleciPipeline struct {
	ID     string `json:"id"`
	Number int    `json:"number"`
}

func (s *CircleCISource) Sweep(ctx context.Context, _ string, out chan<- recon.Finding) error {
	base := s.BaseURL
	if base == "" {
		base = "https://circleci.com/api/v2"
	}
	client := s.Client
	if client == nil {
		client = NewClient()
	}

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

		// Search for pipelines by project slug (query is used as slug hint).
		searchURL := fmt.Sprintf("%s/project/gh/%s/pipeline?limit=5", base, q)
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("Circle-Token", s.Token)
		req.Header.Set("Accept", "application/json")

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

		var pipelines circleciPipelineResponse
		if err := json.NewDecoder(resp.Body).Decode(&pipelines); err != nil {
			_ = resp.Body.Close()
			continue
		}
		_ = resp.Body.Close()

		for _, p := range pipelines.Items {
			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
				}
			}

			// Fetch pipeline workflow logs.
			logURL := fmt.Sprintf("%s/pipeline/%s/workflow", base, p.ID)
			logReq, err := http.NewRequestWithContext(ctx, http.MethodGet, logURL, nil)
			if err != nil {
				continue
			}
			logReq.Header.Set("Circle-Token", s.Token)
			logReq.Header.Set("Accept", "text/plain")

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

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

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