class_name EconomyManagerClass
extends Node

# Currency
var cash: float = 100.0
var total_earned: float = 0.0
var total_spent: float = 0.0
var transaction_history: Array = []
var max_history: int = 50

# Signals
signal cash_changed(new_amount: float, delta: float)
signal transaction_recorded(type: String, amount: float, description: String)
signal insufficient_funds(required: float, available: float)

func _ready() -> void:
	print("[EconomyManager] initialized (cash: %.2f)" % cash)

func add_cash(amount: float, description: String = "") -> void:
	cash += amount
	total_earned += amount
	_record_transaction("income", amount, description)
	cash_changed.emit(cash, amount)
	print("[Economy] +%.2f: %s (Balance: %.2f)" % [amount, description, cash])

func spend_cash(amount: float, description: String = "") -> bool:
	if cash < amount:
		insufficient_funds.emit(amount, cash)
		print("[Economy] Insufficient funds: need %.2f, have %.2f" % [amount, cash])
		return false
	cash -= amount
	total_spent += amount
	_record_transaction("expense", amount, description)
	cash_changed.emit(cash, -amount)
	print("[Economy] -%.2f: %s (Balance: %.2f)" % [amount, description, cash])
	return true

func can_afford(amount: float) -> bool:
	return cash >= amount

func get_profit() -> float:
	return total_earned - total_spent

func _record_transaction(type: String, amount: float, description: String) -> void:
	var entry = {
		"type": type,
		"amount": amount,
		"description": description,
		"timestamp": Time.get_ticks_msec() / 1000.0
	}
	transaction_history.append(entry)
	if transaction_history.size() > max_history:
		transaction_history.pop_front()
	transaction_recorded.emit(type, amount, description)

func serialize() -> Dictionary:
	return {
		"cash": cash,
		"total_earned": total_earned,
		"total_spent": total_spent,
	}

func deserialize(data: Dictionary) -> void:
	cash = data.get("cash", 100.0)
	total_earned = data.get("total_earned", 0.0)
	total_spent = data.get("total_spent", 0.0)
	transaction_history.clear()
	cash_changed.emit(cash, 0.0)
