package cli

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

func Run(args []string) error {
	if len(args) == 0 {
		printUsage()
		return nil
	}

	root, err := findProjectRoot()
	if err != nil {
		return err
	}

	switch args[0] {
	case "init":
		return runInit(root, args[1:])
	case "posts":
		return runPosts(root, args[1:])
	case "tags":
		return runTags(root, args[1:])
	case "db":
		return runDB(root, args[1:])
	case "config":
		return runConfig(root, args[1:])
	case "build":
		return runBuild(root, args[1:])
	case "serve":
		return runServe(root, args[1:])
	case "dev":
		return runDev(root, args[1:])
	case "help", "-h", "--help":
		printUsage()
		return nil
	default:
		return fmt.Errorf("unknown command %q", args[0])
	}
}

func runInit(root string, args []string) error {
	fs := flag.NewFlagSet("init", flag.ContinueOnError)
	fs.SetOutput(os.Stderr)
	if err := fs.Parse(args); err != nil {
		return err
	}

	dirs := []string{
		"config",
		defaultPostsDir,
		defaultAssetsDir,
		".osaet",
		defaultAstroDir,
		defaultBuildOutDir,
	}
	for _, dir := range dirs {
		if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil {
			return err
		}
	}

	if err := writeFileIfMissing(filepath.Join(root, "config/site.yaml"), defaultSiteConfig()); err != nil {
		return err
	}
	if err := writeFileIfMissing(filepath.Join(root, "config/local.example.yaml"), defaultLocalExampleConfig()); err != nil {
		return err
	}

	fmt.Println("initialized local project structure")
	return nil
}

func printUsage() {
	fmt.Print(`osaetctl manages local blog content and static builds.

Usage:
  osaetctl init
  osaetctl posts slug --title "My Post" [--summary "..."]
  osaetctl posts new --title "My Post" [--slug my-post|--no-ai-slug] [--tag go] [--summary "..."] [--status draft]
  osaetctl posts list [--status draft|published]
  osaetctl posts show <slug>
  osaetctl posts publish <slug>
  osaetctl posts unpublish <slug>
  osaetctl posts delete <slug>
  osaetctl posts edit <slug>
  osaetctl posts import [--db .osaet/osaet.db]
  osaetctl posts export [--db .osaet/osaet.db] [--overwrite]
  osaetctl posts diff [--db .osaet/osaet.db]
  osaetctl posts sync [--from files|db|auto] [--yes] [--db .osaet/osaet.db]
  osaetctl tags list [--all]
  osaetctl db init [--path .osaet/osaet.db]
  osaetctl db status [--path .osaet/osaet.db]
  osaetctl config
  osaetctl dev [--host 127.0.0.1] [--port 4321]
  osaetctl build
  osaetctl serve [--host 127.0.0.1] [--port 4321] [--dir dist/site]
`)
}
