package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"led-controller/config"
	"led-controller/controller"
	"led-controller/monitor"
)

func main() {
	cfgPath := flag.String("config", "/etc/led-controller/config.toml", "path to config file")
	flag.Parse()

	args := flag.Args()

	cfg, err := config.Load(*cfgPath)
	if err != nil {
		log.Fatalf("failed to load config: %v", err)
	}

	// Manual toggle: led-controller [--config ...] on|off
	if len(args) > 0 {
		switch args[0] {
		case "on", "off":
			ctrl, err := controller.New(cfg)
			if err != nil {
				log.Fatalf("failed to create controller: %v", err)
			}
			defer ctrl.Close()

			on := args[0] == "on"
			if err := ctrl.SetLEDs(on); err != nil {
				log.Fatalf("failed to set LEDs %s: %v", args[0], err)
			}
			fmt.Printf("LEDs turned %s\n", args[0])
			return
		case "daemon":
			// fall through to daemon mode below
		default:
			fmt.Fprintf(os.Stderr, "usage: led-controller [--config path] [on|off|daemon]\n")
			os.Exit(1)
		}
	}

	// Daemon mode
	log.Printf("led-controller starting (relay=%s)", cfg.Relay.Device)

	ctrl, err := controller.New(cfg)
	if err != nil {
		log.Fatalf("failed to create controller: %v", err)
	}
	defer ctrl.Close()

	// Turn LEDs on at startup — the display is on if we're booting
	log.Println("startup — enabling LEDs")
	if err := ctrl.SetLEDs(true); err != nil {
		log.Printf("error enabling LEDs at startup: %v", err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

	events := make(chan monitor.Event, 16)
	mon, err := monitor.New(cfg, events)
	if err != nil {
		log.Fatalf("failed to create monitor: %v", err)
	}

	go mon.Run(ctx)

	log.Println("daemon running, waiting for display events")

	for {
		select {
		case ev := <-events:
			switch ev {
			case monitor.DisplayOn:
				log.Println("display ON — enabling LEDs")
				if err := ctrl.SetLEDs(true); err != nil {
					log.Printf("error enabling LEDs: %v", err)
				}
			case monitor.DisplayOff:
				log.Println("display OFF — disabling LEDs")
				if err := ctrl.SetLEDs(false); err != nil {
					log.Printf("error disabling LEDs: %v", err)
				}
			}
		case sig := <-sigCh:
			log.Printf("received %v, shutting down", sig)
			cancel()
			return
		}
	}
}
