package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	
	"gitea.deepblack.cloud/chorus/bubble/api"
	"gitea.deepblack.cloud/chorus/bubble/backbeat"
	"gitea.deepblack.cloud/chorus/bubble/storage"
)

func main() {
	// --- Storage Initialization ---
	dbPath := getEnvOrDefault("BUBBLE_DB_PATH", "./bubble.db")

	// Initialize the SQLite store.
	store, err := storage.NewSQLiteStore(dbPath)
	if err != nil {
		log.Fatalf("Failed to initialize sqlite store: %v", err)
	}
	// defer store.DB.Close() // Close the DB when the application exits

	fmt.Println("SQLite store initialized successfully.")

	// --- BACKBEAT Integration ---
	fmt.Println("🥁 Initializing BACKBEAT integration...")
	backbeatIntegration := backbeat.NewBackbeatIntegration("bubble-cluster", "bubble-decision-agent", 2) // 2 BPM
	
	// Connect to BACKBEAT infrastructure
	natsURL := getEnvOrDefault("BACKBEAT_NATS_URL", "nats://backbeat-nats:4222")
	if err := backbeatIntegration.Connect(natsURL); err != nil {
		log.Printf("⚠️ Failed to connect to BACKBEAT: %v", err)
		log.Println("🔄 Continuing without BACKBEAT integration...")
	} else {
		fmt.Println("✅ BACKBEAT integration initialized")
	}

	// --- API Server Initialization ---
	server := api.NewServer(store)
	server.SetBackbeatIntegration(backbeatIntegration)

	// Setup graceful shutdown
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	
	go func() {
		<-c
		fmt.Println("\n🛑 Shutting down BUBBLE Decision Agent...")
		backbeatIntegration.Close()
		os.Exit(0)
	}()

	// Start the server.
	port := getEnvOrDefault("BUBBLE_PORT", "8080")
	fmt.Printf("🚀 Starting BUBBLE Decision Agent on port %s...\n", port)
	fmt.Printf("📊 BACKBEAT timing integration: %s\n", getBoolString(backbeatIntegration != nil))
	fmt.Printf("🌐 API endpoints:\n")
	fmt.Printf("   POST /decision/bundle - Generate decision bundles with timing\n")
	fmt.Printf("   GET  /backbeat/metrics - View BACKBEAT metrics\n")
	fmt.Printf("   GET  /backbeat/operations - View active operations\n")
	
	if err := server.Start(":" + port); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

// getEnvOrDefault returns environment variable value or default if not set
func getEnvOrDefault(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// getBoolString returns a human-readable string for boolean values
func getBoolString(b bool) string {
	if b {
		return "enabled"
	}
	return "disabled"
}