package cmd

import (
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"github.com/tidbcloud/investibook/cli/internal/api"
)

var filesCmd = &cobra.Command{
	Use:   "files",
	Short: "Browse workspace files",
}

var filesListCmd = &cobra.Command{
	Use:     "list",
	Short:   "List files in the workspace",
	Aliases: []string{"ls"},
	Run: func(cmd *cobra.Command, args []string) {
		client, cfg := mustClient()
		wsID := mustWorkspace(cfg)
		files, err := client.ListFiles(wsID)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		if len(files) == 0 {
			fmt.Println("No files in workspace.")
			return
		}
		printFileTree(files, "")
	},
}

func printFileTree(entries []api.FileEntry, indent string) {
	for i, e := range entries {
		isLast := i == len(entries)-1
		prefix := "|- "
		childIndent := indent + "|  "
		if isLast {
			prefix = "`- "
			childIndent = indent + "   "
		}
		name := e.Name
		if e.IsDir() {
			name += "/"
		}
		fmt.Printf("%s%s%s\n", indent, prefix, name)
		if e.IsDir() && len(e.Children) > 0 {
			printFileTree(e.Children, childIndent)
		}
	}
}

var filesGetCmd = &cobra.Command{
	Use:   "get <path>",
	Short: "Display file content",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		client, cfg := mustClient()
		wsID := mustWorkspace(cfg)
		content, err := client.GetFileContent(wsID, args[0])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		fmt.Print(content)
		if !strings.HasSuffix(content, "\n") {
			fmt.Println()
		}
	},
}

func init() {
	filesCmd.AddCommand(filesListCmd)
	filesCmd.AddCommand(filesGetCmd)
	rootCmd.AddCommand(filesCmd)
}
