package cmd

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

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

var (
	repoPrivate bool
	repoDesc    string
)

var initCmd = &cobra.Command{
	Use:   "init <project-name>",
	Short: "Create a local project folder and a new Gitea repo",
	Args:  cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		name := args[0]

		cfg, err := loadConfig()
		if err != nil {
			return err
		}

		// 1. Create local folder
		if err := os.MkdirAll(name, 0755); err != nil {
			return fmt.Errorf("creating folder: %w", err)
		}
		fmt.Println("Created folder:", name)

		// 2. git init with main as the default branch
		if err := runGit(name, "init", "-b", "main"); err != nil {
			// Older git (<2.28) doesn't support -b; fall back
			if err2 := runGit(name, "init"); err2 != nil {
				return err2
			}
		}

		// 3. Create repo on Gitea via API
		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)

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

		// 5. Initial commit
		readmePath := filepath.Join(name, "README.md")
		if err := os.WriteFile(readmePath, []byte("# "+name+"\n"), 0644); err != nil {
			return fmt.Errorf("writing README: %w", err)
		}
		if err := runGit(name, "add", "."); err != nil {
			return err
		}
		if err := runGit(name, "commit", "-m", "Initial commit"); err != nil {
			return err
		}

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

		fmt.Printf("\nDone! cd %s  — your repo is live at %s\n", name, repo.HTMLURL)
		return nil
	},
}

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