package httpc

import (
	"fmt"
	"net/http"
	"strings"
)

const (
	HeaderUserAgent      = "User-Agent"
	HeaderContentType    = "Content-Type"
	HeaderCookie         = "Cookie"
	HeaderAccept         = "Accept"
	HeaderOrigin         = "Origin"
	HeaderReferer        = "Referer"
	HeaderAcceptLanguage = "Accept-Language"
	HeaderAcceptEncoding = "Accept-Encoding"

	ContentTypeJSON = "application/json; charset=utf-8"
)
const (
	MobileUserAgent        = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/124.0.6367.68 MobileRequest/15E148 Safari/604.1"
	PcUserAgent            = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
	AcceptHtml             = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
	AcceptCNLanguage       = "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
	AcceptEncodingIdentity = "identity"
)

func RedirectAllCookies(req *http.Request, via []*http.Request) error {
	_, cookieHeader := GetRedirectCookieHeaders(req, via)
	if cookieHeader != "" {
		req.Header.Set("Cookie", cookieHeader)
	}
	return nil
}

func GetRedirectCookieHeaders(req *http.Request, via []*http.Request) (map[string]string, string) {
	if len(via) == 0 {
		return map[string]string{}, ""
	}

	lastReq := via[len(via)-1]

	cookieMap := parseCookieMap(lastReq.Header.Get("Cookie"))

	for _, c := range lastReq.Cookies() {
		cookieMap[c.Name] = c.Value
	}

	if lastReq.Response != nil {
		for _, c := range lastReq.Response.Cookies() {
			cookieMap[c.Name] = c.Value
		}
	}

	var pairs []string
	for name, value := range cookieMap {
		pairs = append(pairs, fmt.Sprintf("%s=%s", name, value))
	}

	if len(pairs) > 0 {
		// 直接 Set 最终合并后的完整字符串
		return cookieMap, strings.Join(pairs, "; ")
	}

	return map[string]string{}, ""
}

func parseCookieMap(str string) map[string]string {
	res := make(map[string]string)
	if len(str) == 0 {
		return res
	}

	sp := strings.Split(str, ";")

	for _, v := range sp {
		split := strings.SplitN(v, "=", 2)
		if len(split) == 2 {
			name := strings.TrimSpace(split[0])
			value := strings.TrimSpace(split[1])

			if name != "" && value != "" {
				res[name] = value
			}
		}
	}

	return res
}
