package cmd

import (
	"fmt"
	"os"
	"strings"

	cpaws "github.com/tidbcloud/controlplane9/internal/aws"
)

// cleanupOwnedAWSProfile removes only the exact profile section whose persisted
// session marker still belongs to the session being destroyed. The Terraform
// writer uses the same host-global lock, so a newer session binding cannot be
// removed between the ownership check and the atomic rewrite.
func cleanupOwnedAWSProfile(profileName, sessionName string) (string, error) {
	profileName = strings.TrimSpace(profileName)
	sessionName = strings.TrimSpace(sessionName)
	if profileName == "" || sessionName == "" {
		return "AWS profile cleanup skipped: profile/session ownership is incomplete", nil
	}

	configPath, err := cpaws.LocalAWSConfigPath()
	if err != nil {
		return "", err
	}
	releaseLock, acquired, err := cpaws.LockLocalAWSConfig(configPath, true)
	if err != nil {
		if os.IsNotExist(err) {
			return fmt.Sprintf("AWS profile %q already absent", profileName), nil
		}
		return "", fmt.Errorf("open AWS profile ownership lock: %w", err)
	}
	if !acquired {
		return fmt.Sprintf(
			"AWS profile %q retained: a concurrent profile update owns the cleanup lock",
			profileName,
		), nil
	}
	defer releaseLock()

	config, err := os.ReadFile(configPath)
	if err != nil {
		if os.IsNotExist(err) {
			return fmt.Sprintf("AWS profile %q already absent", profileName), nil
		}
		return "", fmt.Errorf("read AWS config %s: %w", configPath, err)
	}
	updated, owned, unambiguous := removeOwnedAWSProfileSection(string(config), profileName, sessionName)
	if !unambiguous {
		return fmt.Sprintf(
			"AWS profile %q retained: its session ownership marker is missing or ambiguous",
			profileName,
		), nil
	}
	if !owned {
		return fmt.Sprintf(
			"AWS profile %q retained: it no longer belongs to session %q",
			profileName,
			sessionName,
		), nil
	}
	if err := cpaws.WriteLocalAWSConfigAtomic(configPath, []byte(updated)); err != nil {
		return "", err
	}
	return fmt.Sprintf("AWS profile %q removed for destroyed session %q", profileName, sessionName), nil
}

func removeOwnedAWSProfileSection(config, profileName, sessionName string) (
	configAfter string,
	owned bool,
	unambiguous bool,
) {
	lines := strings.SplitAfter(config, "\n")
	section := "[profile " + profileName + "]"
	sectionStart := -1
	sectionEnd := -1
	sectionCount := 0
	for index, line := range lines {
		trimmed := strings.TrimSpace(line)
		if trimmed == section {
			sectionCount++
			sectionStart = index
			sectionEnd = len(lines)
			continue
		}
		if sectionStart >= 0 && sectionEnd == len(lines) && strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
			sectionEnd = index
		}
	}
	if sectionCount == 0 {
		return config, false, true
	}
	if sectionCount != 1 || sectionStart < 0 || sectionEnd < sectionStart {
		return config, false, false
	}

	markerPrefix := "# cp9-session ="
	markerCount := 0
	markerMatches := false
	for _, line := range lines[sectionStart+1 : sectionEnd] {
		trimmed := strings.TrimSpace(line)
		if !strings.HasPrefix(trimmed, markerPrefix) {
			continue
		}
		markerCount++
		markerMatches = strings.TrimSpace(strings.TrimPrefix(trimmed, markerPrefix)) == sessionName
	}
	if markerCount != 1 {
		return config, false, false
	}
	if !markerMatches {
		return config, false, true
	}

	updatedLines := append([]string{}, lines[:sectionStart]...)
	updatedLines = append(updatedLines, lines[sectionEnd:]...)
	return strings.Join(updatedLines, ""), true, true
}
