package outbound

import (
	"context"
	"crypto/sha256"
	"crypto/x509"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	urlpkg "net/url"
	"sync"
	"syscall"
	"time"

	"github.com/sagernet/sing-box/log"

	"github.com/sagernet/sing-box/adapter"
	"github.com/sagernet/sing-box/common/hiddify/ipinfo"
	"github.com/sagernet/sing-box/common/urltest"
	C "github.com/sagernet/sing-box/constant"
	"github.com/sagernet/sing/common/batch"
)

func urltestTimeout(ctx context.Context, logger log.Logger, realTag string, outbound adapter.Outbound, url string, history *urltest.HistoryStorage, timeout time.Duration) *urltest.History {
	testCtx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()
	started := time.Now()
	effectiveTimeout := timeout
	if deadline, ok := testCtx.Deadline(); ok {
		effectiveTimeout = time.Until(deadline)
	}
	previous := history.LoadURLTestHistory(realTag)
	t, err := urltest.URLTest(testCtx, url, outbound)
	actual := url
	if actual == "" {
		actual = "https://www.gstatic.com/generate_204"
	}
	reason := "none"
	if err != nil {
		reason = "native_error"
		var dns *net.DNSError
		var unknownCA x509.UnknownAuthorityError
		var hostname x509.HostnameError
		var network net.Error
		switch {
		case errors.Is(err, context.DeadlineExceeded):
			reason = "timeout"
		case errors.Is(err, context.Canceled):
			reason = "canceled"
		case errors.Is(err, syscall.ECONNREFUSED):
			reason = "refused"
		case errors.As(err, &dns):
			reason = "dns"
		case errors.As(err, &unknownCA), errors.As(err, &hostname):
			reason = "tls_trust"
		case errors.As(err, &network) && network.Timeout():
			reason = "timeout"
		}
	} else if t == 0 {
		reason = "zero_delay"
	}
	safeTarget := func(raw string) any {
		parsed, parseErr := urlpkg.Parse(raw)
		if parseErr == nil && parsed.User == nil && parsed.RawQuery == "" && parsed.Fragment == "" {
			switch parsed.Hostname() {
			case "captive.apple.com", "www.gstatic.com", "connectivitycheck.gstatic.com", "cp.cloudflare.com", "google.com":
				switch parsed.Path {
				case "", "/", "/generate_204", "/hotspot-detect.html":
					return map[string]any{"scheme": parsed.Scheme, "host": parsed.Host, "path": parsed.Path}
				}
			}
		}
		return map[string]any{"ref": fmt.Sprintf("%x", sha256.Sum256([]byte(raw))), "redacted": true}
	}
	event := map[string]any{"stage": "native_urltest", "configured_target": safeTarget(url), "actual_target": safeTarget(actual),
		"outbound_ref": fmt.Sprintf("%x", sha256.Sum256([]byte(realTag))), "outbound_kind": outbound.Type(),
		"elapsed_ms": time.Since(started).Milliseconds(), "timeout_ms": timeout.Milliseconds(), "effective_timeout_ms": effectiveTimeout.Milliseconds(), "delay_ms": t,
		"result": err == nil && t > 0, "error_code": reason, "at": time.Now().UTC().Format(time.RFC3339Nano)}
	event["stored_delay_ms"] = t
	if err != nil || t == 0 {
		event["stored_delay_ms"] = TimeoutDelay
	}
	if previous != nil {
		event["previous_history"] = map[string]any{"delay_ms": previous.Delay, "at": previous.Time.UTC().Format(time.RFC3339Nano)}
	}
	event["selected_outbound_ref"] = event["outbound_ref"]
	diagnosticMu.RLock()
	event["effective_logger_level"] = diagnosticLevel
	sink := diagnosticSink
	diagnosticMu.RUnlock()
	encoded, _ := json.Marshal(event)
	if sink != nil {
		sink(encoded)
	}
	logger.Info("VOLNY_CHECK ", string(encoded))
	if err != nil || t == 0 {
		t = TimeoutDelay
	}

	his := history.StoreURLTestHistory(realTag, &urltest.History{
		Time:  time.Now(),
		Delay: t,
	})
	logger.Debug("outbound new ping ", realTag, " = ", his.Delay)
	return his
}

func CheckOutbound(logger log.Logger, ctx context.Context, history *urltest.HistoryStorage, router adapter.Router, url string, outbound adapter.Outbound, ipbatch *batch.Batch[string]) uint16 {
	realTag := RealTag(outbound)
	hisbefore := history.LoadURLTestHistory(realTag)
	timeout := C.TCPTimeout
	isTimeoutBefore := isTimeout(hisbefore)

	if !isTimeoutBefore {
		timeout = time.Duration(max(200, hisbefore.Delay)) * time.Millisecond * 4
		logger.Debug("outbound is already connected ", realTag, " = ", hisbefore.Delay, " set timeout for new urltest to ", timeout)
	}
	his := urltestTimeout(ctx, logger, realTag, outbound, url, history, timeout)

	if outbound.Type() == C.TypeWireGuard && his.Delay > 1000 { // double check for wireguard
		his = urltestTimeout(ctx, logger, realTag, outbound, url, history, timeout)
	}
	if isTimeout(his) && !isTimeoutBefore {
		his = urltestTimeout(ctx, logger, realTag, outbound, url, history, C.TCPTimeout)
	}

	if !isTimeout(his) && his.IpInfo == nil {
		if ipbatch == nil {
			go CheckIP(logger, ctx, history, router, outbound)
		} else {
			ipbatch.Go(realTag+"ip", func() (string, error) {
				CheckIP(logger, ctx, history, router, outbound)
				return "", nil
			})
		}
	}

	return his.Delay
}

func CheckIP(logger log.Logger, ctx context.Context, history *urltest.HistoryStorage, router adapter.Router, outbound adapter.Outbound) {
	if outbound == nil {
		return
	}
	if history == nil {
		return
	}
	realTag := RealTag(outbound)
	detour, loaded := router.Outbound(realTag)
	if !loaded {
		return
	}
	his := history.LoadURLTestHistory(realTag)
	if isTimeout(his) {
		return
	}
	if his.IpInfo != nil {
		// logger.Debug("ip already calculated ", fmt.Sprint(his.IpInfo))
		return
	}
	newip, t, err := ipinfo.GetIpInfo(logger, ctx, detour)
	if err != nil {
		// g.logger.Debug("outbound ", realTag, " IP unavailable (", t, "ms): ", err)
		// g.history.AddOnlyIpToHistory(realTag, &urltest.History{
		// 	Time:   time.Now(),
		// 	Delay:  TimeoutDelay,
		// 	IpInfo: &ipinfo.IpInfo{},
		// })
		return
	}
	// g.logger.Trace("outbound ", realTag, " IP ", fmt.Sprint(newip), " (", t, "ms): ", err)
	history.AddOnlyIpToHistory(realTag, &urltest.History{
		Time:   time.Now(),
		Delay:  t,
		IpInfo: newip,
	})
}

// SetURLTestDiagnosticSink is opt-in and accepts only already-redacted events.
// It does not change the normal logger threshold or URLTest results.
var diagnosticMu sync.RWMutex
var diagnosticSink func([]byte)
var diagnosticLevel string

func SetURLTestDiagnosticSink(sink func([]byte), effectiveLevel string) {
	diagnosticMu.Lock()
	diagnosticSink, diagnosticLevel = sink, effectiveLevel
	diagnosticMu.Unlock()
}
