package commands

import (
	"fmt"
	"os/exec"
	"os"
	"time"
	"path/filepath"
	"datasmith/utils"
	"datasmith/templates"
)

func InitProject(name string, dbType string) {
	utils.PromptIfEmpty(&name, "Enter the name of the project: ")
	slug := utils.Slugify(name)

	// Check if datasmith.yaml already exists in the directory
	configFilePath := filepath.Join(slug, "datasmith.yaml")
	if _, err := os.Stat(configFilePath); err == nil {
		fmt.Printf("Error: A datasmith.yaml file already exists in the directory '%s'. Initialization aborted.\n", slug)
		return
	} else if !os.IsNotExist(err) {
		fmt.Printf("Error checking datasmith.yaml file: %v\n", err)
		return
	}


	if dbType == "" {
		dbType = promptForDbType()
	}

	fmt.Printf("Initializing new project structure in '%s' with database type '%s'\n", slug, dbType)

	// Create project directories
	createProjectDirs(slug)

	// Create datasmith.yaml file from template
	createConfigFile(slug, name, dbType)

	// Create an empty database.dbml file
	createDBMLFile(slug)

	// Create LICENSE.md file from template
	createLicenseFile(slug, name)

	// TODO: copy base files from https://gitlab.ard.de/br/buzzboard/database/-/tree/develop?ref_type=heads
	/*
		- .gitignore
		- .dockerignore
		- .sqlfluff (by database type)
		- Containerfile (by database type)
		- README.md
		- import-sql.sh (by database type)
		- .gilab-ci.yml (by database type) (also import tests from blessing of the day)
		- k8s/deployment.template.yaml
		- k8s/service.template.yaml
		- k8s/persistentVolume.template.yaml
		- k8s/persistentVolumeClaim.template.yaml
		- sql/database.sql (by database type)
	*/

	fmt.Printf("Initialized new project structure in '%s'\n", slug)

	fmt.Println("Initializing Git repository...")
	cmd := exec.Command("git", "init", slug)
	cmd.Run()
	
}

// promptForDbType prompts the user to select a database type
func promptForDbType() string {
	options := []utils.MenuOption{
		{Display: "MySQL (default)", Value: "mysql"},
		{Display: "PostgreSQL", Value: "postgres"},
	}

	dbType, err := utils.SelectMenu(options, "Select database type:")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	return dbType
}

// createProjectDirs creates the necessary project directories
func createProjectDirs(projectName string) {
	dirs := []string{"k8s", "sql"}

	for _, dir := range dirs {
		path := filepath.Join(projectName, dir)
		if err := os.MkdirAll(path, os.ModePerm); err != nil {
			fmt.Printf("Error creating directory '%s': %v\n", path, err)
		} else {
			fmt.Printf("Created directory: %s\n", path)
		}
	}
}

// createConfigFile creates the datasmith.yaml file from template
func createConfigFile(projectDir, projectName, dbType string) {
	data := map[string]interface{}{
		"Name":      projectName,
		"CreatedAt": time.Now().Format(time.RFC3339),
		"DbType":    dbType,
	}

	err := templates.CreateFileFromTemplate(projectDir, "", "datasmith.yaml", "datasmith.yaml", data)
	if err != nil {
		fmt.Printf("Error creating datasmith.yaml file: %v\n", err)
	} else {
		fmt.Printf("Created file: %s/datasmith.yaml\n", projectDir)
	}
}

// createDBMLFile creates an empty database.dbml file in the project directory
func createDBMLFile(projectDir string) {
	dbmlFilePath := filepath.Join(projectDir, "database.dbml")
	file, err := os.Create(dbmlFilePath)
	if err != nil {
		fmt.Printf("Error creating database.dbml file: %v\n", err)
		return
	}
	defer file.Close()

	fmt.Printf("Created file: %s/database.dbml\n", projectDir)
}

// createLicenseFile creates the LICENSE.md file from template
func createLicenseFile(projectDir, projectName string) {
	data := map[string]interface{}{
		"Name": projectName,
		"Year": time.Now().Year(),
	}

	err := templates.CreateFileFromTemplate(projectDir, "", "LICENSE.md", "LICENSE.md", data)
	if err != nil {
		fmt.Printf("Error creating LICENSE.md file: %v\n", err)
	} else {
		fmt.Printf("Created file: %s/LICENSE.md\n", projectDir)
	}
}

// Help returns the help information for the init command
func InitHelp() string {
	return "init [name] [--type mysql|postgres] : Create a new project with the specified name and database type."
}