package server

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"strconv"
	"strings"
	"sync"

	agsserver "github.com/pingcap/agent-git-service/server"

	"github.com/tidbcloud/AgentTeam/internal/identity/trusted"
	"github.com/tidbcloud/AgentTeam/internal/observability/logging"
	"github.com/tidbcloud/AgentTeam/internal/service/automation"
	"github.com/tidbcloud/AgentTeam/internal/store/content"
	reposstore "github.com/tidbcloud/AgentTeam/internal/store/resource/repos"
)

type agsAutomationBranchUpdateBridge struct {
	repositories        *reposstore.Store
	automations         *automation.AutomationsService
	authority           automation.AutomationContentAuthority
	authorizationHeader string
	queue               chan agsserver.RepositoryEvent
	done                chan struct{}
	startOnce           sync.Once
	stopOnce            sync.Once
	mu                  sync.RWMutex
	started             bool
	closed              bool
	processCtx          context.Context
	cancel              context.CancelFunc
}

var errAutomationBridgeNotStarted = errors.New("automation repository event bridge is not started")

type repositoryEventSinks []agsserver.RepositoryEventSink

func (sinks repositoryEventSinks) HandleRepositoryEvent(ctx context.Context, event agsserver.RepositoryEvent) error {
	var joined error
	for _, sink := range sinks {
		if sink != nil {
			joined = errors.Join(joined, sink.HandleRepositoryEvent(ctx, event))
		}
	}
	return joined
}

func newAGSAutomationBranchUpdateBridge(repositories *reposstore.Store, automations *automation.AutomationsService, authorizationHeader string) *agsAutomationBranchUpdateBridge {
	return &agsAutomationBranchUpdateBridge{
		repositories:        repositories,
		automations:         automations,
		authorizationHeader: strings.TrimSpace(authorizationHeader),
		queue:               make(chan agsserver.RepositoryEvent, 64),
		done:                make(chan struct{}),
	}
}

func (b *agsAutomationBranchUpdateBridge) Start() {
	if b == nil {
		return
	}
	b.startOnce.Do(func() {
		b.mu.Lock()
		defer b.mu.Unlock()
		if b.closed {
			return
		}
		b.started = true
		b.processCtx, b.cancel = context.WithCancel(context.Background())
		logging.Go(slog.Default(), b.run)
	})
}

func (b *agsAutomationBranchUpdateBridge) HandleRepositoryEvent(ctx context.Context, event agsserver.RepositoryEvent) error {
	if b == nil {
		return nil
	}
	b.mu.RLock()
	if b.closed || !b.started {
		b.mu.RUnlock()
		return errAutomationBridgeNotStarted
	}
	safe := agsserver.RepositoryEvent{
		RepositoryID: event.RepositoryID, Event: event.Event, Action: event.Action,
		PayloadJSON: append([]byte(nil), event.PayloadJSON...),
	}
	select {
	case b.queue <- safe:
		b.mu.RUnlock()
	default:
		b.mu.RUnlock()
		slog.WarnContext(ctx, "automation repository event queue full; dropping event", "repo_id", event.RepositoryID, "event", event.Event)
	}
	return nil
}

func (b *agsAutomationBranchUpdateBridge) processRepositoryEvent(ctx context.Context, event agsserver.RepositoryEvent) error {
	eventName := strings.TrimSpace(event.Event)
	if eventName != "push" && !(eventName == "pull_request" && strings.TrimSpace(event.Action) == "closed") {
		return nil
	}
	var payload agsWebhookPayload
	if len(event.PayloadJSON) == 0 || json.Unmarshal(event.PayloadJSON, &payload) != nil {
		return nil
	}
	fullName := strings.TrimSpace(payload.Repository.FullName)
	if eventName == "pull_request" && !payload.PullRequest.Merged {
		return nil
	}
	ref, before, after := payload.Ref, payload.Before, payload.After
	if eventName == "pull_request" {
		ref = "refs/heads/" + strings.TrimSpace(payload.PullRequest.Base.Ref)
		before = strings.TrimSpace(payload.PullRequest.Base.SHA)
		after = strings.TrimSpace(payload.PullRequest.MergeCommitSHA)
	}
	branch := repositoryBranchUpdate{
		RepositoryFullName: fullName,
		Ref:                ref, Before: before, After: after,
		ActorRef:     "user:" + strings.TrimSpace(payload.Sender.Login),
		ActorDisplay: firstNonEmptyString(payload.Sender.Name, payload.Sender.FullName, payload.Sender.Login),
		EventID:      repositoryEventID(event, payload), PayloadJSON: string(event.PayloadJSON),
	}
	return b.handleBranchUpdate(ctx, branch)
}

func (b *agsAutomationBranchUpdateBridge) run() {
	defer close(b.done)
	for event := range b.queue {
		if err := b.processRepositoryEvent(b.processCtx, event); err != nil {
			slog.Warn("automation repository event bridge failed", "repo_id", event.RepositoryID, "event", event.Event, "error", err)
		}
	}
}

func (b *agsAutomationBranchUpdateBridge) Close() {
	if b == nil {
		return
	}
	_ = b.Quiesce(context.Background())
}

func (b *agsAutomationBranchUpdateBridge) Quiesce(ctx context.Context) error {
	if b == nil {
		return nil
	}
	b.stopOnce.Do(func() {
		b.mu.Lock()
		b.closed = true
		if b.started {
			close(b.queue)
		} else {
			close(b.done)
		}
		b.mu.Unlock()
	})
	select {
	case <-b.done:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func repositoryEventID(event agsserver.RepositoryEvent, payload agsWebhookPayload) string {
	hash := sha256.New()
	for _, value := range []string{
		strconv.FormatUint(uint64(event.RepositoryID), 10),
		event.Event, event.Action, payload.Ref, payload.Before, payload.After,
	} {
		_, _ = hash.Write([]byte(strings.TrimSpace(value)))
		_, _ = hash.Write([]byte{0})
	}
	return "ags-repository-event:" + hex.EncodeToString(hash.Sum(nil))
}

type repositoryBranchUpdate struct {
	RepositoryFullName                           string
	Ref, Before, After                           string
	ChangedPaths                                 []string
	ActorRef, ActorDisplay, EventID, PayloadJSON string
}

func (b *agsAutomationBranchUpdateBridge) handleBranchUpdate(ctx context.Context, event repositoryBranchUpdate) error {
	if b == nil || b.repositories == nil || b.automations == nil {
		return nil
	}
	fullName := strings.TrimSpace(event.RepositoryFullName)
	owner, repo, ok := splitRepositoryFullName(fullName)
	if !ok {
		return fmt.Errorf("automation branch update repository_full_name is invalid")
	}
	repos, err := b.repositories.ListByRepoFullName(ctx, fullName)
	if err != nil {
		return err
	}
	if len(repos) == 0 {
		slog.InfoContext(ctx, "automation branch update repo mapping not found; skipping", "repository", fullName, "ref", event.Ref)
		return nil
	}
	var joined error
	seen := map[string]struct{}{}
	for _, repoRecord := range repos {
		// The AGS event fanout is shared by several product domains. Only an
		// explicit Automation repository binding may start Automation runs;
		// a KB source mapping for the same upstream repository is not an
		// Automation trigger (and may already be native-active).
		if strings.TrimSpace(repoRecord.ResourceType) != reposstore.ResourceTypeAutomationRepository {
			continue
		}
		workspaceID := strings.TrimSpace(repoRecord.WorkspaceID)
		if workspaceID == "" {
			continue
		}
		if _, ok := seen[workspaceID]; ok {
			continue
		}
		if b.authority != nil {
			authority, found, authorityErr := b.authority.GetAuthority(ctx, workspaceID, "automation", owner+"/"+repo)
			if authorityErr != nil {
				joined = errors.Join(joined, fmt.Errorf("%s: resolve automation authority: %w", workspaceID, authorityErr))
				continue
			}
			if found && authority.State == content.AuthorityStateNativeActive {
				continue
			}
			if found && authority.State != content.AuthorityStateLegacyActive {
				joined = errors.Join(joined, fmt.Errorf("%s: unknown automation authority state %q", workspaceID, authority.State))
				continue
			}
		}
		seen[workspaceID] = struct{}{}
		callCtx := automationEventerContext(ctx, workspaceID)
		_, err := b.automations.StartRepositoryAutomationRunsForPushEvent(callCtx, workspaceID, automation.AutomationEventerPrincipalID, automation.AutomationRepositoryPushEventMutation{
			RepositoryOwner:     owner,
			RepositoryName:      repo,
			AuthorizationHeader: b.authorizationHeader,
			EventID:             strings.TrimSpace(event.EventID),
			Ref:                 strings.TrimSpace(event.Ref),
			Before:              strings.TrimSpace(event.Before),
			After:               strings.TrimSpace(event.After),
			ChangedPaths:        append([]string(nil), event.ChangedPaths...),
			ActorRef:            strings.TrimSpace(event.ActorRef),
			ActorDisplay:        strings.TrimSpace(event.ActorDisplay),
			EventPayloadJSON:    strings.TrimSpace(event.PayloadJSON),
		})
		if err != nil {
			slog.WarnContext(ctx, "automation branch update bridge failed", "workspace_id", workspaceID, "repository", fullName, "ref", event.Ref, "error", err)
			joined = errors.Join(joined, fmt.Errorf("%s: %w", workspaceID, err))
		}
	}
	return joined
}

func automationEventerContext(ctx context.Context, workspaceID string) context.Context {
	workspaceID = strings.TrimSpace(workspaceID)
	claims := map[string]any{
		"sub":                    automation.AutomationEventerPrincipalID,
		"workspace_ids":          []string{workspaceID},
		"automation_permissions": []string{"automation:eventer", "automation:service"},
		"service_actor":          true,
	}
	return trusted.WithIdentity(ctx, trusted.Identity{
		Subject:   automation.AutomationEventerPrincipalID,
		RawClaims: claims,
	})
}

func splitRepositoryFullName(fullName string) (string, string, bool) {
	owner, repo, ok := strings.Cut(strings.TrimSpace(fullName), "/")
	owner = strings.TrimSpace(owner)
	repo = strings.TrimSpace(repo)
	return owner, repo, ok && owner != "" && repo != ""
}
