package search

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

	"gorm.io/gorm"
	"senlinai-agent/backend/internal/models"
)

type Service struct {
	db *gorm.DB
}

const (
	maxSearchResults      = 50
	maxSearchSnippetRunes = 240
)

type rankedSearchResult struct {
	result    SearchResultDTO
	updatedAt time.Time
}

// SearchResultDTO 是搜索接口的稳定结果，所有关联均使用公开 identity。
type SearchResultDTO struct {
	Type      string `json:"type"`
	ID        string `json:"id"`
	ProjectID string `json:"projectId"`
	Title     string `json:"title"`
	Snippet   string `json:"snippet"`
}

func NewService(databases ...*gorm.DB) *Service {
	var database *gorm.DB
	if len(databases) > 0 {
		database = databases[0]
	}
	return &Service{db: database}
}

func (s *Service) database() *gorm.DB {
	if s.db != nil {
		return s.db
	}
	return models.DBService
}

func (s *Service) Search(userID uint, query string) ([]SearchResultDTO, error) {
	query = strings.TrimSpace(query)
	if query == "" {
		return []SearchResultDTO{}, nil
	}

	like := containsPattern(query)
	operator := "LIKE"
	if s.database().Dialector.Name() == "postgres" {
		operator = "ILIKE"
	}

	var projects []models.SenlinAgentProject
	projectFilter := fmt.Sprintf("owner_id = ? AND (name %s ? ESCAPE '!' OR description %s ? ESCAPE '!')", operator, operator)
	if err := s.database().Where(projectFilter, userID, like, like).
		Order("updated_at DESC").Order("identity ASC").
		Limit(maxSearchResults).Find(&projects).Error; err != nil {
		return nil, err
	}
	projectResults := make([]rankedSearchResult, 0, len(projects))
	for _, project := range projects {
		projectResults = append(projectResults, rankedSearchResult{
			result:    SearchResultDTO{Type: "project", ID: project.Identity, ProjectID: project.Identity, Title: project.Name, Snippet: project.Description},
			updatedAt: project.UpdatedAt,
		})
	}

	var tasks []models.SenlinAgentTask
	taskFilter := fmt.Sprintf("(senlin_agent_projects.owner_id = ? OR senlin_agent_tasks.assignee_id = ?) AND (senlin_agent_tasks.title %s ? ESCAPE '!' OR senlin_agent_tasks.description %s ? ESCAPE '!')", operator, operator)
	if err := s.database().Select("senlin_agent_tasks.*").Joins("JOIN senlin_agent_projects ON senlin_agent_projects.id = senlin_agent_tasks.project_id").
		Where(taskFilter, userID, userID, like, like).
		Order("senlin_agent_tasks.updated_at DESC").Order("senlin_agent_tasks.identity ASC").
		Limit(maxSearchResults).
		Find(&tasks).Error; err != nil {
		return nil, err
	}
	taskResults := make([]rankedSearchResult, 0, len(tasks))
	for _, task := range tasks {
		taskResults = append(taskResults, rankedSearchResult{
			result:    SearchResultDTO{Type: "task", ID: task.Identity, ProjectID: task.ProjectIdentity, Title: task.Title, Snippet: task.Description},
			updatedAt: task.UpdatedAt,
		})
	}

	var notes []models.SenlinAgentNote
	noteFilter := fmt.Sprintf(`(senlin_agent_projects.owner_id = ? OR EXISTS (
			SELECT 1 FROM senlin_agent_task_shares
			JOIN senlin_agent_tasks ON senlin_agent_tasks.id = senlin_agent_task_shares.task_id
			WHERE senlin_agent_task_shares.object_type = 'note'
			  AND senlin_agent_task_shares.object_id = senlin_agent_notes.id
			  AND senlin_agent_tasks.project_id = senlin_agent_notes.project_id
			  AND senlin_agent_tasks.assignee_id = ?
		)) AND (senlin_agent_notes.title %s ? ESCAPE '!' OR senlin_agent_notes.markdown %s ? ESCAPE '!')`, operator, operator)
	if err := s.database().Select("senlin_agent_notes.*").Joins("JOIN senlin_agent_projects ON senlin_agent_projects.id = senlin_agent_notes.project_id").
		Where(noteFilter, userID, userID, like, like).
		Order("senlin_agent_notes.updated_at DESC").Order("senlin_agent_notes.identity ASC").
		Limit(maxSearchResults).
		Find(&notes).Error; err != nil {
		return nil, err
	}
	noteResults := make([]rankedSearchResult, 0, len(notes))
	for _, note := range notes {
		noteResults = append(noteResults, rankedSearchResult{
			result:    SearchResultDTO{Type: "note", ID: note.Identity, ProjectID: note.ProjectIdentity, Title: note.Title, Snippet: note.Markdown},
			updatedAt: note.UpdatedAt,
		})
	}

	return stableFairLimit(projectResults, taskResults, noteResults), nil
}

func stableFairLimit(buckets ...[]rankedSearchResult) []SearchResultDTO {
	for _, bucket := range buckets {
		sort.Slice(bucket, func(left, right int) bool {
			if bucket[left].updatedAt.Equal(bucket[right].updatedAt) {
				return bucket[left].result.ID < bucket[right].result.ID
			}
			return bucket[left].updatedAt.After(bucket[right].updatedAt)
		})
	}

	results := make([]SearchResultDTO, 0, maxSearchResults)
	for position := 0; len(results) < maxSearchResults; position++ {
		added := false
		for _, bucket := range buckets {
			if position >= len(bucket) {
				continue
			}
			result := bucket[position].result
			result.Snippet = boundedSnippet(result.Snippet)
			results = append(results, result)
			added = true
			if len(results) == maxSearchResults {
				return results
			}
		}
		if !added {
			return results
		}
	}
	return results
}

func boundedSnippet(value string) string {
	runes := []rune(value)
	if len(runes) <= maxSearchSnippetRunes {
		return value
	}
	return string(runes[:maxSearchSnippetRunes])
}

func containsPattern(query string) string {
	escaped := strings.NewReplacer("!", "!!", "%", "!%", "_", "!_").Replace(query)
	return "%" + escaped + "%"
}
