// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"sort"
	"strings"
	"time"

	"github.com/gocolly/colly/v2"
	"golang.org/x/net/html"
)

// Resolve and pin public addresses at dial time, including redirect and sitemap
// requests. The crawler never uses browser credentials or local network proxies.
func newCrawlHTTPClient() *http.Client {
	transport := &http.Transport{ResponseHeaderTimeout: crawlTimeout, TLSHandshakeTimeout: 8 * time.Second}
	transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
		host, port, err := net.SplitHostPort(address)
		if err != nil {
			return nil, err
		}
		ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)
		if err != nil || len(ips) == 0 {
			return nil, fmt.Errorf("alamat website belum dapat ditemukan")
		}
		for _, addr := range ips {
			ip := addr.IP
			if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
				return nil, fmt.Errorf("gunakan alamat website publik")
			}
		}
		var lastErr error
		dialer := &net.Dialer{Timeout: 8 * time.Second}
		for _, addr := range ips {
			conn, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(addr.IP.String(), port))
			if dialErr == nil {
				return conn, nil
			}
			lastErr = dialErr
		}
		return nil, lastErr
	}
	return &http.Client{Timeout: crawlTimeout, Transport: transport, CheckRedirect: crawlRedirect}
}

func crawlRedirect(req *http.Request, via []*http.Request) error {
	if len(via) >= 5 {
		return fmt.Errorf("terlalu banyak pengalihan website")
	}
	if req.URL.User != nil || (req.URL.Scheme != "https" && req.URL.Scheme != "http") {
		return fmt.Errorf("alamat pengalihan tidak valid")
	}
	if len(via) > 0 && canonicalHost(req.URL.Hostname()) != canonicalHost(via[0].URL.Hostname()) {
		return fmt.Errorf("website mengalihkan ke domain lain; gunakan alamat akhirnya")
	}
	return nil
}

type crawlPageSink func(pageURL, title, content string, err error)

// One collector per job shares visited URLs, robots rules, and rate limits.
// A bounded breadth-first queue avoids deep recursive crawls and duplicate pages.
func crawlWebsite(root string, seeds []string, maxPages int, client *http.Client, delay time.Duration, save crawlPageSink) error {
	ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute)
	defer cancel()
	return crawlWebsiteWithRenderer(ctx, root, seeds, maxPages, client, delay, renderCrawlPage, save)
}

func crawlWebsiteWithRenderer(ctx context.Context, root string, seeds []string, maxPages int, client *http.Client, delay time.Duration, render crawlPageRenderer, save crawlPageSink) error {
	base, err := url.Parse(root)
	if err != nil || base.Host == "" || base.User != nil || (base.Scheme != "http" && base.Scheme != "https") {
		return fmt.Errorf("alamat website tidak valid")
	}
	if maxPages <= 0 {
		maxPages = 50
	}
	if maxPages > 200 {
		maxPages = 200
	}
	c := colly.NewCollector(colly.UserAgent(crawlUA), colly.MaxBodySize(maxPageBytes+1))
	c.IgnoreRobotsTxt = false
	c.DetectCharset = true
	c.SetClient(client)
	c.SetRedirectHandler(crawlRedirect)
	c.OnRequest(func(r *colly.Request) {
		if ctx.Err() != nil {
			r.Abort()
		}
	})
	if err := c.Limit(&colly.LimitRule{DomainGlob: "*", Parallelism: 1, Delay: delay}); err != nil {
		return err
	}
	host := canonicalHost(base.Hostname())
	queue := []string{}
	seen := map[string]bool{}
	enqueue := func(raw string) {
		u, err := url.Parse(raw)
		if err != nil || u.User != nil || canonicalHost(u.Hostname()) != host {
			return
		}
		normalized := normalizeURL(raw)
		if normalized == "" || seen[normalized] || shouldSkipURL(normalized) || len(seen) >= 5000 {
			return
		}
		seen[normalized] = true
		queue = append(queue, normalized)
	}
	enqueue(root)
	ordered := append([]string(nil), seeds...)
	sort.SliceStable(ordered, func(i, j int) bool { return crawlSeedPriority(ordered[i]) > crawlSeedPriority(ordered[j]) })
	for _, seed := range ordered {
		enqueue(seed)
	}
	var title, content string
	var pageErr error
	c.OnResponse(func(r *colly.Response) {
		if len(r.Body) > maxPageBytes {
			pageErr = fmt.Errorf("halaman melebihi batas 3 MB")
			return
		}
		if ct := strings.ToLower(r.Headers.Get("Content-Type")); ct != "" && !strings.Contains(ct, "html") {
			pageErr = fmt.Errorf("halaman bukan HTML")
			return
		}
		doc, err := html.Parse(strings.NewReader(string(r.Body)))
		if err != nil {
			pageErr = fmt.Errorf("HTML belum dapat dibaca")
			return
		}
		links := extractLinks(doc, r.Request.URL)
		title, content = extractTitleText(doc)
		if crawlNeedsBrowser(string(r.Body), content) {
			if render == nil {
				pageErr = fmt.Errorf("isi halaman membutuhkan pemuatan JavaScript")
				return
			}
			rendered, err := render(ctx, r.Request.URL.String())
			if err != nil {
				pageErr = err
				return
			}
			renderedURL, err := url.Parse(rendered.URL)
			if err != nil || canonicalHost(renderedURL.Hostname()) != host {
				pageErr = fmt.Errorf("website mengalihkan ke domain lain; gunakan alamat akhirnya")
				return
			}
			doc, err = html.Parse(strings.NewReader(rendered.HTML))
			if err != nil {
				pageErr = fmt.Errorf("isi halaman belum dapat dibaca")
				return
			}
			links = append(links, extractLinks(doc, renderedURL)...)
			title, content = extractTitleText(doc)
		}
		sort.SliceStable(links, func(i, j int) bool { return crawlSeedPriority(links[i]) > crawlSeedPriority(links[j]) })
		for _, link := range links {
			enqueue(link)
		}
		if issue := CrawlContentIssue(content); issue != "" {
			pageErr = fmt.Errorf("%s", issue)
		}
	})
	for visited := 0; len(queue) > 0 && visited < maxPages; visited++ {
		if ctx.Err() != nil {
			return fmt.Errorf("waktu pengambilan website habis; halaman yang sudah terbaca tetap tersimpan")
		}
		target := queue[0]
		queue = queue[1:]
		title, content, pageErr = "", "", nil
		if visitErr := c.Visit(target); visitErr != nil {
			pageErr = visitErr
		}
		save(target, title, content, pageErr)
	}
	return nil
}

func crawlSeedPriority(raw string) int {
	path := strings.ToLower(raw)
	for _, term := range []string{"faq", "contact", "kontak", "about", "tentang", "kebijakan", "syarat", "ketentuan", "retur", "refund", "garansi"} {
		if strings.Contains(path, term) {
			return 2
		}
	}
	for _, term := range []string{"/product/", "/products/", "/produk/", "/product?", "/produk?"} {
		if strings.Contains(path, term) {
			return 1
		}
	}
	return 0
}
