// iso-bot — isometric game bot engine.
//
// Usage:
//
//	iso-bot --game d2r --routine mephisto --api :8080
//	iso-bot --dev --api :8080 --capture-file testdata/d2r_1080p.png
package main

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

	"git.cloonar.com/openclawd/iso-bot/pkg/api"
	"git.cloonar.com/openclawd/iso-bot/pkg/engine"
	"git.cloonar.com/openclawd/iso-bot/pkg/engine/capture/backends"
	"git.cloonar.com/openclawd/iso-bot/pkg/plugin"
	"git.cloonar.com/openclawd/iso-bot/plugins/d2r"
)

func main() {
	// Command line flags
	game := flag.String("game", "d2r", "game plugin to load")
	routine := flag.String("routine", "mephisto", "farming routine to run")
	apiAddr := flag.String("api", ":8080", "API server address")
	configFile := flag.String("config", "", "path to config file (YAML)")
	devMode := flag.Bool("dev", false, "enable development mode (no input simulation, serves dev dashboard)")
	captureFile := flag.String("capture-file", "", "file to capture from (for dev/testing)")
	captureDir := flag.String("capture-dir", "", "directory to capture from (for dev/testing)")
	flag.Parse()

	log.Printf("iso-bot starting: game=%s routine=%s api=%s dev=%t", *game, *routine, *apiAddr, *devMode)

	if *configFile != "" {
		log.Printf("Loading config from %s", *configFile)
		// TODO: Load YAML config
	}

	// Set up capture source
	var captureSource string
	var captureConfig map[string]interface{}
	
	if *devMode {
		if *captureFile != "" {
			captureSource = *captureFile
			captureConfig = map[string]interface{}{
				"path": *captureFile,
				"type": "image",
				"loop": true,
			}
		} else if *captureDir != "" {
			captureSource = *captureDir
			captureConfig = map[string]interface{}{
				"path":       *captureDir,
				"type":       "directory",
				"frame_rate": 1.0, // 1 FPS for directory scanning
				"loop":       true,
			}
		} else {
			// Default test image
			testDataPath := filepath.Join("testdata", "d2r_1080p.png")
			captureSource = testDataPath
			captureConfig = map[string]interface{}{
				"path": testDataPath,
				"type": "image",
				"loop": true,
			}
			log.Printf("No capture source specified, using default: %s", testDataPath)
		}
	} else {
		// Production mode - would use window/monitor capture
		log.Fatal("Production mode not implemented yet. Use --dev for development.")
	}

	// Create capture backend
	registry := backends.GetDefault()
	source, err := registry.Create(backends.BackendFile, captureConfig)
	if err != nil {
		log.Fatalf("Failed to create capture source %s: %v", captureSource, err)
	}
	defer source.Close()

	// Load game plugin
	var gamePlugin plugin.Plugin
	switch *game {
	case "d2r":
		gamePlugin = d2r.New()
	default:
		log.Fatalf("Unknown game plugin: %s", *game)
	}

	// Create engine
	eng, err := engine.NewEngine(source, gamePlugin, *devMode)
	if err != nil {
		log.Fatalf("Failed to create engine: %v", err)
	}

	// Set up web root for dev dashboard
	webRoot := "web/dev"
	if _, err := os.Stat(webRoot); os.IsNotExist(err) {
		// Try relative to executable
		execDir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
		webRoot = filepath.Join(execDir, "web", "dev")
	}

	// Start API server
	server := api.NewServer(*apiAddr, eng, webRoot)
	go func() {
		log.Printf("Starting API server on %s", *apiAddr)
		if *devMode {
			log.Printf("Dev dashboard will be available at http://localhost%s", *apiAddr)
		}
		if err := server.Start(); err != nil {
			log.Fatalf("API server error: %v", err)
		}
	}()

	// Start engine
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	
	go func() {
		if err := eng.Start(ctx); err != nil {
			log.Printf("Engine error: %v", err)
		}
	}()

	fmt.Printf("Game: %s, Routine: %s, Dev Mode: %t\n", *game, *routine, *devMode)
	log.Printf("Capture source: %s", captureSource)

	// Wait for interrupt
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	<-sig

	log.Println("Shutting down...")
	cancel()
	eng.Stop()
}
