package app

import (
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/store/app/installation"
	"github.com/tidbcloud/AgentTeam/internal/store/app/registry"
	"github.com/tidbcloud/AgentTeam/internal/store/model"
)

type agentAppCapabilitySet struct {
	Supported             bool
	MCPName               string
	Tools                 []string
	Scopes                []string
	AuthorizationMode     string
	InstallMode           string
	RequiresSubscriptions bool
}

func agentAppCapabilitySetForService(appSlug string, hasMCPTools bool, hasSubscriptionsManage bool, configJSON []byte) agentAppCapabilitySet {
	normalizedSlug := strings.ToLower(strings.TrimSpace(appSlug))
	config, err := model.DecodeAppExecutionCapability(configJSON)
	if err != nil {
		return agentAppCapabilitySet{}
	}
	if !registry.IsProductAppSlug(normalizedSlug) ||
		!hasMCPTools ||
		(config.RequiresSubscriptions && !hasSubscriptionsManage) {
		return agentAppCapabilitySet{}
	}
	tools := normalizeScopeSet(config.Tools)
	if len(tools) == 0 {
		tools = installation.AgentAppMCPTools(normalizedSlug)
	}
	scopes := normalizeScopeSet(config.Scopes)
	if len(scopes) == 0 {
		scopes = installation.DefaultAgentAppAuthorizationScopes(normalizedSlug)
	}
	if len(tools) == 0 || len(scopes) == 0 {
		return agentAppCapabilitySet{}
	}
	return agentAppCapabilitySet{
		Supported:         true,
		MCPName:           normalizedSlug,
		Tools:             tools,
		Scopes:            scopes,
		AuthorizationMode: config.AuthorizationMode,
		InstallMode:       config.InstallMode,
		RequiresSubscriptions: config.
			RequiresSubscriptions,
	}
}
