package linknorm

import (
	"fmt"
	"strings"

	"vpnclient/internal/config"
	"vpnclient/internal/protocols/hysteria2"
	"vpnclient/internal/protocols/naive"
)

// Normalize normalizes a share/proxy URI for the given protocol (or auto-detect).
func Normalize(proto config.Protocol, raw string) (normalized string, detected config.Protocol, remark string, err error) {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return "", proto, "", fmt.Errorf("пустая ссылка")
	}
	if proto == "" {
		proto = config.DetectProtocol(raw)
	}
	switch proto {
	case config.ProtocolHysteria2:
		u, rem, err := hysteria2.NormalizeShareLink(raw)
		return u, config.ProtocolHysteria2, rem, err
	case config.ProtocolNaive, "":
		u, rem, err := naive.ParseShareLink(raw)
		if err != nil {
			// try hy2 if naive failed and looks like hy
			if hysteria2.Detect(raw) {
				u2, rem2, err2 := hysteria2.NormalizeShareLink(raw)
				return u2, config.ProtocolHysteria2, rem2, err2
			}
			return "", config.ProtocolNaive, "", err
		}
		return u, config.ProtocolNaive, rem, nil
	default:
		return "", proto, "", fmt.Errorf("unsupported protocol %q", proto)
	}
}
