package agent

import (
	"context"
	"fmt"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/coredb"
)

const maasLLMProxyAuthorityGeneration int64 = 1

// MaaSLLMProxyScope is the current agentteam authority projected into agentteam-maas.
type MaaSLLMProxyScope struct {
	OrganizationID      string
	WorkspaceID         string
	AgentID             string
	MemberID            string
	MachineID           string
	Runtime             string
	ModelReference      string
	LLMMode             string
	RuntimeSessionID    string
	AuthorityGeneration int64
	OrganizationStatus  string
	WorkspaceStatus     string
	AgentStatus         string
	RuntimeStatus       string
}

func (service *Service) LoadMaaSLLMProxyScope(ctx context.Context, authenticated AuthenticatedAgent) (MaaSLLMProxyScope, error) {
	if service == nil || service.db == nil {
		return MaaSLLMProxyScope{}, fmt.Errorf("agent service is not configured")
	}

	trimmedAgentID := strings.TrimSpace(authenticated.AgentID)
	trimmedWorkspaceID := strings.TrimSpace(authenticated.WorkspaceID)
	trimmedMemberID := strings.TrimSpace(authenticated.MemberID)
	trimmedMachineID := strings.TrimSpace(authenticated.MachineID)
	if trimmedAgentID == "" || trimmedWorkspaceID == "" || trimmedMemberID == "" || trimmedMachineID == "" {
		return MaaSLLMProxyScope{}, ErrUnauthorized
	}

	var scope MaaSLLMProxyScope
	if err := service.db.QueryRow(ctx, `
SELECT
    w.organization_id,
    a.workspace_id,
    a.id,
    a.member_id,
    a.machine_id,
    a.runtime,
    COALESCE(NULLIF(a.model, ''), ''),
    a.llm_mode
FROM agents a
JOIN workspaces w
  ON w.id = a.workspace_id
JOIN machines mac
  ON mac.workspace_id = a.workspace_id
 AND mac.id = a.machine_id
WHERE a.id = $1
  AND a.workspace_id = $2
  AND a.member_id = $3
  AND a.machine_id = $4
  AND a.status <> 'archived'
  AND mac.status = 'active'
`, trimmedAgentID, trimmedWorkspaceID, trimmedMemberID, trimmedMachineID).Scan(
		&scope.OrganizationID,
		&scope.WorkspaceID,
		&scope.AgentID,
		&scope.MemberID,
		&scope.MachineID,
		&scope.Runtime,
		&scope.ModelReference,
		&scope.LLMMode,
	); err != nil {
		if coredb.IsNotFound(err) {
			return MaaSLLMProxyScope{}, ErrUnauthorized
		}
		return MaaSLLMProxyScope{}, fmt.Errorf("load maas llm proxy scope: %w", err)
	}
	scope.AuthorityGeneration = maasLLMProxyAuthorityGeneration
	scope.OrganizationStatus = "active"
	scope.WorkspaceStatus = "active"
	scope.AgentStatus = "active"
	scope.RuntimeStatus = "active"
	return scope, nil
}
