package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/niveus/cloud-build-go/cloudbuild"
	"github.com/niveus/cloud-build-go/config"
	cloudbuildv1 "google.golang.org/api/cloudbuild/v1"
	cloudbuildv2 "google.golang.org/api/cloudbuild/v2"
)

// printRepositoryInfo prints debug information about a repository
func printRepositoryInfo(repo *cloudbuildv2.Repository) {
	fmt.Println("Repository Information:")
	fmt.Printf("  Name: %s\n", repo.Name)
	fmt.Printf("  Remote URI: %s\n", repo.RemoteUri)
	fmt.Printf("  Create Time: %s\n", repo.CreateTime)
	fmt.Printf("  Update Time: %s\n", repo.UpdateTime)

	fmt.Println("  Annotations:")
	for k, v := range repo.Annotations {
		fmt.Printf("    %s: %s\n", k, v)
	}
}

// formatTimestamp generates a human-readable timestamp from trigger ID or current time if ID is empty
func formatTimestamp(id string) string {
	// In Cloud Build v1 API, we don't have direct access to update time
	// But we can extract the timestamp from the ID if available or use current time
	if id == "" {
		return time.Now().Format(time.RFC3339)
	}

	// Just return the ID since we can't reliably extract a timestamp
	return id
}

func main() {
	// Define command-line flags
	configPath := flag.String("config", "config/config.json", "Path to config file")
	action := flag.String("action", "list-connections", "Action to perform: list-connections, create-gitlab, delete-connection, list-linkable-repos, inspect, list-repositories, list-repositories-for-triggers, create-trigger, list-triggers")
	connectionName := flag.String("name", "", "Name for the connection")
	triggerName := flag.String("trigger-name", "test-trigger", "Name for the trigger")
	repositoryName := flag.String("repo", "", "Repository name to use for the trigger")
	branchPattern := flag.String("branch", "master", "Branch pattern for the trigger")
	buildConfigPath := flag.String("config-path", "/cloudbuild.yaml", "Path to the Cloud Build configuration file")
	triggerConfigPath := flag.String("trigger-config", "", "Path to trigger configuration JSON file")
	flag.Parse()

	// Project ID, location, connection type will come from config file
	var projectIDValue, locationValue, connTypeValue string

	// Load config file
	cfg, err := config.LoadConfig(*configPath)
	if err != nil {
		fmt.Printf("Warning: Unable to load config from %s: %v\n", *configPath, err)
		// Create a minimal config with just connection type
		cfg = &config.Config{
			DefaultConnType: "GITHUB",
		}
	}

	// Also try to load trigger config if specified for repository type detection
	var triggerCfg *config.TriggerConfig
	if *action == "create-trigger" && *triggerConfigPath != "" {
		triggerCfg, err = config.LoadTriggerConfig(*triggerConfigPath)
		if err == nil && triggerCfg != nil {
			fmt.Printf("Loaded trigger config from %s, repository type: %s\n",
				*triggerConfigPath, triggerCfg.RepositoryType)
			if triggerCfg.RepositoryType != "" {
				// Override default connection type with repository type from trigger config
				cfg.DefaultConnType = triggerCfg.RepositoryType
				fmt.Printf("Using repository type from trigger config: %s\n", triggerCfg.RepositoryType)
			}
		}
	}

	// Set up project ID, location and connection type from config or flags
	projectIDValue = cfg.ProjectID
	locationValue = cfg.Location
	connTypeValue = cfg.DefaultConnType

	// Log the values that will be used
	log.Printf("Config values set to: Project=%s, Location=%s, Type=%s",
		projectIDValue, locationValue, connTypeValue)

	// Check for required values after loading from config
	if projectIDValue == "" {
		log.Fatal("project ID is required in the config file")
	}

	// We no longer need this validation because each case will handle missing connection names by
	// automatically using values from the config file
	// Validation still happens in each case for more specific handling

	ctx := context.Background()

	// Create a Cloud Build client using our package
	var client *cloudbuild.Client

	// Authentication approach Application Default Credentials
	client, err = cloudbuild.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create Cloud Build client: %v", err)
	}

	// Perform the requested action
	switch *action {

	case "create-gitlab":
		// Find the connection config for the given name
		var connConfig *config.ConnectionConfig
		for _, conn := range cfg.Connections {
			if conn.Name == *connectionName || *connectionName == "" && len(cfg.Connections) == 1 {
				connConfig = &conn
				break
			}
		}

		if connConfig == nil {
			if *connectionName == "" {
				log.Fatalf("No connection configuration found in config file. Please add connections to your config file.")
			} else {
				log.Fatalf("No connection configuration found for name '%s' in config file", *connectionName)
			}
		}

		// Check if the connection config has GitLab configuration
		if connConfig.GitlabConfig == nil {
			log.Fatalf("Connection '%s' does not have GitLab configuration", connConfig.Name)
		}

		log.Printf("Creating GitLab connection using config: ProjectID=%s, Location=%s, Name=%s",
			projectIDValue, locationValue, connConfig.Name)

		fmt.Printf("Creating GitLab connection '%s' in project '%s' (location: '%s')\n",
			connConfig.Name, projectIDValue, locationValue)

		// Create the GitLab connection using the Cloud Build SDK
		err, resourceName := client.CreateGitLabConnection(
			projectIDValue,
			locationValue,
			connConfig.Name,
			connConfig.GitlabConfig,
			connConfig.Annotations,
		)
		if err != nil {
			log.Fatalf("Failed to create GitLab connection: %v", err)
		}

		fmt.Printf("Connection creation initiated successfully. GitLab connection resource: %s\n", resourceName)
		fmt.Println("Note: The connection might take a moment to become fully active in the Cloud Build system.")

	case "list-connections":
		// Use project ID and location from config
		log.Printf("Listing connections in project %s (location: %s)", projectIDValue, locationValue)

		connections, err := client.ListConnections(projectIDValue, locationValue)
		if err != nil {
			log.Fatalf("Failed to list connections: %v", err)
		}
		fmt.Printf("Found %d connections in project %s (location: %s):\n",
			len(connections), projectIDValue, locationValue)
		for i, conn := range connections {
			// Determine connection type based on config
			connType := "Unknown"
			if conn.GithubConfig != nil {
				connType = "GitHub"
			} else if conn.GitlabConfig != nil {
				connType = "GitLab"
			}
			fmt.Printf("%d. %s (Type: %s)\n", i+1, conn.Name, connType)
		}

	case "list-linkable-repos":
		// If connection name not provided via command line, get it from config
		connNameToList := *connectionName
		if connNameToList == "" {
			// If there's only one connection in config, use that
			if len(cfg.Connections) == 1 {
				connNameToList = cfg.Connections[0].Name
				fmt.Printf("Using connection name from config: %s\n", connNameToList)
			} else if len(cfg.Connections) > 1 {
				// If multiple connections, show the available options
				fmt.Println("Multiple connections found in config. Please specify which one to use with --name flag:")
				for i, conn := range cfg.Connections {
					fmt.Printf("%d. %s\n", i+1, conn.Name)
				}
				os.Exit(1)
			} else {
				log.Fatalf("No connections found in config file")
			}
		}

		log.Printf("Listing linkable repositories for connection %s in project %s (location: %s)",
			connNameToList, projectIDValue, locationValue)

		repositories, err := client.ListLinkableRepositories(projectIDValue, locationValue, connNameToList)
		if err != nil {
			log.Fatalf("Failed to list linkable repositories: %v", err)
		}
		fmt.Printf("Found %d linkable repositories for connection %s:\n",
			len(repositories), connNameToList)
		for i, repo := range repositories {
			fmt.Printf("%d. %s\n", i+1, repo.Name)
			if repo.RemoteUri != "" {
				fmt.Printf("   URI: %s\n", repo.RemoteUri)
			}
			// Add a blank line between repositories for better readability
			if i < len(repositories)-1 {
				fmt.Println()
			}
		}

	case "link-repository":
		// If connection name not provided via command line, get it from config
		connNameToLink := *connectionName
		if connNameToLink == "" {
			// If there's only one connection in config, use that
			if len(cfg.Connections) == 1 {
				connNameToLink = cfg.Connections[0].Name
				fmt.Printf("Using connection name from config: %s\n", connNameToLink)
			} else if len(cfg.Connections) > 1 {
				// If multiple connections, show the available options
				fmt.Println("Multiple connections found in config. Please specify which one to use with --name flag:")
				for i, conn := range cfg.Connections {
					fmt.Printf("%d. %s\n", i+1, conn.Name)
				}
				os.Exit(1)
			} else {
				log.Fatalf("No connections found in config file")
			}
		}

		// Get the linkable repositories for this connection
		log.Printf("Finding linkable repositories for connection %s in project %s (location: %s)",
			connNameToLink, projectIDValue, locationValue)

		linkableRepos, err := client.ListLinkableRepositories(projectIDValue, locationValue, connNameToLink)
		if err != nil {
			log.Fatalf("Failed to list linkable repositories: %v", err)
		}

		if len(linkableRepos) == 0 {
			log.Fatalf("No linkable repositories found for connection %s", connNameToLink)
		}

		// Use the first repository in the list
		repoToLink := linkableRepos[0]

		// Extract and use a valid repository name
		// First check if the repository has a RemoteUri field which usually contains the repo info
		var repoName string
		if repoToLink.RemoteUri != "" {
			// Extract name from the remote URI (e.g., https://gitlab.com/namespace/repo-name)
			uriParts := strings.Split(repoToLink.RemoteUri, "/")
			if len(uriParts) > 0 {
				repoName = uriParts[len(uriParts)-1]
				// Remove .git suffix if present
				repoName = strings.TrimSuffix(repoName, ".git")
			}
		}

		// If we still don't have a name, use attributes (which is a more reliable way)
		if repoName == "" {
			// For GitLab repositories, the name is in the attributes
			printRepositoryInfo(repoToLink) // Print debug info

			// Try common attribute keys that might contain the name
			if repoToLink.Annotations != nil {
				if name, ok := repoToLink.Annotations["name"]; ok && name != "" {
					repoName = name
				} else if name, ok := repoToLink.Annotations["repository_name"]; ok && name != "" {
					repoName = name
				}
			}
		}

		// If we still don't have a name, ask the user to provide one manually
		if repoName == "" {
			fmt.Println("Unable to automatically determine repository name. Please provide one manually:")
			fmt.Print("Repository name: ")
			fmt.Scanln(&repoName)
		}

		// Make sure the repository name is valid
		if repoName == "" {
			log.Fatalf("Cannot link repository: No valid repository name provided")
		}

		fmt.Printf("Linking repository: %s\n", repoName)

		// We need to get the remote URI for the repository
		var remoteURI string
		if repoToLink.RemoteUri != "" {
			// Use the remote URI from the repository object if available
			remoteURI = repoToLink.RemoteUri
			fmt.Printf("Using remote URI from repository data: %s\n", remoteURI)
		} else {
			// Otherwise construct a likely URI based on the connection and repository name
			// This is a best guess and may need adjustment for different Git providers
			for _, conn := range cfg.Connections {
				if conn.Name == connNameToLink && conn.GitlabConfig != nil {
					// If we have GitLab config, use the host URI to construct a repo URL
					remoteURI = fmt.Sprintf("%s/%s.git", strings.TrimSuffix(conn.GitlabConfig.HostURI, "/"), repoName)
					break
				}
			}

			// If we still don't have a remote URI, prompt the user
			if remoteURI == "" {
				fmt.Println("Please enter the remote URI for the repository (e.g., https://gitlab.com/namespace/repo.git):")
				fmt.Print("Remote URI: ")
				fmt.Scanln(&remoteURI)

				if remoteURI == "" {
					log.Fatalf("Remote URI is required to link a repository")
				}
			} else {
				fmt.Printf("Constructed remote URI: %s\n", remoteURI)
			}
		}

		// Link the repository with the remote URI
		err = client.LinkRepository(projectIDValue, locationValue, connNameToLink, repoName, remoteURI)
		if err != nil {
			log.Fatalf("Failed to link repository: %v", err)
		}

		fmt.Printf("Successfully linked repository %s to connection %s\n", repoName, connNameToLink)

	case "delete-connection":
		// If connection name not provided via command line, get it from config
		connNameToDelete := *connectionName
		if connNameToDelete == "" {
			// If there's only one connection in config, use that
			if len(cfg.Connections) == 1 {
				connNameToDelete = cfg.Connections[0].Name
				fmt.Printf("Using connection name from config: %s\n", connNameToDelete)
			} else if len(cfg.Connections) > 1 {
				// If multiple connections, show the available options
				fmt.Println("Multiple connections found in config. Please specify which one to delete with --name flag:")
				for i, conn := range cfg.Connections {
					fmt.Printf("%d. %s\n", i+1, conn.Name)
				}
				os.Exit(1)
			} else {
				log.Fatalf("No connections found in config file")
			}
		}

		log.Printf("Deleting connection %s in project %s (location: %s)",
			connNameToDelete, projectIDValue, locationValue)

		err := client.DeleteConnection(projectIDValue, locationValue, connNameToDelete)
		if err != nil {
			log.Fatalf("Failed to delete connection: %v", err)
		}
		fmt.Printf("Successfully deleted connection: %s\n", connNameToDelete)

	case "inspect":
		// This action provides detailed inspection of a connection's configuration and status
		// If connection name not provided via command line, get it from config
		connNameToInspect := *connectionName
		if connNameToInspect == "" {
			// If there's only one connection in config, use that
			if len(cfg.Connections) == 1 {
				connNameToInspect = cfg.Connections[0].Name
				fmt.Printf("Using connection name from config: %s\n", connNameToInspect)
			} else if len(cfg.Connections) > 1 {
				// If multiple connections, show the available options
				fmt.Println("Multiple connections found in config. Please specify which one to inspect with --name flag:")
				for i, conn := range cfg.Connections {
					fmt.Printf("%d. %s\n", i+1, conn.Name)
				}
				os.Exit(1)
			} else {
				log.Fatalf("No connections found in config file")
			}
		}

		log.Printf("Inspecting connection %s in project %s (location: %s)",
			connNameToInspect, projectIDValue, locationValue)

		fmt.Printf("Inspecting connection %s in project %s (location: %s)...\n\n",
			connNameToInspect, projectIDValue, locationValue)
		err := client.InspectConnection(projectIDValue, locationValue, connNameToInspect)
		if err != nil {
			log.Fatalf("Failed to inspect connection: %v", err)
		}

	case "list-repositories":
		// List all repositories available from the trigger service
		log.Printf("Listing repositories in project %s (location: %s)", projectIDValue, locationValue)

		repositories, err := client.ListRepositoriesFromTriggerService(projectIDValue, locationValue)
		if err != nil {
			log.Fatalf("Failed to list repositories: %v", err)
		}

		fmt.Printf("Found %d repositories:\n", len(repositories))
		for i, repo := range repositories {
			fmt.Printf("\n%d. Repository Details:\n", i+1)
			printRepositoryInfo(repo)
		}

		if len(repositories) == 0 {
			fmt.Println("\nNo repositories found.")
			fmt.Println("Hint: You may need to link a repository first using the 'list-linkable-repos' action.")
		}

	case "create-trigger":
		// Create variables for trigger details with default values
		triggerNameValue := *triggerName
		repoNameForTrigger := *repositoryName
		branchPatternValue := *branchPattern
		buildConfigPathValue := *buildConfigPath
		repoTypeValue := connTypeValue // Default to global connection type

		if *triggerConfigPath != "" {
			// Load trigger configuration from JSON file
			var err error
			if triggerCfg == nil { // Only load if not already loaded during startup
				triggerCfg, err = config.LoadTriggerConfig(*triggerConfigPath)
				if err != nil {
					log.Fatalf("Failed to load trigger configuration: %v", err)
				}
				fmt.Printf("Loaded trigger config with repository type: %s\n", triggerCfg.RepositoryType)
			}

			// Use values from config file
			if triggerCfg.ProjectID != "" {
				projectIDValue = triggerCfg.ProjectID
			}
			if triggerCfg.Location != "" {
				locationValue = triggerCfg.Location
			}
			if triggerCfg.RepositoryType != "" {
				repoTypeValue = triggerCfg.RepositoryType
				fmt.Printf("Using repository type from trigger config: %s\n", repoTypeValue)
			}

			// Override command-line arguments with values from config
			if triggerCfg.Name != "" {
				triggerNameValue = triggerCfg.Name
			}
			if triggerCfg.RepositoryName != "" {
				repoNameForTrigger = triggerCfg.RepositoryName
			}
			if triggerCfg.BranchPattern != "" {
				branchPatternValue = triggerCfg.BranchPattern
			}
			if triggerCfg.ConfigPath != "" {
				buildConfigPathValue = triggerCfg.ConfigPath
			}

			fmt.Println("Using trigger configuration from file:", *triggerConfigPath)
		}

		// Debug output to help track where the repository name is coming from
		fmt.Printf("Repository name from config: %s\n", repoNameForTrigger)

		// If repository name is still missing, prompt for selection
		if repoNameForTrigger == "" {
			fmt.Println("No repository specified. Listing available repositories:")
			repositories, err := client.ListRepositoriesFromTriggerService(projectIDValue, locationValue)
			if err != nil {
				log.Fatalf("Failed to list repositories: %v", err)
			}

			fmt.Printf("Found %d repositories:\n", len(repositories))
			// Create a map to store repository display names to actual repository identifiers
			repoDisplayMap := make(map[int]string)

			for i, repo := range repositories {
				// Extract proper repository identifier
				var repoNameDisplay string
				if repo.RemoteUri != "" {
					// For repositories with a Remote URI, use that (typically GitLab/GitHub repos)
					// Extract the actual repository name from the URI
					uriParts := strings.Split(repo.RemoteUri, "/")
					if len(uriParts) > 0 {
						// Get the last segment, removing .git suffix if present
						repoBase := uriParts[len(uriParts)-1]
						repoNameDisplay = strings.TrimSuffix(repoBase, ".git")
						// Store the actual repository name without .git suffix in our map
						repoDisplayMap[i+1] = repoNameDisplay
					} else {
						// Fallback to full URI if we can't parse it
						repoNameDisplay = repo.RemoteUri
						repoDisplayMap[i+1] = repo.RemoteUri
					}
				} else if repo.Name != "" {
					// If we have a Name but no RemoteUri, use the last part of the Name
					parts := strings.Split(repo.Name, "/")
					repoNameDisplay = parts[len(parts)-1]
					repoDisplayMap[i+1] = repoNameDisplay
				} else {
					// If we don't have RemoteUri or a valid Name, use "Unknown Repository"
					repoNameDisplay = fmt.Sprintf("Unknown Repository %d", i+1)
					repoDisplayMap[i+1] = fmt.Sprintf("repo-%d", i+1) // Fallback name
				}
				fmt.Printf("%d. %s\n", i+1, repoNameDisplay)
			}

			if len(repositories) == 0 {
				fmt.Println("No repositories found. Please link a repository first.")
				os.Exit(1)
			}

			// Prompt for repository selection
			var repoIndex int
			fmt.Print("Enter the number of the repository to use: ")
			_, err = fmt.Scanf("%d", &repoIndex)
			if err != nil || repoIndex < 1 || repoIndex > len(repositories) {
				log.Fatalf("Invalid repository selection")
			}

			// Use the repository name from our map
			repoNameForTrigger = repoDisplayMap[repoIndex]

			// If we somehow still have an empty repository name, use a fallback
			if repoNameForTrigger == "" {
				// As a fallback, extract from the repo name
				if repositories[repoIndex-1].RemoteUri != "" {
					// Use the remote URI
					uriParts := strings.Split(repositories[repoIndex-1].RemoteUri, "/")
					if len(uriParts) > 0 {
						repoNameForTrigger = strings.TrimSuffix(uriParts[len(uriParts)-1], ".git")
					}
				} else {
					// Last resort: use a generic name with timestamp
					repoNameForTrigger = fmt.Sprintf("repository-%d", time.Now().Unix())
				}
			}
		}

		log.Printf("Creating trigger %s for repository %s in project %s (location: %s)",
			triggerNameValue, repoNameForTrigger, projectIDValue, locationValue)

		fmt.Printf("Creating Cloud Build trigger with the following configuration:\n")
		fmt.Printf("  Trigger Name: %s\n", triggerNameValue)
		fmt.Printf("  Region: %s\n", locationValue)
		fmt.Printf("  Repository: %s\n", repoNameForTrigger)
		fmt.Printf("  Branch Pattern: %s\n", branchPatternValue)
		fmt.Printf("  Build Config File: %s\n\n", buildConfigPathValue)

		// Extract repository URI from config file if available
		repoURIValue := ""

		// If we loaded from a config file, use URI from there
		if triggerCfg != nil && triggerCfg.RepositoryURI != "" {
			repoURIValue = triggerCfg.RepositoryURI
		}

		// We're already using the existing client, no need to create a new one
		// client was created at the beginning of main()

		// Create the trigger with all information
		trigger, err := client.CreateTrigger(
			projectIDValue,
			locationValue,
			triggerNameValue,
			repoNameForTrigger,
			branchPatternValue,
			buildConfigPathValue,
			repoTypeValue,
			repoURIValue,
		)

		if err != nil {
			log.Fatalf("Failed to create trigger: %v", err)
		}

		// Print success message
		fmt.Printf("Successfully created trigger: %s\n", trigger.Name)
		fmt.Printf("Trigger description: %s\n", trigger.Description)

	case "list-triggers":
		// List all triggers in the project and location
		log.Printf("Listing triggers in project %s (location: %s)", projectIDValue, locationValue)

		triggers, err := client.ListTriggers(projectIDValue, locationValue)
		if err != nil {
			log.Fatalf("Failed to list triggers: %v", err)
		}

		fmt.Printf("Found %d build triggers:\n", len(triggers))
		// Use a nil check to ensure we're correctly using the cloudbuildv1 type
		_ = (*cloudbuildv1.BuildTrigger)(nil)
		for i, trigger := range triggers {
			fmt.Printf("\n%d. Trigger: %s\n", i+1, trigger.Name)
			fmt.Printf("   Description: %s\n", trigger.Description)
			fmt.Printf("   Created: %s\n", trigger.CreateTime)
			fmt.Printf("   Last Modified: %s\n", formatTimestamp(trigger.Id))

			// Print repository information if available
			if trigger.TriggerTemplate != nil {
				fmt.Printf("   Repository: %s\n", trigger.TriggerTemplate.RepoName)

				// Print branch pattern if available
				if trigger.TriggerTemplate.BranchName != "" {
					fmt.Printf("   Branch Pattern: %s\n", trigger.TriggerTemplate.BranchName)
				}
			}

			// Print build configuration file if available
			if trigger.Filename != "" {
				fmt.Printf("   Build Config File: %s\n", trigger.Filename)
			}
		}

		if len(triggers) == 0 {
			fmt.Println("\nNo triggers found.")
		}

	case "list-repositories-for-triggers":
		// This case helps identify what repositories are available for trigger creation
		fmt.Println("Listing all repositories available for Cloud Build triggers...")

		// Use the current client for this operation
		repos, err := client.ListRepositoriesFromTriggerService(projectIDValue, locationValue)
		if err != nil {
			fmt.Printf("WARNING: Error listing repositories: %v\n", err)
			fmt.Println("This could be due to permission issues with the Cloud Build service account.")

			// Try listing connections as a fallback
			conns, connErr := client.ListConnections(projectIDValue, locationValue)
			if connErr != nil {
				log.Fatalf("Failed to list connections: %v", connErr)
			}

			fmt.Printf("Found %d connection(s) in project %s (location: %s)\n", len(conns), projectIDValue, locationValue)
			for i, conn := range conns {
				fmt.Printf("  %d. Connection: %s\n", i+1, conn.Name)
				if conn.GitlabConfig != nil {
					fmt.Printf("     Type: GitLab\n")
					fmt.Printf("     Host URI: %s\n", conn.GitlabConfig.HostUri)
				}
			}

			fmt.Println("\nTROUBLESHOOTING TIPS:")
			fmt.Println("1. Ensure your Cloud Build service account has the Secret Manager Secret Accessor role")
			fmt.Println("2. For 1st-gen repositories, use repository names in the format 'github_org_repo'")
			fmt.Println("3. For GitLab repositories, verify that the connection is properly set up")
		} else {
			fmt.Printf("Found %d repository/repositories available for triggers:\n", len(repos))

			if len(repos) == 0 {
				fmt.Println("No repositories available for triggers.")
				fmt.Println("You need to connect repositories to your Cloud Build project first.")
			}

			for i, repo := range repos {
				fmt.Printf("\nRepository %d:\n", i+1)
				fmt.Printf("  Full Name: %s\n", repo.Name)
				if repo.RemoteUri != "" {
					fmt.Printf("  Remote URI: %s\n", repo.RemoteUri)
				}

				// Extract the repo name for reference
				var simpleName string
				if repo.RemoteUri != "" {
					uriParts := strings.Split(repo.RemoteUri, "/")
					if len(uriParts) > 0 {
						simpleName = strings.TrimSuffix(uriParts[len(uriParts)-1], ".git")
					}
				} else if repo.Name != "" {
					// Try to get name from Name field
					parts := strings.Split(repo.Name, "/")
					simpleName = parts[len(parts)-1]
				}

				if simpleName != "" {
					fmt.Printf("  Simple Name: %s (use this in your trigger config)\n", simpleName)
				}
			}

			fmt.Println("\nTo create a trigger, use one of the repository names listed above in your trigger configuration.")
		}

	default:
		log.Fatalf("Unknown action: %s. Supported actions are: list-connections, create-gitlab, delete-connection, list-linkable-repos, inspect, list-repositories, list-repositories-for-triggers, create-trigger, list-triggers", *action)
	}
}
