package site

import (
	"bytes"
	"fmt"
	"html"
	"html/template"
	"io"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"time"

	"mkblog/internal/config"
	"mkblog/internal/content"
	"mkblog/internal/render"
	"mkblog/internal/shortcode"
)

type BuildOptions struct {
	ConfigPath    string
	ContentDir    string
	StaticDir     string
	ThemesDir     string
	ThemeOverride string
	OutDir        string
	IncludeDrafts bool
	IncludeFuture bool
}

type BuildResult struct {
	PostCount int
	TagCount  int
}

const (
	NotFoundPathPlaceholder  = "__MKBLOG_404_PATH__"
	NotFoundErrorPlaceholder = "__MKBLOG_404_ERROR__"
	NotFoundNoSuch           = "No such file or directory"
	NotFoundDenied           = "Permission denied"
)

type viewPost struct {
	Title   string
	Slug    string
	Date    time.Time
	Tags    []string
	URL     string
	Source  string
	Content template.HTML
}

type pageData struct {
	Site                config.Config
	PageTitle           string
	NowYear             int
	HomeDirSize         int
	HomeDirTime         time.Time
	BlogDirSize         int
	BlogDirTime         time.Time
	TagsDirSize         int
	TagsDirTime         time.Time
	TagDirSize          int
	TagDirTime          time.Time
	ArchivesDirSize     int
	ArchivesDirTime     time.Time
	ArchiveYearDirSize  int
	ArchiveYearDirTime  time.Time
	ArchiveMonthDirSize int
	ArchiveMonthDirTime time.Time
	Posts               []Post
	Post                viewPost
	Tag                 TagPage
	Tags                []TagPage
	StaticFiles         []StaticFileEntry
	ArchiveYear         ArchiveYear
	ArchiveMonth        ArchiveMonth
	YearArchives        []ArchiveYear
	NotFoundPath        string
	NotFoundError       string
}

func Build(opts BuildOptions) (BuildResult, error) {
	var result BuildResult

	cfg, err := loadConfig(opts)
	if err != nil {
		return result, err
	}

	if err := validateOutputDir(opts, cfg.Theme); err != nil {
		return result, err
	}

	posts, err := content.LoadPosts(opts.ContentDir)
	if err != nil {
		return result, err
	}

	now := time.Now()
	slugSet := map[string]string{}
	renderedPosts := make([]Post, 0, len(posts))
	listedPosts := make([]Post, 0, len(posts))
	for _, p := range posts {
		if p.Draft && !opts.IncludeDrafts {
			continue
		}
		if p.Date.After(now) && !opts.IncludeFuture {
			continue
		}
		if prev, ok := slugSet[p.Slug]; ok {
			return result, fmt.Errorf("duplicate slug %q in %s and %s", p.Slug, prev, p.Source)
		}
		slugSet[p.Slug] = p.Source
		if p.InferredMeta {
			log.Printf("warning: %s has no front matter; using inferred title=%q slug=%q date=%s", p.Source, p.Title, p.Slug, p.Date.Format(time.RFC3339))
		}

		expanded, err := shortcode.Expand(p.BodyMarkdown, opts.ContentDir)
		if err != nil {
			return result, fmt.Errorf("shortcode in %s: %w", p.Source, err)
		}
		htmlBody, err := render.MarkdownToHTML(expanded)
		if err != nil {
			return result, fmt.Errorf("render markdown %s: %w", p.Source, err)
		}

		post := Post{
			Title:     p.Title,
			Slug:      p.Slug,
			Date:      p.Date,
			ListTime:  combineListTime(p.Date, p.DateHasTime, p.FileModTime),
			SizeBytes: p.FileSize,
			Tags:      p.Tags,
			Draft:     p.Draft,
			Hidden:    p.Hidden,
			Source:    p.Source,
			BodyHTML:  htmlBody,
			URL:       "/blog/" + p.Slug + "/",
		}
		renderedPosts = append(renderedPosts, post)
		if !post.Hidden {
			listedPosts = append(listedPosts, post)
		}
	}

	sort.Slice(renderedPosts, func(i, j int) bool {
		return renderedPosts[i].Date.After(renderedPosts[j].Date)
	})
	sort.Slice(listedPosts, func(i, j int) bool {
		return listedPosts[i].Date.After(listedPosts[j].Date)
	})

	tags := buildTags(listedPosts)
	archives := buildArchives(listedPosts)
	staticFiles, err := collectFilesForListing(opts.ContentDir, opts.StaticDir)
	if err != nil {
		return result, err
	}

	if err := resetOutputDir(opts.OutDir); err != nil {
		return result, err
	}
	if err := copyTree(opts.StaticDir, opts.OutDir); err != nil {
		return result, err
	}
	themeAssets := filepath.Join(opts.ThemesDir, cfg.Theme, "assets")
	if _, err := os.Stat(themeAssets); err == nil {
		if err := copyTree(themeAssets, filepath.Join(opts.OutDir, "assets", "theme")); err != nil {
			return result, err
		}
	}
	if err := copyContentAssets(opts.ContentDir, opts.StaticDir, opts.OutDir); err != nil {
		return result, err
	}

	tpl, err := loadTemplates(opts.ThemesDir, cfg.Theme)
	if err != nil {
		return result, err
	}

	if err := renderHome(tpl, cfg, opts.OutDir, listedPosts, tags, staticFiles, archives); err != nil {
		return result, err
	}
	if err := renderBlogRoot(tpl, cfg, opts.OutDir, listedPosts, tags, staticFiles, archives); err != nil {
		return result, err
	}
	if err := renderTagsIndex(tpl, cfg, opts.OutDir, listedPosts, tags, staticFiles); err != nil {
		return result, err
	}
	if err := renderArchivesIndex(tpl, cfg, opts.OutDir, listedPosts, archives, staticFiles); err != nil {
		return result, err
	}
	if err := renderNotFoundPage(tpl, cfg, opts.OutDir, listedPosts, tags, archives, staticFiles); err != nil {
		return result, err
	}
	for _, p := range renderedPosts {
		if err := renderPostPage(tpl, cfg, opts.OutDir, p, listedPosts, tags, archives, staticFiles); err != nil {
			return result, err
		}
	}
	for _, t := range tags {
		if err := renderTagPage(tpl, cfg, opts.OutDir, t, listedPosts, tags, staticFiles); err != nil {
			return result, err
		}
	}
	for _, y := range archives {
		if err := renderYearArchive(tpl, cfg, opts.OutDir, y, listedPosts, archives, staticFiles); err != nil {
			return result, err
		}
		for _, m := range y.Months {
			if err := renderMonthArchive(tpl, cfg, opts.OutDir, m, listedPosts, y, staticFiles); err != nil {
				return result, err
			}
		}
	}

	result.PostCount = len(renderedPosts)
	result.TagCount = len(tags)
	return result, nil
}

func renderNotFoundPage(tpl *template.Template, cfg config.Config, outDir string, posts []Post, tags []TagPage, archives []ArchiveYear, staticFiles []StaticFileEntry) error {
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	return renderTemplateToPath(tpl, "404", filepath.Join(outDir, "404.html"), pageData{
		Site:          cfg,
		PageTitle:     "404 | " + cfg.Title,
		NowYear:       time.Now().Year(),
		HomeDirSize:   homeSize,
		HomeDirTime:   homeTime,
		Posts:         posts,
		Tags:          tags,
		StaticFiles:   staticFiles,
		YearArchives:  archives,
		NotFoundPath:  NotFoundPathPlaceholder,
		NotFoundError: NotFoundErrorPlaceholder,
	})
}

func loadTemplates(themesDir, theme string) (*template.Template, error) {
	layoutGlob := filepath.Join(themesDir, theme, "layouts", "*.html")
	partialGlob := filepath.Join(themesDir, theme, "partials", "*.html")

	layoutFiles, err := filepath.Glob(layoutGlob)
	if err != nil || len(layoutFiles) == 0 {
		return nil, fmt.Errorf("load theme layouts: no files for %s", layoutGlob)
	}
	partialFiles, _ := filepath.Glob(partialGlob)

	files := append(layoutFiles, partialFiles...)
	tpl, err := template.New("site").Funcs(template.FuncMap{
		"formatDate":     func(t time.Time) string { return t.Format("2006-01-02") },
		"tagSlug":        content.Slugify,
		"lsDate":         lsDate,
		"lsTime":         lsTime,
		"lsSize":         lsSize,
		"dirLinks":       dirLinks,
		"fileLinks":      fileLinks,
		"latestPostTime": latestListTime,
		"excerpt":        excerptHTML,
	}).ParseFiles(files...)
	if err != nil {
		return nil, fmt.Errorf("parse templates: %w", err)
	}
	return tpl, nil
}

var (
	paragraphRE              = regexp.MustCompile(`(?is)<p\b[^>]*>(.*?)</p>`)
	tagRE                    = regexp.MustCompile(`(?s)<[^>]+>`)
	spaceBeforePunctuationRE = regexp.MustCompile(`\s+([.,!?;:])`)
)

func excerptHTML(body string) string {
	paragraphs := paragraphRE.FindAllStringSubmatch(body, 4)
	parts := make([]string, 0, len(paragraphs))
	for _, match := range paragraphs {
		plain := html.UnescapeString(tagRE.ReplaceAllString(match[1], " "))
		if plain = strings.Join(strings.Fields(plain), " "); plain != "" {
			plain = spaceBeforePunctuationRE.ReplaceAllString(plain, "$1")
			parts = append(parts, plain)
		}
	}
	plain := strings.Join(parts, " ")
	if plain == "" {
		plain = strings.Join(strings.Fields(html.UnescapeString(tagRE.ReplaceAllString(body, " "))), " ")
		plain = spaceBeforePunctuationRE.ReplaceAllString(plain, "$1")
	}

	runes := []rune(plain)
	const maxRunes = 240
	limit := len(runes)
	if limit > maxRunes {
		limit = maxRunes
	}
	sentences := 0
	for i := 0; i < limit; i++ {
		if runes[i] != '.' && runes[i] != '!' && runes[i] != '?' {
			continue
		}
		if i+1 < len(runes) && runes[i+1] != ' ' {
			continue
		}
		sentences++
		if sentences == 2 {
			return strings.TrimSpace(string(runes[:i+1]))
		}
	}
	if len(runes) <= maxRunes {
		return plain
	}
	cut := strings.LastIndex(string(runes[:maxRunes]), " ")
	if cut < 1 {
		cut = maxRunes
	}
	return strings.TrimSpace(string(runes[:cut])) + "…"
}

func renderHome(tpl *template.Template, cfg config.Config, outDir string, posts []Post, tags []TagPage, staticFiles []StaticFileEntry, archives []ArchiveYear) error {
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	return renderTemplateToPath(tpl, "index", filepath.Join(outDir, "index.html"), pageData{
		Site:         cfg,
		PageTitle:    cfg.Title,
		NowYear:      time.Now().Year(),
		HomeDirSize:  homeSize,
		HomeDirTime:  homeTime,
		Posts:        posts,
		Tags:         tags,
		StaticFiles:  staticFiles,
		YearArchives: archives,
	})
}

func renderTagsIndex(tpl *template.Template, cfg config.Config, outDir string, posts []Post, tags []TagPage, staticFiles []StaticFileEntry) error {
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	blogSize, blogTime := blogDirMeta(posts)
	tagsSize, tagsTime := tagsDirMeta(tags)
	return renderTemplateToPath(tpl, "tags", filepath.Join(outDir, "tags", "index.html"), pageData{
		Site:        cfg,
		PageTitle:   "Tags | " + cfg.Title,
		NowYear:     time.Now().Year(),
		HomeDirSize: homeSize,
		HomeDirTime: homeTime,
		BlogDirSize: blogSize,
		BlogDirTime: blogTime,
		TagsDirSize: tagsSize,
		TagsDirTime: tagsTime,
		Tags:        tags,
		StaticFiles: staticFiles,
	})
}

func renderBlogRoot(tpl *template.Template, cfg config.Config, outDir string, posts []Post, tags []TagPage, staticFiles []StaticFileEntry, archives []ArchiveYear) error {
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	blogSize, blogTime := blogDirMeta(posts)
	tagsSize, tagsTime := tagsDirMeta(tags)
	archivesSize, archivesTime := archivesDirMeta(archives)
	return renderTemplateToPath(tpl, "blog", filepath.Join(outDir, "blog", "index.html"), pageData{
		Site:            cfg,
		PageTitle:       "Blog | " + cfg.Title,
		NowYear:         time.Now().Year(),
		HomeDirSize:     homeSize,
		HomeDirTime:     homeTime,
		BlogDirSize:     blogSize,
		BlogDirTime:     blogTime,
		TagsDirSize:     tagsSize,
		TagsDirTime:     tagsTime,
		ArchivesDirSize: archivesSize,
		ArchivesDirTime: archivesTime,
		Posts:           posts,
		Tags:            tags,
		StaticFiles:     staticFiles,
		YearArchives:    archives,
	})
}

func renderArchivesIndex(tpl *template.Template, cfg config.Config, outDir string, posts []Post, archives []ArchiveYear, staticFiles []StaticFileEntry) error {
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	blogSize, blogTime := blogDirMeta(posts)
	archivesSize, archivesTime := archivesDirMeta(archives)
	return renderTemplateToPath(tpl, "archives", filepath.Join(outDir, "archives", "index.html"), pageData{
		Site:            cfg,
		PageTitle:       "Archives | " + cfg.Title,
		NowYear:         time.Now().Year(),
		HomeDirSize:     homeSize,
		HomeDirTime:     homeTime,
		BlogDirSize:     blogSize,
		BlogDirTime:     blogTime,
		ArchivesDirSize: archivesSize,
		ArchivesDirTime: archivesTime,
		YearArchives:    archives,
		StaticFiles:     staticFiles,
	})
}

func renderPostPage(tpl *template.Template, cfg config.Config, outDir string, p Post, posts []Post, tags []TagPage, archives []ArchiveYear, staticFiles []StaticFileEntry) error {
	path := filepath.Join(outDir, strings.TrimPrefix(p.URL, "/"), "index.html")
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	blogSize, blogTime := blogDirMeta(posts)
	tagsSize, tagsTime := tagsDirMeta(tags)
	archivesSize, archivesTime := archivesDirMeta(archives)
	return renderTemplateToPath(tpl, "post", path, pageData{
		Site:            cfg,
		PageTitle:       p.Title + " | " + cfg.Title,
		NowYear:         time.Now().Year(),
		HomeDirSize:     homeSize,
		HomeDirTime:     homeTime,
		BlogDirSize:     blogSize,
		BlogDirTime:     blogTime,
		TagsDirSize:     tagsSize,
		TagsDirTime:     tagsTime,
		ArchivesDirSize: archivesSize,
		ArchivesDirTime: archivesTime,
		Posts:           posts,
		Tags:            tags,
		StaticFiles:     staticFiles,
		YearArchives:    archives,
		Post: viewPost{
			Title:   p.Title,
			Slug:    p.Slug,
			Date:    p.Date,
			Tags:    p.Tags,
			URL:     p.URL,
			Source:  p.Source,
			Content: template.HTML(p.BodyHTML),
		},
	})
}

func renderTagPage(tpl *template.Template, cfg config.Config, outDir string, tag TagPage, posts []Post, allTags []TagPage, staticFiles []StaticFileEntry) error {
	path := filepath.Join(outDir, strings.TrimPrefix(tag.URL, "/"), "index.html")
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	blogSize, blogTime := blogDirMeta(posts)
	tagSize, tagTime := tagDirMeta(tag)
	tagsSize, tagsTime := tagsDirMeta(allTags)
	return renderTemplateToPath(tpl, "tag", path, pageData{
		Site:        cfg,
		PageTitle:   "Tag: " + tag.Name + " | " + cfg.Title,
		NowYear:     time.Now().Year(),
		HomeDirSize: homeSize,
		HomeDirTime: homeTime,
		BlogDirSize: blogSize,
		BlogDirTime: blogTime,
		TagsDirSize: tagsSize,
		TagsDirTime: tagsTime,
		TagDirSize:  tagSize,
		TagDirTime:  tagTime,
		Tags:        allTags,
		Tag:         tag,
		StaticFiles: staticFiles,
	})
}

func renderYearArchive(tpl *template.Template, cfg config.Config, outDir string, year ArchiveYear, posts []Post, allYears []ArchiveYear, staticFiles []StaticFileEntry) error {
	path := filepath.Join(outDir, strings.TrimPrefix(year.URL, "/"), "index.html")
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	blogSize, blogTime := blogDirMeta(posts)
	yearSize, yearTime := archiveYearDirMeta(year)
	archivesSize, archivesTime := archivesDirMeta(allYears)
	return renderTemplateToPath(tpl, "archive_year", path, pageData{
		Site:               cfg,
		PageTitle:          fmt.Sprintf("Archive %d | %s", year.Year, cfg.Title),
		NowYear:            time.Now().Year(),
		HomeDirSize:        homeSize,
		HomeDirTime:        homeTime,
		BlogDirSize:        blogSize,
		BlogDirTime:        blogTime,
		ArchiveYearDirSize: yearSize,
		ArchiveYearDirTime: yearTime,
		ArchivesDirSize:    archivesSize,
		ArchivesDirTime:    archivesTime,
		ArchiveYear:        year,
		YearArchives:       allYears,
		StaticFiles:        staticFiles,
	})
}

func renderMonthArchive(tpl *template.Template, cfg config.Config, outDir string, month ArchiveMonth, posts []Post, parentYear ArchiveYear, staticFiles []StaticFileEntry) error {
	path := filepath.Join(outDir, strings.TrimPrefix(month.URL, "/"), "index.html")
	homeSize, homeTime := homeDirMeta(posts, staticFiles)
	blogSize, blogTime := blogDirMeta(posts)
	monthSize, monthTime := archiveMonthDirMeta(month)
	yearSize, yearTime := archiveYearDirMeta(parentYear)
	return renderTemplateToPath(tpl, "archive_month", path, pageData{
		Site:                cfg,
		PageTitle:           fmt.Sprintf("Archive %04d-%02d | %s", month.Year, month.Month, cfg.Title),
		NowYear:             time.Now().Year(),
		HomeDirSize:         homeSize,
		HomeDirTime:         homeTime,
		BlogDirSize:         blogSize,
		BlogDirTime:         blogTime,
		ArchiveMonthDirSize: monthSize,
		ArchiveMonthDirTime: monthTime,
		ArchiveYearDirSize:  yearSize,
		ArchiveYearDirTime:  yearTime,
		ArchiveYear:         parentYear,
		ArchiveMonth:        month,
		StaticFiles:         staticFiles,
	})
}

func renderTemplateToPath(tpl *template.Template, tmplName, outputPath string, data pageData) error {
	if err := os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
		return fmt.Errorf("mkdir %s: %w", outputPath, err)
	}
	f, err := os.Create(outputPath)
	if err != nil {
		return fmt.Errorf("create %s: %w", outputPath, err)
	}
	defer f.Close()

	if err := tpl.ExecuteTemplate(f, tmplName, data); err != nil {
		return fmt.Errorf("render template %s -> %s: %w", tmplName, outputPath, err)
	}
	return nil
}

func buildTags(posts []Post) []TagPage {
	groups := map[string][]Post{}
	names := map[string]string{}
	for _, p := range posts {
		for _, tag := range p.Tags {
			slug := content.Slugify(tag)
			if slug == "" {
				continue
			}
			groups[slug] = append(groups[slug], p)
			names[slug] = tag
		}
	}

	out := make([]TagPage, 0, len(groups))
	for slug, items := range groups {
		sort.Slice(items, func(i, j int) bool { return items[i].Date.After(items[j].Date) })
		latest := latestListTime(items)
		out = append(out, TagPage{
			Name:           names[slug],
			Slug:           slug,
			URL:            "/tags/" + slug + "/",
			Posts:          items,
			LatestListTime: latest,
			Count:          len(items),
		})
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
	return out
}

func buildArchives(posts []Post) []ArchiveYear {
	yearMap := map[int]*ArchiveYear{}
	monthMap := map[string]*ArchiveMonth{}

	for _, p := range posts {
		y := p.Date.Year()
		m := int(p.Date.Month())

		yr, ok := yearMap[y]
		if !ok {
			yr = &ArchiveYear{Year: y, URL: fmt.Sprintf("/archives/%04d/", y)}
			yearMap[y] = yr
		}
		yr.Posts = append(yr.Posts, p)

		key := fmt.Sprintf("%04d-%02d", y, m)
		mo, ok := monthMap[key]
		if !ok {
			mo = &ArchiveMonth{Year: y, Month: m, URL: fmt.Sprintf("/archives/%04d/%02d/", y, m)}
			monthMap[key] = mo
			yr.Months = append(yr.Months, *mo)
		}
		mo.Posts = append(mo.Posts, p)
	}

	out := make([]ArchiveYear, 0, len(yearMap))
	for _, yr := range yearMap {
		sort.Slice(yr.Posts, func(i, j int) bool { return yr.Posts[i].Date.After(yr.Posts[j].Date) })
		yr.Count = len(yr.Posts)
		yr.LatestListTime = latestListTime(yr.Posts)
		months := make([]ArchiveMonth, 0)
		for _, m := range yr.Months {
			key := fmt.Sprintf("%04d-%02d", m.Year, m.Month)
			actual := monthMap[key]
			sort.Slice(actual.Posts, func(i, j int) bool { return actual.Posts[i].Date.After(actual.Posts[j].Date) })
			actual.Count = len(actual.Posts)
			actual.LatestListTime = latestListTime(actual.Posts)
			months = append(months, *actual)
		}
		sort.Slice(months, func(i, j int) bool {
			if months[i].Year == months[j].Year {
				return months[i].Month > months[j].Month
			}
			return months[i].Year > months[j].Year
		})
		yr.Months = months
		out = append(out, *yr)
	}

	sort.Slice(out, func(i, j int) bool { return out[i].Year > out[j].Year })
	return out
}

func collectFilesForListing(contentDir, staticDir string) ([]StaticFileEntry, error) {
	contentFilesDir := filepath.Join(contentDir, "files")
	staticFilesDir := filepath.Join(staticDir, "files")

	contentExists, err := isDir(contentFilesDir)
	if err != nil {
		return nil, err
	}
	staticExists, err := isDir(staticFilesDir)
	if err != nil {
		return nil, err
	}

	switch {
	case contentExists:
		if staticExists {
			log.Printf("warning: static/files is deprecated; using content/files")
		}
		return collectFileEntries(contentFilesDir, "/files/", "content files")
	case staticExists:
		log.Printf("warning: static/files is deprecated; move files to content/files")
		return collectFileEntries(staticFilesDir, "/files/", "static files")
	default:
		return nil, nil
	}
}

func collectFileEntries(dir, urlPrefix, sourceLabel string) ([]StaticFileEntry, error) {
	entries, err := os.ReadDir(dir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, fmt.Errorf("read %s dir %s: %w", sourceLabel, dir, err)
	}

	out := make([]StaticFileEntry, 0, len(entries))
	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}
		info, err := entry.Info()
		if err != nil {
			return nil, fmt.Errorf("stat %s file %s: %w", sourceLabel, entry.Name(), err)
		}
		out = append(out, StaticFileEntry{
			Name:      entry.Name(),
			URL:       urlPrefix + entry.Name(),
			SizeBytes: info.Size(),
			ModTime:   info.ModTime(),
		})
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
	return out, nil
}

func Render404HTML(page []byte, pathValue, errValue string) []byte {
	replaced := bytes.ReplaceAll(page, []byte(NotFoundPathPlaceholder), []byte(template.HTMLEscapeString(pathValue)))
	replaced = bytes.ReplaceAll(replaced, []byte(NotFoundErrorPlaceholder), []byte(template.HTMLEscapeString(errValue)))
	return replaced
}

func copyContentAssets(contentDir, staticDir, outDir string) error {
	contentFilesDir := filepath.Join(contentDir, "files")
	staticFilesDir := filepath.Join(staticDir, "files")
	contentCastsDir := filepath.Join(contentDir, "casts")
	staticCastsDir := filepath.Join(staticDir, "casts")

	if err := copyPreferredAssetDir("files", contentFilesDir, staticFilesDir, filepath.Join(outDir, "files")); err != nil {
		return err
	}
	if err := copyPreferredAssetDir("casts", contentCastsDir, staticCastsDir, filepath.Join(outDir, "casts")); err != nil {
		return err
	}
	return nil
}

func copyPreferredAssetDir(name, preferredDir, legacyDir, outDir string) error {
	preferredExists, err := isDir(preferredDir)
	if err != nil {
		return err
	}
	legacyExists, err := isDir(legacyDir)
	if err != nil {
		return err
	}

	if preferredExists {
		if legacyExists {
			log.Printf("warning: static/%s is deprecated; using content/%s", name, name)
		}
		if err := os.RemoveAll(outDir); err != nil {
			return fmt.Errorf("remove output %s dir %s: %w", name, outDir, err)
		}
		if err := copyTree(preferredDir, outDir); err != nil {
			return fmt.Errorf("copy content/%s to output: %w", name, err)
		}
		return nil
	}
	if legacyExists {
		log.Printf("warning: static/%s is deprecated; move assets to content/%s", name, name)
	}
	return nil
}

func isDir(path string) (bool, error) {
	st, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, fmt.Errorf("stat %s: %w", path, err)
	}
	return st.IsDir(), nil
}

func lsDate(t time.Time) string {
	if t.IsZero() {
		return ""
	}
	return t.Format("2 Jan 2006")
}

func lsTime(t time.Time) string {
	if t.IsZero() {
		return ""
	}
	return t.Format("15:04")
}

func lsSize(size any) string {
	switch v := size.(type) {
	case int:
		return fmt.Sprintf("%d", v)
	case int64:
		return fmt.Sprintf("%d", v)
	case uint64:
		return fmt.Sprintf("%d", v)
	default:
		return fmt.Sprintf("%v", v)
	}
}

func combineListTime(date time.Time, dateHasTime bool, mod time.Time) time.Time {
	if dateHasTime {
		return date
	}
	if mod.IsZero() {
		return date
	}
	return time.Date(date.Year(), date.Month(), date.Day(), mod.Hour(), mod.Minute(), mod.Second(), 0, mod.Location())
}

func latestListTime(posts []Post) time.Time {
	var latest time.Time
	for _, p := range posts {
		if p.ListTime.After(latest) {
			latest = p.ListTime
		}
	}
	return latest
}

func homeDirMeta(posts []Post, files []StaticFileEntry) (int, time.Time) {
	latest := latestTime(latestListTime(posts), latestStaticTime(files))
	return 1 + len(files), latest
}

func blogDirMeta(posts []Post) (int, time.Time) {
	return 4 + len(posts), latestListTime(posts)
}

func tagsDirMeta(tags []TagPage) (int, time.Time) {
	latest := time.Time{}
	for _, t := range tags {
		latest = latestTime(latest, t.LatestListTime)
	}
	return 2 + len(tags), latest
}

func tagDirMeta(tag TagPage) (int, time.Time) {
	return 2 + len(tag.Posts), latestListTime(tag.Posts)
}

func archivesDirMeta(years []ArchiveYear) (int, time.Time) {
	latest := time.Time{}
	for _, y := range years {
		latest = latestTime(latest, y.LatestListTime)
	}
	return 2 + len(years), latest
}

func archiveYearDirMeta(year ArchiveYear) (int, time.Time) {
	return 2 + len(year.Months) + len(year.Posts), year.LatestListTime
}

func archiveMonthDirMeta(month ArchiveMonth) (int, time.Time) {
	return 2 + len(month.Posts), month.LatestListTime
}

func latestStaticTime(files []StaticFileEntry) time.Time {
	latest := time.Time{}
	for _, f := range files {
		if f.ModTime.After(latest) {
			latest = f.ModTime
		}
	}
	return latest
}

func latestTime(a, b time.Time) time.Time {
	if b.After(a) {
		return b
	}
	return a
}

func dirLinks(childDirs int) int {
	return 2 + childDirs
}

func fileLinks() int {
	return 1
}

func resetOutputDir(path string) error {
	if err := os.RemoveAll(path); err != nil {
		return fmt.Errorf("reset output remove %s: %w", path, err)
	}
	if err := os.MkdirAll(path, 0o755); err != nil {
		return fmt.Errorf("reset output create %s: %w", path, err)
	}
	return nil
}

func validateOutputDir(opts BuildOptions, theme string) error {
	protectedRoots := []struct {
		label string
		path  string
	}{
		{label: "content directory", path: opts.ContentDir},
		{label: "static directory", path: opts.StaticDir},
		{label: "theme directory", path: filepath.Join(opts.ThemesDir, theme)},
	}

	for _, root := range protectedRoots {
		if inside, err := pathEqualOrInside(opts.OutDir, root.path); err != nil {
			return err
		} else if inside {
			return fmt.Errorf("invalid output directory: --out %s is equal to or inside %s %s", opts.OutDir, root.label, root.path)
		}
	}
	return nil
}

func pathEqualOrInside(path, root string) (bool, error) {
	absPath, err := filepath.Abs(path)
	if err != nil {
		return false, fmt.Errorf("resolve output path %s: %w", path, err)
	}
	absRoot, err := filepath.Abs(root)
	if err != nil {
		return false, fmt.Errorf("resolve input path %s: %w", root, err)
	}
	rel, err := filepath.Rel(absRoot, absPath)
	if err != nil {
		return false, fmt.Errorf("compare output path %s with input path %s: %w", absPath, absRoot, err)
	}
	return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))), nil
}

func copyTree(src, dst string) error {
	if _, err := os.Stat(src); err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return fmt.Errorf("stat source %s: %w", src, err)
	}

	return filepath.WalkDir(src, func(path string, d os.DirEntry, err error) error {
		if err != nil {
			return err
		}
		rel, err := filepath.Rel(src, path)
		if err != nil {
			return err
		}
		target := filepath.Join(dst, rel)
		if d.IsDir() {
			return os.MkdirAll(target, 0o755)
		}
		if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
			return err
		}
		return copyFile(path, target)
	})
}

func copyFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return fmt.Errorf("open %s: %w", src, err)
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return fmt.Errorf("create %s: %w", dst, err)
	}
	defer out.Close()

	if _, err := io.Copy(out, in); err != nil {
		return fmt.Errorf("copy %s -> %s: %w", src, dst, err)
	}
	if err := out.Chmod(fs.FileMode(0o644)); err != nil {
		return fmt.Errorf("chmod %s: %w", dst, err)
	}
	return nil
}
