package ui

import (
	"os"
	"path/filepath"

	"git.ourworld.tf/herocode/heroagent/pkg/servers/ui/routes" // Import the routes package
	"github.com/gofiber/fiber/v2"
	jetadapter "github.com/gofiber/template/jet/v2" // Aliased for clarity
)

// AppConfig holds the configuration for the UI application.
type AppConfig struct {
	// Any specific configurations can be added here later
}

// NewApp creates and configures a new Fiber application for the UI.
func NewApp(config AppConfig) *fiber.App {
	// Initialize Jet template engine
	// Using OSFileSystemLoader to load templates from the filesystem.
	// The path is relative to where the application is run.
	// Get current working directory and construct absolute path to views
	cwd, err := os.Getwd()
	if err != nil {
		panic("Failed to get current working directory: " + err.Error())
	}
	viewsPath := filepath.Join(cwd, "pkg", "servers", "ui", "views")

	// Validate that the views directory and key template files exist
	if _, err := os.Stat(viewsPath); os.IsNotExist(err) {
		panic("Views directory does not exist: " + viewsPath)
	}

	// Check for key template files
	baseLayoutPath := filepath.Join(viewsPath, "layouts", "base.jet")
	dashboardPath := filepath.Join(viewsPath, "pages", "dashboard.jet")
	navbarPath := filepath.Join(viewsPath, "components", "navbar.jet")
	sidebarPath := filepath.Join(viewsPath, "components", "sidebar.jet")

	requiredFiles := []string{baseLayoutPath, dashboardPath, navbarPath, sidebarPath}
	for _, filePath := range requiredFiles {
		if _, err := os.Stat(filePath); os.IsNotExist(err) {
			panic("Required template file does not exist: " + filePath)
		}
	}

	// Log the views path for debugging
	println("Views directory found at:", viewsPath)
	println("All required template files exist")

	// Create Fiber Jet adapter
	engine := jetadapter.New(viewsPath, ".jet")

	// Enable template reloading for development
	engine.Reload(true)

	// Create a new Fiber app with the configured Jet engine
	app := fiber.New(fiber.Config{
		Views: engine,
	})

	// Setup static file serving
	// Files in ./pkg/servers/ui/static will be accessible via /static URL path
	app.Static("/static", "./pkg/servers/ui/static")

	// Setup routes
	routes.SetupRoutes(app)

	return app
}
