package cmd

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	gogitea "code.gitea.io/sdk/gitea"
	"github.com/spf13/cobra"
)

var connectCmd = &cobra.Command{
	Use:   "connect",
	Short: "Create a Gitea repo for the current directory and push",
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := loadConfig()
		if err != nil {
			return err
		}

		// Use current folder name as repo name
		cwd, err := os.Getwd()
		if err != nil {
			return fmt.Errorf("getting current directory: %w", err)
		}
		raw := filepath.Base(cwd)
		// Gitea repo names: only alphanumeric, dash, dot — replace everything else with a dash
		name := regexp.MustCompile(`[^a-zA-Z0-9.\-]`).ReplaceAllString(raw, "-")
		name = strings.Trim(name, "-")
		fmt.Printf("Using repo name: %s\n", name)

		client, err := gogitea.NewClient(cfg.URL, gogitea.SetToken(cfg.Token))
		if err != nil {
			return fmt.Errorf("connecting to Gitea: %w", err)
		}

		repo, _, err := client.CreateRepo(gogitea.CreateRepoOption{
			Name:        name,
			Description: repoDesc,
			Private:     repoPrivate,
			AutoInit:    false,
		})
		if err != nil {
			return fmt.Errorf("creating Gitea repo: %w", err)
		}
		fmt.Println("Created Gitea repo:", repo.HTMLURL)

		remote := authCloneURL(cfg, repo.CloneURL)
		if err := runGit(".", "remote", "add", "origin", remote); err != nil {
			return err
		}

		if err := runGit(".", "push", "-u", "origin", "main"); err != nil {
			return err
		}

		fmt.Println("Pushed to:", repo.HTMLURL)
		return nil
	},
}

func init() {
	connectCmd.Flags().BoolVarP(&repoPrivate, "private", "p", false, "Make the repo private")
	connectCmd.Flags().StringVarP(&repoDesc, "desc", "d", "", "Repo description")
	rootCmd.AddCommand(connectCmd)
}
