package richtext

import (
	"strings"
)

const UltidocExtension = "ultidoc.json"

// Config holds rich-text editor integration settings.
type Config struct {
	Enabled           bool
	HocuspocusPublicURL string
	HocuspocusSecret    string
	APIInternalURL      string
	StorageMode         string // sidecar | overwrite
	ExportMirrorFormat  string // "" | docx
}

func normalizePath(p string) string {
	p = strings.TrimSpace(p)
	if p == "" {
		return "/"
	}
	if !strings.HasPrefix(p, "/") {
		p = "/" + p
	}
	return strings.ReplaceAll(p, "//", "/")
}

func fileNameFromPath(p string) string {
	p = normalizePath(p)
	if p == "/" {
		return ""
	}
	if i := strings.LastIndex(p, "/"); i >= 0 {
		return p[i+1:]
	}
	return p
}

func isUltidocPath(path string) bool {
	return strings.HasSuffix(strings.ToLower(path), "."+UltidocExtension)
}

func sidecarPathForSource(sourcePath string) string {
	sourcePath = normalizePath(sourcePath)
	dir := "/"
	name := strings.TrimPrefix(sourcePath, "/")
	if i := strings.LastIndex(name, "/"); i >= 0 {
		dir = "/" + name[:i]
		name = name[i+1:]
	}
	base := name
	if dot := strings.LastIndex(name, "."); dot > 0 {
		base = name[:dot]
	}
	sidecar := base + "." + UltidocExtension
	if dir == "/" {
		return "/" + sidecar
	}
	return dir + "/" + sidecar
}

func parentDir(path string) string {
	path = normalizePath(path)
	if path == "/" {
		return "/"
	}
	idx := strings.LastIndex(path, "/")
	if idx <= 0 {
		return "/"
	}
	return path[:idx]
}
