package main

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

var sourceOrder = []string{
	filepath.Join("internal", "web", "ui", "base.css"),
	filepath.Join("internal", "web", "ui", "catalog", "catalog.css"),
	filepath.Join("internal", "web", "ui", "button.css"),
	filepath.Join("internal", "web", "ui", "badge.css"),
	filepath.Join("internal", "web", "ui", "icon-button.css"),
	filepath.Join("internal", "web", "ui", "input.css"),
	filepath.Join("internal", "web", "ui", "select.css"),
	filepath.Join("internal", "web", "ui", "textarea.css"),
	filepath.Join("internal", "web", "ui", "form-field.css"),
	filepath.Join("internal", "web", "ui", "modal.css"),
	filepath.Join("internal", "web", "ui", "table.css"),
	filepath.Join("internal", "web", "ui", "empty-state.css"),
	filepath.Join("internal", "web", "ui", "card.css"),
	filepath.Join("internal", "web", "ui", "spacing.css"),
	filepath.Join("internal", "web", "ui", "app.css"),
}

func main() {
	output := flag.String("out", filepath.Join("static", "styles.css"), "output stylesheet path")
	flag.Parse()

	if err := generateStyles(sourceOrder, *output); err != nil {
		fmt.Fprintf(os.Stderr, "build styles: %v\n", err)
		os.Exit(1)
	}
}

func generateStyles(sourcePaths []string, outputPath string) error {
	var buf bytes.Buffer
	buf.WriteString("/* Code generated by cmd/buildstyles; DO NOT EDIT. */\n\n")

	for i, path := range sourcePaths {
		body, err := os.ReadFile(path)
		if err != nil {
			return fmt.Errorf("read %s: %w", path, err)
		}

		buf.WriteString("/* Source: ")
		buf.WriteString(filepath.ToSlash(path))
		buf.WriteString(" */\n")
		buf.Write(bytes.TrimSpace(body))
		buf.WriteByte('\n')
		if i < len(sourcePaths)-1 {
			buf.WriteByte('\n')
		}
	}

	if err := os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
		return fmt.Errorf("mkdir output dir: %w", err)
	}
	if err := os.WriteFile(outputPath, buf.Bytes(), 0o644); err != nil {
		return fmt.Errorf("write %s: %w", outputPath, err)
	}
	return nil
}
