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"
)

// GitHubActionsSource searches GitHub Actions workflow run logs for leaked API
// keys. Workflow logs are public for public repositories and frequently contain
// accidentally printed secrets, debug output with credentials, or insecure
// echo statements that expose environment variables.
type GitHubActionsSource struct {
	Token    string
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// Enabled requires a GitHub token (reuses GitHubToken from SourcesConfig).
func (s *GitHubActionsSource) Enabled(_ recon.Config) bool { return s.Token != "" }

// ghActionsRunsResponse represents the GitHub Actions workflow runs list.
type ghActionsRunsResponse struct {
	WorkflowRuns []ghActionsRun `json:"workflow_runs"`
}

type ghActionsRun struct {
	ID         int64  `json:"id"`
	LogsURL    string `json:"logs_url"`
	HTMLURL    string `json:"html_url"`
	Status     string `json:"status"`
	Conclusion string `json:"conclusion"`
}

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

	queries := BuildQueries(s.Registry, "ghactions")
	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 workflow runs via the Actions API.
		searchURL := fmt.Sprintf("%s/search/code?q=%s+path:.github/workflows", base, q)
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("Authorization", "Bearer "+s.Token)
		req.Header.Set("Accept", "application/vnd.github.v3+json")

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

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

		for _, run := range runs.WorkflowRuns {
			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 log content.
			logURL := fmt.Sprintf("%s/actions/runs/%d/logs", base, run.ID)
			logReq, err := http.NewRequestWithContext(ctx, http.MethodGet, logURL, nil)
			if err != nil {
				continue
			}
			logReq.Header.Set("Authorization", "Bearer "+s.Token)
			logReq.Header.Set("Accept", "application/vnd.github.v3+json")

			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:ghactions",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
