package xray

import (
	"context"
	"crypto/tls"
	"errors"
	"io"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
	"unicode/utf8"

	xrayNet "github.com/xtls/xray-core/common/net"
	"github.com/xtls/xray-core/common/session"
	"github.com/xtls/xray-core/core"
	"github.com/xtls/xray-core/features/outbound"
)

const managedProbeMaxBody = 128

// ManagedProbeResult confirms an HTTPS response through the requested existing
// outbound only. The application must validate its endpoint's response body.
// It does not prove capture of operating-system traffic or the TUN/DNS path.
type ManagedProbeResult struct {
	Status     string `json:"status"`
	HTTPStatus int    `json:"httpStatus,omitempty"`
	Body       string `json:"body,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

func ProbeManagedConnectivity(outboundTag, targetURL string, timeoutMilliseconds int) (ManagedProbeResult, error) {
	return probeManagedConnectivity(outboundTag, targetURL, timeoutMilliseconds, nil)
}

// tlsConfig is private and used by local HTTPS tests to trust their fixture CA.
// Public callers always use system certificate roots and hostname validation.
func probeManagedConnectivity(outboundTag, targetURL string, timeoutMilliseconds int, tlsConfig *tls.Config) (ManagedProbeResult, error) {
	target, err := url.Parse(targetURL)
	if err != nil || len(targetURL) > 2048 || target.Scheme != "https" || target.Hostname() == "" || target.User != nil || target.Fragment != "" || target.Opaque != "" {
		return ManagedProbeResult{}, errors.New("managed probe requires an absolute HTTPS URL without user info or fragment")
	}
	if strings.TrimSpace(outboundTag) != outboundTag || outboundTag == "" || len(outboundTag) > 128 {
		return ManagedProbeResult{}, errors.New("managed probe requires an existing outbound tag")
	}
	if timeoutMilliseconds == 0 {
		timeoutMilliseconds = 7000
	}
	if timeoutMilliseconds < 100 || timeoutMilliseconds > 7000 {
		return ManagedProbeResult{}, errors.New("managed probe timeout must be between 100 and 7000 milliseconds")
	}

	coreServerMu.Lock()
	server, lifetime := coreServer, coreProbeContext
	if server == nil || lifetime == nil || lifetime.Err() != nil {
		coreServerMu.Unlock()
		return ManagedProbeResult{Status: "unavailable", Reason: "inactive"}, nil
	}
	manager, ok := server.GetFeature(outbound.ManagerType()).(outbound.Manager)
	if !ok || manager.GetHandler(outboundTag) == nil {
		coreServerMu.Unlock()
		return ManagedProbeResult{Status: "unavailable", Reason: "missing_outbound"}, nil
	}
	coreServerMu.Unlock()

	ctx, cancel := context.WithTimeout(lifetime, time.Duration(timeoutMilliseconds)*time.Millisecond)
	defer cancel()
	result := managedProbeHTTPS(ctx, server, outboundTag, targetURL, tlsConfig)
	coreServerMu.Lock()
	stale := server != coreServer || lifetime.Err() != nil
	coreServerMu.Unlock()
	if stale {
		return ManagedProbeResult{Status: "unavailable", Reason: "stopped"}, nil
	}
	return result, nil
}

func managedProbeHTTPS(ctx context.Context, server *core.Instance, outboundTag, targetURL string, tlsConfig *tls.Config) ManagedProbeResult {
	transport := &http.Transport{
		Proxy:                  nil,
		DisableKeepAlives:      true,
		DisableCompression:     true,
		TLSClientConfig:        tlsConfig,
		MaxResponseHeaderBytes: 4096,
		DialContext: func(dialCtx context.Context, network, address string) (net.Conn, error) {
			if network != "tcp" && network != "tcp4" && network != "tcp6" {
				return nil, errors.New("unsupported probe network")
			}
			destination, err := xrayNet.ParseDestination("tcp:" + address)
			if err != nil {
				return nil, err
			}
			if err := ctx.Err(); err != nil {
				return nil, err
			}
			// http.Transport can detach a dial from request cancellation. Keep the
			// managed lifetime/deadline on the core dispatch and explicitly close
			// its virtual connection when this request expires or the core stops.
			forced := session.SetForcedOutboundTagToContext(ctx, outboundTag)
			connection, err := core.Dial(forced, server, destination)
			if err != nil {
				return nil, err
			}
			stop := context.AfterFunc(ctx, func() { _ = connection.Close() })
			return &managedProbeConn{Conn: connection, stop: stop}, nil
		},
	}
	defer transport.CloseIdleConnections()
	client := &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
	request, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
	if err != nil {
		return ManagedProbeResult{Status: "failed", Reason: "request"}
	}
	request.Header.Set("Cache-Control", "no-cache")
	response, err := client.Do(request)
	if err != nil {
		reason := "tls_or_transport"
		if errors.Is(ctx.Err(), context.DeadlineExceeded) {
			reason = "timeout"
		}
		return ManagedProbeResult{Status: "failed", Reason: reason}
	}
	defer response.Body.Close()
	if response.StatusCode >= 300 && response.StatusCode <= 399 {
		return ManagedProbeResult{Status: "failed", HTTPStatus: response.StatusCode, Reason: "redirect"}
	}
	body, err := io.ReadAll(io.LimitReader(response.Body, managedProbeMaxBody+1))
	if err != nil {
		reason := "read"
		if errors.Is(ctx.Err(), context.DeadlineExceeded) {
			reason = "timeout"
		}
		return ManagedProbeResult{Status: "failed", Reason: reason}
	}
	if len(body) > managedProbeMaxBody {
		return ManagedProbeResult{Status: "failed", Reason: "response_too_large"}
	}
	if !utf8.Valid(body) {
		return ManagedProbeResult{Status: "failed", Reason: "invalid_text"}
	}
	if ctx.Err() != nil {
		return ManagedProbeResult{Status: "failed", Reason: "timeout"}
	}
	return ManagedProbeResult{Status: "response", HTTPStatus: response.StatusCode, Body: string(body)}
}

type managedProbeConn struct {
	net.Conn
	stop func() bool
}

func (connection *managedProbeConn) Close() error {
	connection.stop()
	return connection.Conn.Close()
}
