package forum

import (
	"fmt"
	"sort"
	"strings"
	"time"

	nigiri "git.sharkk.net/Sharkk/Nigiri"
)

// Forum represents a forum post or thread in the game
type Forum struct {
	ID       int    `json:"id"`
	Posted   int64  `json:"posted"`
	LastPost int64  `json:"last_post"`
	Author   int    `json:"author" db:"index"`
	Parent   int    `json:"parent" db:"index"`
	Replies  int    `json:"replies"`
	Title    string `json:"title" db:"required"`
	Content  string `json:"content" db:"required"`
}

// Global store
var store *nigiri.BaseStore[Forum]

// Init sets up the Nigiri store and indices
func Init(collection *nigiri.Collection) {
	store = nigiri.NewBaseStore[Forum]()

	// Register custom indices
	store.RegisterIndex("byParent", nigiri.BuildIntGroupIndex(func(f *Forum) int {
		return f.Parent
	}))

	store.RegisterIndex("byAuthor", nigiri.BuildIntGroupIndex(func(f *Forum) int {
		return f.Author
	}))

	store.RegisterIndex("allByLastPost", nigiri.BuildSortedListIndex(func(a, b *Forum) bool {
		if a.LastPost != b.LastPost {
			return a.LastPost > b.LastPost // DESC
		}
		return a.ID > b.ID // DESC
	}))

	store.RebuildIndices()
}

// GetStore returns the forum store
func GetStore() *nigiri.BaseStore[Forum] {
	if store == nil {
		panic("forum store not initialized - call Initialize first")
	}
	return store
}

// Creates a new Forum with sensible defaults
func New() *Forum {
	now := time.Now().Unix()
	return &Forum{
		Posted:   now,
		LastPost: now,
		Author:   0,
		Parent:   0, // Default to thread (not reply)
		Replies:  0,
		Title:    "",
		Content:  "",
	}
}

// Validate checks if forum has valid values
func (f *Forum) Validate() error {
	if strings.TrimSpace(f.Title) == "" {
		return fmt.Errorf("forum title cannot be empty")
	}
	if strings.TrimSpace(f.Content) == "" {
		return fmt.Errorf("forum content cannot be empty")
	}
	if f.Posted <= 0 {
		return fmt.Errorf("forum Posted timestamp must be positive")
	}
	if f.LastPost <= 0 {
		return fmt.Errorf("forum LastPost timestamp must be positive")
	}
	if f.Parent < 0 {
		return fmt.Errorf("forum Parent cannot be negative")
	}
	if f.Replies < 0 {
		return fmt.Errorf("forum Replies cannot be negative")
	}
	return nil
}

// CRUD operations
func (f *Forum) Save() error {
	if f.ID == 0 {
		id, err := store.Create(f)
		if err != nil {
			return err
		}
		f.ID = id
		return nil
	}
	return store.Update(f.ID, f)
}

func (f *Forum) Delete() error {
	store.Remove(f.ID)
	return nil
}

// Insert with ID assignment
func (f *Forum) Insert() error {
	id, err := store.Create(f)
	if err != nil {
		return err
	}
	f.ID = id
	return nil
}

// Query functions
func Find(id int) (*Forum, error) {
	forum, exists := store.Find(id)
	if !exists {
		return nil, fmt.Errorf("forum post with ID %d not found", id)
	}
	return forum, nil
}

func All() ([]*Forum, error) {
	return store.AllSorted("allByLastPost"), nil
}

func Threads() ([]*Forum, error) {
	return store.FilterByIndex("allByLastPost", func(f *Forum) bool {
		return f.Parent == 0
	}), nil
}

func ByParent(parentID int) ([]*Forum, error) {
	replies := store.GroupByIndex("byParent", parentID)

	// Sort replies chronologically (posted ASC, then ID ASC)
	if parentID > 0 && len(replies) > 1 {
		sort.Slice(replies, func(i, j int) bool {
			if replies[i].Posted != replies[j].Posted {
				return replies[i].Posted < replies[j].Posted // ASC
			}
			return replies[i].ID < replies[j].ID // ASC
		})
	}

	return replies, nil
}

func ByAuthor(authorID int) ([]*Forum, error) {
	posts := store.GroupByIndex("byAuthor", authorID)

	// Sort by posted DESC, then ID DESC
	sort.Slice(posts, func(i, j int) bool {
		if posts[i].Posted != posts[j].Posted {
			return posts[i].Posted > posts[j].Posted // DESC
		}
		return posts[i].ID > posts[j].ID // DESC
	})

	return posts, nil
}

func Recent(limit int) ([]*Forum, error) {
	all := store.AllSorted("allByLastPost")
	if limit > len(all) {
		limit = len(all)
	}
	return all[:limit], nil
}

func Search(term string) ([]*Forum, error) {
	lowerTerm := strings.ToLower(term)
	return store.FilterByIndex("allByLastPost", func(f *Forum) bool {
		return strings.Contains(strings.ToLower(f.Title), lowerTerm) ||
			strings.Contains(strings.ToLower(f.Content), lowerTerm)
	}), nil
}

func Since(since int64) ([]*Forum, error) {
	return store.FilterByIndex("allByLastPost", func(f *Forum) bool {
		return f.LastPost >= since
	}), nil
}

// Helper methods
func (f *Forum) PostedTime() time.Time {
	return time.Unix(f.Posted, 0)
}

func (f *Forum) LastPostTime() time.Time {
	return time.Unix(f.LastPost, 0)
}

func (f *Forum) SetPostedTime(t time.Time) {
	f.Posted = t.Unix()
}

func (f *Forum) SetLastPostTime(t time.Time) {
	f.LastPost = t.Unix()
}

func (f *Forum) IsThread() bool {
	return f.Parent == 0
}

func (f *Forum) IsReply() bool {
	return f.Parent > 0
}

func (f *Forum) HasReplies() bool {
	return f.Replies > 0
}

func (f *Forum) IsRecentActivity() bool {
	return time.Since(f.LastPostTime()) < 24*time.Hour
}

func (f *Forum) ActivityAge() time.Duration {
	return time.Since(f.LastPostTime())
}

func (f *Forum) PostAge() time.Duration {
	return time.Since(f.PostedTime())
}

func (f *Forum) IsAuthor(userID int) bool {
	return f.Author == userID
}

func (f *Forum) Preview(maxLength int) string {
	if len(f.Content) <= maxLength {
		return f.Content
	}

	if maxLength < 3 {
		return f.Content[:maxLength]
	}

	return f.Content[:maxLength-3] + "..."
}

func (f *Forum) WordCount() int {
	if f.Content == "" {
		return 0
	}

	// Simple word count by splitting on whitespace
	words := 0
	inWord := false

	for _, char := range f.Content {
		if char == ' ' || char == '\t' || char == '\n' || char == '\r' {
			if inWord {
				words++
				inWord = false
			}
		} else {
			inWord = true
		}
	}

	if inWord {
		words++
	}

	return words
}

func (f *Forum) Length() int {
	return len(f.Content)
}

func (f *Forum) Contains(term string) bool {
	lowerTerm := strings.ToLower(term)
	return strings.Contains(strings.ToLower(f.Title), lowerTerm) ||
		strings.Contains(strings.ToLower(f.Content), lowerTerm)
}

func (f *Forum) UpdateLastPost() {
	f.LastPost = time.Now().Unix()
}

func (f *Forum) IncrementReplies() {
	f.Replies++
}

func (f *Forum) DecrementReplies() {
	if f.Replies > 0 {
		f.Replies--
	}
}

func (f *Forum) GetReplies() ([]*Forum, error) {
	return ByParent(f.ID)
}

func (f *Forum) GetThread() (*Forum, error) {
	if f.IsThread() {
		return f, nil
	}
	return Find(f.Parent)
}

// Legacy compatibility functions (will be removed later)
func LoadData(dataPath string) error {
	// No longer needed - Nigiri handles this
	return nil
}

func SaveData(dataPath string) error {
	// No longer needed - Nigiri handles this
	return nil
}
