package sdlc

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

// Init creates the .sdlc/ directory structure and default files.
func Init(root, projectName string) error {
	sdlcRoot := SDLCRoot(root)

	// Check if already initialized
	if _, err := os.Stat(sdlcRoot); err == nil {
		return fmt.Errorf("already initialized: %s exists", sdlcRoot)
	}

	// Create .sdlc/ and all subdirectories
	for _, dir := range SubDirs() {
		dirPath := filepath.Join(sdlcRoot, dir)
		if err := os.MkdirAll(dirPath, 0o755); err != nil {
			return fmt.Errorf("create directory %s: %w", dir, err)
		}
	}

	// Write default state
	state := DefaultState(projectName)
	if err := state.Save(root); err != nil {
		return fmt.Errorf("write default state: %w", err)
	}

	// Write default config
	config := DefaultConfig(projectName)
	if err := config.Save(root); err != nil {
		return fmt.Errorf("write default config: %w", err)
	}

	return nil
}

// IsInitialized returns true if the .sdlc/ directory exists.
func IsInitialized(root string) bool {
	info, err := os.Stat(SDLCRoot(root))
	return err == nil && info.IsDir()
}
