package threadsapi

import (
	"regexp"
	"strings"
)

// profileAuthorRE captures the @<username> segment of a Threads permalink.
// Examples:
//
//	https://www.threads.com/@some.user/post/CfXyZ123
//	https://www.threads.net/@some.user/p/CfXyZ123
var profileAuthorRE = regexp.MustCompile(`(?i)threads\.(?:com|net)/@([a-zA-Z0-9._]+)`)

// ProfileURLFromPermalink derives the author's profile root URL from a Threads
// post permalink. Falls back to https://www.threads.com/@<username> when the
// permalink does not contain an @<username> segment. Prefer threads.com over
// threads.net because the .com host is the current canonical domain.
func ProfileURLFromPermalink(permalink, username string) string {
	username = strings.TrimSpace(username)
	if permalink != "" {
		if match := profileAuthorRE.FindStringSubmatch(permalink); len(match) >= 2 {
			return "https://www.threads.com/@" + match[1]
		}
	}
	if username == "" {
		return ""
	}
	return "https://www.threads.com/@" + username
}
