package main

import (
	"bytes"
	"context"
	"flag"
	"fmt"
	"html/template"
	"os"
	"path/filepath"

	"github.com/a-h/templ"

	"xtablo-backend/internal/web/ui/catalog"
)

func main() {
	outputDir := flag.String("output", filepath.Join("..", "docs", "design-system"), "output directory for generated catalog pages")
	flag.Parse()

	if err := GenerateSite(*outputDir); err != nil {
		fmt.Fprintf(os.Stderr, "generate design system: %v\n", err)
		os.Exit(1)
	}
}

func GenerateSite(outputDir string) error {
	if err := os.MkdirAll(outputDir, 0o755); err != nil {
		return fmt.Errorf("create output dir: %w", err)
	}

	if err := writePage(filepath.Join(outputDir, "index.html"), "Design System", catalog.CatalogIndex(catalog.Pages())); err != nil {
		return err
	}

	for _, page := range catalog.Pages() {
		target := filepath.Join(outputDir, page.Slug+".html")
		if err := writePage(target, page.Title, catalog.CatalogPage(page)); err != nil {
			return err
		}
	}

	return nil
}

func writePage(path string, title string, component templ.Component) error {
	body, err := renderComponent(component)
	if err != nil {
		return fmt.Errorf("render %s: %w", path, err)
	}

	doc := buildHTMLDocument(title, body)
	if err := os.WriteFile(path, []byte(doc), 0o644); err != nil {
		return fmt.Errorf("write %s: %w", path, err)
	}
	return nil
}

func renderComponent(component templ.Component) (template.HTML, error) {
	var buf bytes.Buffer
	if err := component.Render(context.Background(), &buf); err != nil {
		return "", err
	}
	return template.HTML(buf.String()), nil
}

func buildHTMLDocument(title string, body template.HTML) string {
	return fmt.Sprintf(`<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>%s</title>
  <link rel="stylesheet" href="../../go-backend/static/tailwind.css">
  <link rel="stylesheet" href="../../go-backend/static/styles.css">
</head>
<body>
%s
</body>
</html>
`, template.HTMLEscapeString(title), body)
}
