package sources

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

	"golang.org/x/time/rate"

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

// ConfluenceSource searches publicly exposed Confluence wikis for leaked API
// keys. Many Confluence instances are misconfigured to allow anonymous access
// and their REST API exposes page content including credentials pasted into
// documentation.
type ConfluenceSource struct {
	BaseURL  string
	Registry *providers.Registry
	Limiters *recon.LimiterRegistry
	Client   *Client
}

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

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

// confluenceSearchResponse represents the Confluence REST API content search response.
type confluenceSearchResponse struct {
	Results []confluenceResult `json:"results"`
}

type confluenceResult struct {
	ID    string          `json:"id"`
	Title string          `json:"title"`
	Body  confluenceBody  `json:"body"`
	Links confluenceLinks `json:"_links"`
}

type confluenceBody struct {
	Storage confluenceStorage `json:"storage"`
}

type confluenceStorage struct {
	Value string `json:"value"`
}

type confluenceLinks struct {
	WebUI string `json:"webui"`
}

// htmlTagPattern strips HTML tags to extract text content from Confluence storage format.
var htmlTagPattern = regexp.MustCompile(`<[^>]*>`)

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

	queries := BuildQueries(s.Registry, "confluence")
	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 Confluence via CQL (Confluence Query Language).
		searchURL := fmt.Sprintf("%s/rest/api/content/search?cql=%s&limit=10&expand=body.storage",
			base, url.QueryEscape(fmt.Sprintf(`text~"%s"`, q)))
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
		if err != nil {
			continue
		}
		req.Header.Set("Accept", "application/json")

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

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

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

		for _, page := range result.Results {
			// Strip HTML tags to get plain text for key matching.
			plainText := htmlTagPattern.ReplaceAllString(page.Body.Storage.Value, " ")

			if ciLogKeyPattern.MatchString(plainText) {
				pageURL := fmt.Sprintf("%s%s", base, page.Links.WebUI)
				out <- recon.Finding{
					ProviderName: q,
					Source:       pageURL,
					SourceType:   "recon:confluence",
					Confidence:   "medium",
					DetectedAt:   time.Now(),
				}
			}
		}
	}
	return nil
}
