package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"mkblog/internal/server"
	"mkblog/internal/site"
)

var version = "dev"

func main() {
	log.SetFlags(0)

	if len(os.Args) == 2 && os.Args[1] == "--version" {
		fmt.Println(version)
		return
	}

	if len(os.Args) < 2 {
		usage()
		os.Exit(2)
	}

	switch os.Args[1] {
	case "build":
		runBuild(os.Args[2:])
	case "serve":
		runServe(os.Args[2:])
	default:
		usage()
		os.Exit(2)
	}
}

func runBuild(args []string) {
	fs := flag.NewFlagSet("build", flag.ExitOnError)
	cfgPath := fs.String("config", "config.yaml", "path to site config yaml")
	contentDir := fs.String("content", "content", "content directory")
	staticDir := fs.String("static", "static", "static assets directory")
	themesDir := fs.String("themes", "themes", "themes directory")
	theme := fs.String("theme", "", "theme override")
	outDir := fs.String("out", "public", "output directory")
	includeDrafts := fs.Bool("include-drafts", false, "include draft posts")
	includeFuture := fs.Bool("include-future", false, "include future-dated posts")
	fs.Parse(args)

	res, err := site.Build(site.BuildOptions{
		ConfigPath:    *cfgPath,
		ContentDir:    *contentDir,
		StaticDir:     *staticDir,
		ThemesDir:     *themesDir,
		ThemeOverride: *theme,
		OutDir:        *outDir,
		IncludeDrafts: *includeDrafts,
		IncludeFuture: *includeFuture,
	})
	if err != nil {
		log.Fatalf("build failed: %v", err)
	}
	log.Printf("build complete: %d posts, %d tags", res.PostCount, res.TagCount)
}

func runServe(args []string) {
	fs := flag.NewFlagSet("serve", flag.ExitOnError)
	cfgPath := fs.String("config", "config.yaml", "path to site config yaml")
	contentDir := fs.String("content", "content", "content directory")
	staticDir := fs.String("static", "static", "static assets directory")
	themesDir := fs.String("themes", "themes", "themes directory")
	theme := fs.String("theme", "", "theme override")
	outDir := fs.String("out", "public", "output directory")
	includeDrafts := fs.Bool("include-drafts", false, "include draft posts")
	includeFuture := fs.Bool("include-future", false, "include future-dated posts")
	port := fs.Int("port", 1313, "local server port")
	watch := fs.Bool("watch", false, "watch for file changes and rebuild")
	fs.Parse(args)

	err := server.Serve(server.ServeOptions{
		Port:  *port,
		Watch: *watch,
		Build: site.BuildOptions{
			ConfigPath:    *cfgPath,
			ContentDir:    *contentDir,
			StaticDir:     *staticDir,
			ThemesDir:     *themesDir,
			ThemeOverride: *theme,
			OutDir:        *outDir,
			IncludeDrafts: *includeDrafts,
			IncludeFuture: *includeFuture,
		},
	})
	if err != nil {
		log.Fatalf("serve failed: %v", err)
	}
}

func usage() {
	fmt.Fprintf(os.Stderr, `mkblog - static site generator

Usage:
  mkblog --version
  mkblog build [flags]
  mkblog serve [flags]

`)
}
