/*
   Copyright 2026 Docker Compose CLI authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package desktop

import (
	"context"
	"net"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"

	"github.com/moby/moby/client"
	"github.com/sirupsen/logrus"

	"github.com/docker/compose/v5/internal/memnet"
)

// ddProxyHost is a sentinel hostname stamped into the proxy URL handed to the
// stdlib transport. It is never resolved on the network: the transport's
// DialContext recognizes it and routes the connection to Docker Desktop's
// proxy socket instead. The .invalid TLD is reserved (RFC 6761) so it can
// never collide with a real registry host.
const ddProxyHost = "docker-desktop-http-proxy.invalid"

// Endpoint returns the Docker Desktop API socket endpoint advertised via the
// engine info labels, or "" when the active engine is not Docker Desktop.
func Endpoint(ctx context.Context, apiClient client.APIClient) (string, error) {
	res, err := apiClient.Info(ctx, client.InfoOptions{})
	if err != nil {
		return "", err
	}
	for _, l := range res.Info.Labels {
		if k, v, ok := strings.Cut(l, "="); ok && k == EngineLabel {
			return v, nil
		}
	}
	return "", nil
}

// httpProxySocketEndpoint derives Docker Desktop's HTTP proxy socket endpoint
// from a Docker Desktop socket endpoint in the same directory. Returns ""
// when the input is not a recognized form or when the derived unix socket
// does not exist (older DD versions or non-DD installs).
//
// On macOS/Linux: unix:///path/to/Data/docker-cli.sock     → unix:///path/to/Data/httpproxy.sock
// On Windows:    npipe://\\.\pipe\docker_cli               → npipe://\\.\pipe\dockerHttpProxy
func httpProxySocketEndpoint(endpoint string) string {
	if sockPath, ok := strings.CutPrefix(endpoint, "unix://"); ok {
		proxyPath := filepath.Join(filepath.Dir(sockPath), "httpproxy.sock")
		if _, err := os.Stat(proxyPath); err != nil {
			return ""
		}
		return "unix://" + proxyPath
	}
	if strings.HasPrefix(endpoint, "npipe://") {
		// Named pipes all live in the same `\\.\pipe\` namespace, so only the
		// trailing pipe name differs. Swap it in place rather than rebuilding
		// the endpoint string: this preserves the engine endpoint's exact
		// prefix (Docker Desktop reports the backslash form
		// `npipe://\\.\pipe\docker_cli`), which winio can dial. Hardcoding
		// `npipe://./pipe/...` instead would yield the relative path
		// `./pipe/dockerHttpProxy`, which fails with "open
		// ./pipe/dockerHttpProxy: The system cannot find the path specified."
		// (docker/compose#13824). LastIndexAny handles both the backslash form
		// above and the forward-slash form `npipe:////./pipe/...`.
		if idx := strings.LastIndexAny(endpoint, `/\`); idx >= 0 {
			return endpoint[:idx+1] + "dockerHttpProxy"
		}
		return ""
	}
	return ""
}

// ProxyTransport returns an http.RoundTripper that routes traffic through
// Docker Desktop's PAC-aware HTTP proxy when DD exposes the proxy socket,
// or nil when no override is needed (callers should use their own default
// transport in that case — for the OCI resolver this means containerd's
// built-in transport). Pass "" for endpoint when DD is not the active
// engine.
//
// Loopback targets (localhost, 127.0.0.0/8, ::1) bypass the proxy and connect
// directly, so `compose publish` to a local/insecure registry behaves like
// `docker push` instead of failing inside the proxy (docker/compose#13824).
// All other registry traffic continues through Docker Desktop's proxy so
// Desktop stays in control of proxy decisions (e.g. enterprise-managed
// proxies); the local process NO_PROXY is deliberately not honored.
//
// When DD is available, the returned transport is a clone of
// http.DefaultTransport with only Proxy and DialContext overridden, so it
// preserves stdlib timeout, pooling, and HTTP/2 defaults.
func ProxyTransport(endpoint string) http.RoundTripper {
	proxyEndpoint := httpProxySocketEndpoint(endpoint)
	if proxyEndpoint == "" {
		logrus.Debug("Docker Desktop HTTP proxy not available; deferring to caller's default transport")
		return nil
	}
	logrus.Debugf("routing OCI traffic through Docker Desktop HTTP proxy at %s", proxyEndpoint)
	// Clone http.DefaultTransport to inherit stdlib timeout, pool, and
	// HTTP/2 defaults. Type-assertion is guarded since a process may have
	// replaced http.DefaultTransport with a wrapping RoundTripper (e.g.
	// instrumentation libraries); fall back to a fresh transport in that
	// case rather than panicking.
	var tr *http.Transport
	if defaultTr, ok := http.DefaultTransport.(*http.Transport); ok {
		tr = defaultTr.Clone()
	} else {
		tr = &http.Transport{}
	}

	tr.Proxy = ddProxyFunc()

	// Bypassed (direct) requests reach DialContext with their real target
	// address and use the standard dialer; proxied requests reach it with the
	// sentinel proxy address and are routed to the Docker Desktop socket.
	baseDial := tr.DialContext
	if baseDial == nil {
		baseDial = (&net.Dialer{}).DialContext
	}
	proxyAddr := net.JoinHostPort(ddProxyHost, "80")
	tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
		if addr == proxyAddr {
			return memnet.DialEndpoint(ctx, proxyEndpoint)
		}
		return baseDial(ctx, network, addr)
	}
	return tr
}

// ddProxyFunc returns a transport Proxy function that routes every request
// through the Docker Desktop proxy except loopback targets, which connect
// directly. Loopback is the only local bypass: all other registry traffic is
// left to Docker Desktop's PAC-aware proxy so Desktop stays in control of
// proxy decisions. In particular this does not honor the local process
// NO_PROXY/no_proxy, which could otherwise let a broad value (such as "*" or
// ".corp") bypass centrally managed enterprise proxy policy
// (docker/compose#13825 review). The sentinel proxy URL resolves to
// ddProxyHost, which DialContext intercepts.
func ddProxyFunc() func(*http.Request) (*url.URL, error) {
	proxyURL := &url.URL{Scheme: "http", Host: ddProxyHost}
	return func(req *http.Request) (*url.URL, error) {
		if isLoopbackHost(req.URL.Hostname()) {
			return nil, nil
		}
		return proxyURL, nil
	}
}

// isLoopbackHost reports whether host is the loopback name "localhost" or any
// loopback IP (127.0.0.0/8, ::1). host must be a bare hostname with no port,
// e.g. the result of url.URL.Hostname.
func isLoopbackHost(host string) bool {
	if strings.EqualFold(host, "localhost") {
		return true
	}
	if ip := net.ParseIP(host); ip != nil {
		return ip.IsLoopback()
	}
	return false
}

// ProxyTransportFor discovers the Docker Desktop endpoint via apiClient and
// returns the matching transport, or nil when DD is not active or discovery
// fails (so callers fall back to their own default transport).
func ProxyTransportFor(ctx context.Context, apiClient client.APIClient) http.RoundTripper {
	endpoint, err := Endpoint(ctx, apiClient)
	if err != nil {
		logrus.Debugf("could not detect Docker Desktop endpoint, deferring to caller's default transport: %v", err)
		return nil
	}
	return ProxyTransport(endpoint)
}
