package app

import (
	"context"
	"time"

	"github.com/dtoro/oikos/internal/core/domain"
	"github.com/dtoro/oikos/internal/core/ports"
)

// KnowledgeService is the use-case layer for knowledge-base operations.
// Shared by REST + MCP knowledge tools (Phase 6 convergence).
type KnowledgeService struct {
	repo ports.KnowledgeRepository
}

func NewKnowledgeService(repo ports.KnowledgeRepository) *KnowledgeService {
	return &KnowledgeService{repo: repo}
}

type SearchCmd struct {
	Query string
	Limit int
}

func (s *KnowledgeService) Search(ctx context.Context, cmd SearchCmd) ([]ports.KnowledgeEntry, error) {
	return s.repo.Search(ctx, cmd.Query, cmd.Limit)
}

type UpsertKnowledgeCmd struct {
	Entry  KnowledgeEntryCmd
	ActorType string
	Actor     string
}

type KnowledgeEntryCmd struct {
	Slug    string
	Title   string
	Kind    string
	Tags    []string
	Content string
	About   []string
}

func (s *KnowledgeService) Upsert(ctx context.Context, cmd UpsertKnowledgeCmd) (ports.KnowledgeEntry, error) {
	return s.repo.Upsert(ctx, ports.KnowledgeUpsertInput{
		Entry: ports.KnowledgeEntry{
			Slug: cmd.Entry.Slug, Title: cmd.Entry.Title,
			Kind: cmd.Entry.Kind, Tags: cmd.Entry.Tags,
			Content: cmd.Entry.Content, About: cmd.Entry.About,
			UpdatedAt: time.Now(),
		},
	})
}

func (s *KnowledgeService) GetContent(ctx context.Context, slug string) (ports.KnowledgeEntry, error) {
	return s.repo.GetContent(ctx, slug)
}

func (s *KnowledgeService) SoftDelete(ctx context.Context, slug string) error {
	return s.repo.SoftDelete(ctx, slug)
}

func (s *KnowledgeService) Restore(ctx context.Context, slug string) error {
	return s.repo.Restore(ctx, slug)
}

// LearningService handles patterns, feedback, and skills.
type LearningService struct {
	repo ports.LearningRepository
}

func NewLearningService(repo ports.LearningRepository) *LearningService {
	return &LearningService{repo: repo}
}

func (s *LearningService) ListPatterns(ctx context.Context) ([]domain.Pattern, error) {
	return s.repo.ListPatterns(ctx, 100)
}

func (s *LearningService) UpsertPattern(ctx context.Context, pattern domain.Pattern) error {
	return s.repo.UpsertPattern(ctx, pattern)
}

func (s *LearningService) Validate(ctx context.Context, patternID domain.UUID) error {
	return s.repo.Validate(ctx, patternID)
}

func (s *LearningService) Quarantine(ctx context.Context, patternID domain.UUID, reason string) error {
	return s.repo.Quarantine(ctx, patternID, reason)
}