package l7

import (
	"bytes"
	"strconv"
	"strings"
)

func ParseHttp(payload []byte) (string, string) {
	method, rest, ok := bytes.Cut(payload, space)
	if !ok {
		return "", ""
	}
	if !isHttpMethod(string(method)) {
		return "", ""
	}
	uri, _, ok := bytes.Cut(rest, space)
	if !ok {
		uri = append(uri, []byte("...")...)
	}
	return string(method), string(uri)
}

func ParseHttpHost(payload []byte, isTls bool) (string, string, string, uint16) {
	method, rest, ok := bytes.Cut(payload, space)
	if !ok {
		return "", "", "", 0
	}
	if !isHttpMethod(string(method)) {
		return "", "", "", 0
	}

	uri, rest, ok := bytes.Cut(rest, space)
	if !ok {
		uri = append(uri, []byte("...")...)
	}

	//hostStart := bytes.Index(rest, []byte("Host:")) + len("Host:")
	hostHeader := "Host:"
	hostIdx := bytes.Index(rest, []byte(hostHeader))
	if hostIdx == -1 {
		return string(method), string(uri), "", 0
	}
	hostStart := hostIdx + len(hostHeader)
	hostEnd := bytes.Index(rest[hostStart:], []byte("\r\n"))
	var hostPortBts []byte
	if hostEnd == -1 {
		hostPortBts = rest[hostStart:]
	} else {
		hostPortBts = rest[hostStart : hostStart+hostEnd]
	}
	hostPort := string(bytes.TrimSpace(hostPortBts))
	hostParts := strings.Split(hostPort, ":")
	host := hostParts[0]

	// 根据 TLS 标识设置默认端口
	var port uint16
	if isTls {
		port = 443 // HTTPS 默认端口
	} else {
		port = 80 // HTTP 默认端口
	}

	// 如果 Host 头部明确指定了端口，使用指定的端口
	if len(hostParts) > 1 {
		port64, err := strconv.ParseUint(hostParts[1], 10, 16)
		if err == nil {
			port = uint16(port64)
		}
	}

	return string(method), string(uri), host, port
}
