package server

import (
	"net/http"
	"strings"
)

// IsGlobalRoute reports AGS routes whose contract is not scoped to a AgentTeam
// workspace. Split deployments send these routes to one explicitly configured
// AGS global owner rather than guessing a workspace from an absent identity.
func IsGlobalRoute(method, path string) bool {
	method = strings.ToUpper(strings.TrimSpace(method))
	path = strings.TrimSpace(path)
	if path == "" || path[0] != '/' {
		return false
	}
	if method == http.MethodOptions && (hasPathPrefix(path, "/api/ext/v1") || hasPathPrefix(path, "/api/v3")) {
		return true
	}
	switch method + " " + path {
	case "POST /login/device/code",
		"POST /login/oauth/access_token",
		"GET /login/oauth/authorize",
		"GET /login/device",
		"POST /login/device",
		"GET /auth/connected/login",
		"GET /auth/connected/callback",
		"GET /api/v3",
		"GET /api/v3/",
		"GET /api/v3/openapi.json",
		"GET /api/v3/meta",
		"GET /api/v3/rate_limit",
		"GET /api/ext/v1",
		"GET /api/ext/v1/",
		"GET /api/ext/v1/openapi.json",
		"POST /api/ext/v1/agents",
		"POST /api/ext/v1/analytics/events",
		"POST /api/ext/v1/oauth/device/approve",
		"POST /api/ext/v1/oauth/device/reject",
		"POST /api/ext/v1/oidc/device/code",
		"POST /api/ext/v1/oidc/session",
		"POST /api/ext/v1/oidc/callback",
		"POST /api/ext/v1/oidc/lookup":
		return true
	}
	return method == http.MethodGet && (hasPathPrefix(path, "/avatars") || isPublicStarredLookup(path))
}

func hasPathPrefix(path, prefix string) bool {
	return path == prefix || strings.HasPrefix(path, prefix+"/")
}

func isPublicStarredLookup(path string) bool {
	parts := strings.Split(strings.Trim(path, "/"), "/")
	return len(parts) == 5 && parts[0] == "api" && parts[1] == "v3" &&
		parts[2] == "users" && parts[3] != "" && parts[4] == "starred"
}
