// Package plugin defines the interfaces that game plugins must implement.
//
// The engine is game-agnostic. All game-specific logic lives in plugins
// that implement these interfaces. Adding a new game = a new plugin.
package plugin

import (
	"context"
	"image"

	"git.cloonar.com/openclawd/iso-bot/pkg/engine/capture"
)

// GameState represents the current state of the game (menu, loading, in-game, etc.)
type GameState string

const (
	StateUnknown         GameState = "unknown"
	StateLoading         GameState = "loading"
	StateMainMenu        GameState = "main_menu"
	StateCharacterSelect GameState = "character_select"
	StateInGame          GameState = "in_game"
	StateInventory       GameState = "inventory"
	StateDead            GameState = "dead"
	StateDisconnected    GameState = "disconnected"
)

// DetectedItem represents an item found on screen.
type DetectedItem struct {
	Name       string
	Type       string // "unique", "set", "rare", "rune", "normal"
	Rarity     int    // game-specific rarity tier
	Position   image.Point
	BBox       image.Rectangle
	Confidence float64
	Properties map[string]string // parsed item properties
}

// VitalStats represents character health/mana/etc.
type VitalStats struct {
	HealthPct float64 // 0.0 - 1.0
	ManaPct   float64
	XPPct     float64
}

// GameDetector detects the current game state from a screen capture.
type GameDetector interface {
	// DetectState analyzes a screenshot and returns the current game state.
	DetectState(frame image.Image) GameState

	// ReadVitals reads health, mana, and other vital stats from the screen.
	ReadVitals(frame image.Image) VitalStats

	// IsInGame returns true if the player is in an active game session.
	IsInGame(frame image.Image) bool
}

// ScreenReader extracts game information from screenshots.
type ScreenReader interface {
	// FindItems detects item labels/drops on screen.
	FindItems(frame image.Image) []DetectedItem

	// FindPortal locates a town portal on screen.
	FindPortal(frame image.Image) (image.Point, bool)

	// FindEnemies detects enemy positions (optional, not all games need this).
	FindEnemies(frame image.Image) []image.Point

	// ReadText extracts text from a screen region (OCR).
	ReadText(frame image.Image, region image.Rectangle) string
}

// Routine represents an automated game routine (e.g., a farming run).
type Routine interface {
	// Name returns the routine's display name.
	Name() string

	// Run executes one iteration of the routine.
	// Returns nil on success, error on failure (bot will handle recovery).
	Run(ctx context.Context) error

	// Phase returns the current phase name for status display.
	Phase() string
}

// LootFilter decides which items to pick up.
type LootFilter interface {
	// ShouldPickup evaluates an item against the filter rules.
	ShouldPickup(item DetectedItem) (pickup bool, priority int)

	// ShouldAlert returns true if this item warrants a notification.
	ShouldAlert(item DetectedItem) bool
}

// Plugin is the main interface a game plugin must implement.
type Plugin interface {
	// Info returns plugin metadata.
	Info() PluginInfo

	// Init initializes the plugin with engine services.
	Init(services EngineServices) error

	// Detector returns the game state detector.
	Detector() GameDetector

	// Reader returns the screen reader.
	Reader() ScreenReader

	// Routines returns available farming routines.
	Routines() []Routine

	// DefaultLootFilter returns the default loot filter.
	DefaultLootFilter() LootFilter

	// SupportedResolutions returns resolutions available for this game.
	SupportedResolutions() []image.Point
}

// PluginInfo describes a game plugin.
type PluginInfo struct {
	ID          string // e.g., "d2r"
	Name        string // e.g., "Diablo II: Resurrected"
	Version     string
	Description string
	Resolution  image.Point // target resolution, e.g., (1920, 1080)
}

// EngineServices provides access to engine capabilities for plugins.
type EngineServices interface {
	// Capture returns the current screen frame.
	Capture() image.Image

	// CaptureSource returns the active capture source.
	CaptureSource() capture.Source

	// Resolution returns the current capture resolution.
	Resolution() (width, height int)

	// Region returns a named screen region for the current game and resolution.
	Region(name string) image.Rectangle

	// Click sends a mouse click at the given position.
	Click(pos image.Point)

	// MoveMouse moves the mouse to the given position with human-like movement.
	MoveMouse(pos image.Point)

	// PressKey sends a key press.
	PressKey(key string)

	// TypeText types text with human-like delays.
	TypeText(text string)

	// Wait pauses for a human-like delay.
	Wait()

	// WaitMs pauses for a specific duration with randomization.
	WaitMs(baseMs int, varianceMs int)

	// Log logs a message associated with the plugin.
	Log(level string, msg string, args ...any)
}
