package agentteambridge

import (
	"context"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/apr/provider/codex"
)

// CodexAuthSnapshot describes one live Codex auth backend in AgentTeam's registry.
type CodexAuthSnapshot struct {
	Source          string
	Name            string
	BackendID       int
	BaseURL         string
	Mode            string
	Active          bool
	Weight          float64
	AllowedAPIKeys  []string
	HasAccessToken  bool
	HasRefreshToken bool
	AccessToken     string
	APIKey          string
	AccountID       string
	LastRefreshAt   string
	LastStatus      int
	LastError       string
}

// CodexAuthRefreshResult describes one manual refresh attempt.
type CodexAuthRefreshResult struct {
	Source    string
	Refreshed bool
	Error     string
}

func codexProviderRuntimeKey(organizationID string, providerID string) string {
	organizationID = strings.TrimSpace(organizationID)
	providerID = strings.TrimSpace(providerID)
	if organizationID == "" || providerID == "" {
		return ""
	}
	return organizationID + "/" + providerID
}

func toAgentTeamCodexAuthSnapshots(items []codex.AuthSnapshot) []CodexAuthSnapshot {
	if len(items) == 0 {
		return nil
	}
	result := make([]CodexAuthSnapshot, 0, len(items))
	for _, item := range items {
		result = append(result, CodexAuthSnapshot{
			Source:          item.Source,
			Name:            item.Name,
			BackendID:       item.ID,
			BaseURL:         item.BaseURL,
			Mode:            item.Mode,
			Active:          item.Active,
			Weight:          item.Weight,
			AllowedAPIKeys:  append([]string(nil), item.AllowedAPIKeys...),
			HasAccessToken:  item.HasAccessToken,
			HasRefreshToken: item.HasRefreshToken,
			AccessToken:     item.AccessToken,
			APIKey:          item.APIKey,
			AccountID:       item.AccountID,
			LastRefreshAt:   item.LastRefreshAt,
			LastStatus:      item.LastStatus,
			LastError:       item.LastError,
		})
	}
	return result
}

func toAgentTeamCodexAuthRefreshResults(items []codex.AuthRefreshResult) []CodexAuthRefreshResult {
	if len(items) == 0 {
		return nil
	}
	result := make([]CodexAuthRefreshResult, 0, len(items))
	for _, item := range items {
		result = append(result, CodexAuthRefreshResult{
			Source:    item.Source,
			Refreshed: item.Refreshed,
			Error:     item.Error,
		})
	}
	return result
}

func (refresher *Refresher) CodexAuthSnapshots(organizationID string, providerID string) ([]CodexAuthSnapshot, bool) {
	if refresher == nil {
		return nil, false
	}

	refresher.mu.RLock()
	defer refresher.mu.RUnlock()

	provider := refresher.codexProviders[codexProviderRuntimeKey(organizationID, providerID)]
	if provider == nil {
		return nil, false
	}
	return toAgentTeamCodexAuthSnapshots(provider.AuthSnapshots()), true
}

func (refresher *Refresher) ForceRefreshCodexAuth(ctx context.Context, organizationID string, providerID string, source string) ([]CodexAuthRefreshResult, bool) {
	if refresher == nil {
		return nil, false
	}

	refresher.mu.RLock()
	defer refresher.mu.RUnlock()

	provider := refresher.codexProviders[codexProviderRuntimeKey(organizationID, providerID)]
	if provider == nil {
		return nil, false
	}
	return toAgentTeamCodexAuthRefreshResults(provider.ForceRefreshAuth(ctx, source)), true
}
