// Package treepath provides message tree traversal operations.
//
// v0.29.0: Delegates to store.MessageStore. The package exists only for
// backward compatibility with handler aliases in tree.go. New code should
// call stores.Messages.* directly. This package will be deleted once all
// callers are migrated.
package treepath

import (
	"context"
	"encoding/json"

	"chat-switchboard/store"
)

// Stores is set at startup by main.go. All tree operations delegate here.
// If nil, functions panic — there is no fallback to raw SQL.
var Stores *store.Stores

// ── Type Aliases ────────────────────────────
// Existing consumers reference these types. They're now aliases into the
// store package where the canonical definitions live.

type PathMessage = store.PathMessage
type SiblingInfo = store.SiblingInfo

// ── Public Functions ────────────────────────
// Same signatures as before. All delegate to store methods.

func GetActiveLeaf(channelID, userID string) (*string, error) {
	return Stores.Messages.GetActiveLeaf(context.Background(), channelID, userID)
}

func GetActivePath(channelID, userID string) ([]PathMessage, error) {
	return Stores.Messages.GetActivePath(context.Background(), channelID, userID)
}

func GetPathToLeaf(channelID, leafID string) ([]PathMessage, error) {
	return Stores.Messages.GetPathToLeaf(context.Background(), channelID, leafID)
}

func GetSiblingCount(channelID string, parentID *string) int {
	count, _ := Stores.Messages.GetSiblingCount(context.Background(), channelID, parentID)
	return count
}

func GetSiblings(messageID string) ([]SiblingInfo, int, error) {
	return Stores.Messages.GetSiblingsList(context.Background(), messageID)
}

func FindLeafFromMessage(messageID string) (string, error) {
	return Stores.Messages.FindLeafFromMessage(context.Background(), messageID)
}

func UpdateCursor(channelID, userID, messageID string) error {
	return Stores.Channels.SetCursor(context.Background(), channelID, userID, messageID)
}

func NextSiblingIndex(channelID string, parentID *string) int {
	idx, _ := Stores.Messages.NextSiblingIndexForParent(context.Background(), channelID, parentID)
	return idx
}

// IsSummaryMessage checks if a PathMessage has summary metadata.
func IsSummaryMessage(m *PathMessage) bool {
	if m.Metadata == nil {
		return false
	}
	var meta map[string]interface{}
	if err := json.Unmarshal(*m.Metadata, &meta); err != nil {
		return false
	}
	t, _ := meta["type"].(string)
	return t == "summary"
}
