package tools

import (
	"context"
	"strings"

	"github.com/modelcontextprotocol/go-sdk/mcp"

	"git.warky.dev/wdevs/amcs/internal/config"
	"git.warky.dev/wdevs/amcs/internal/session"
	"git.warky.dev/wdevs/amcs/internal/store"
	thoughttypes "git.warky.dev/wdevs/amcs/internal/types"
)

type ListTool struct {
	store    *store.DB
	search   config.SearchConfig
	sessions *session.ActiveProjects
}

type ListInput struct {
	Limit           int    `json:"limit,omitempty" jsonschema:"maximum number of thoughts to return"`
	Type            string `json:"type,omitempty" jsonschema:"filter by thought type"`
	Topic           string `json:"topic,omitempty" jsonschema:"filter by topic"`
	Person          string `json:"person,omitempty" jsonschema:"filter by mentioned person"`
	Days            int    `json:"days,omitempty" jsonschema:"only include thoughts from the last N days"`
	IncludeArchived bool   `json:"include_archived,omitempty" jsonschema:"include archived thoughts when true"`
	Project         string `json:"project,omitempty" jsonschema:"optional project name or id to scope the listing"`
}

type ListOutput struct {
	Thoughts []thoughttypes.Thought `json:"thoughts"`
}

func NewListTool(db *store.DB, search config.SearchConfig, sessions *session.ActiveProjects) *ListTool {
	return &ListTool{store: db, search: search, sessions: sessions}
}

func (t *ListTool) Handle(ctx context.Context, req *mcp.CallToolRequest, in ListInput) (*mcp.CallToolResult, ListOutput, error) {
	project, err := resolveProject(ctx, t.store, t.sessions, req, in.Project, false)
	if err != nil {
		return nil, ListOutput{}, err
	}

	var projectID *int64
	if project != nil {
		projectID = &project.NumericID
	}

	thoughts, err := t.store.ListThoughts(ctx, thoughttypes.ListFilter{
		Limit:           normalizeLimit(in.Limit, t.search),
		Type:            strings.TrimSpace(in.Type),
		Topic:           strings.TrimSpace(in.Topic),
		Person:          strings.TrimSpace(in.Person),
		Days:            in.Days,
		IncludeArchived: in.IncludeArchived,
		ProjectID:       projectID,
	})
	if err != nil {
		return nil, ListOutput{}, err
	}
	if project != nil {
		_ = t.store.TouchProject(ctx, project.NumericID)
	}

	return nil, ListOutput{Thoughts: thoughts}, nil
}
