extends Node
# Autoload: Manager

# --- KONFIGURACJA ---
@export var SECTOR_COUNT: int = 3
@export var PLANETS_PER_SECTOR_RANGE: Vector2 = Vector2(1, 5)
const UPDATE_INTERVAL := 2.0

# --- DANE ---
var sectors_data: Array = []  # Każdy element: {"name", "position", "planets", "star"}
var current_sector: int = -1

# Timer aktualizacji
var update_timer := 0.0

# Nazwy sektorów i planet
var sector_names = [
	"Aetherion", "Altaris", "Andur System", "Artemis Reach", "Astrion",
	"Azura Prime", "Borealis Expanse", "Caldris Belt", "Canthar System", "Celion Verge",
	"Corvax Sector", "Cygnera Rift", "Daedalus Reach", "Darnis Cluster", "Dravon Expanse",
	"Eclipta Prime", "Erevos System", "Eryndor Belt", "Ethon Reach", "Epsilon Mare",
	"Falcoris Rim", "Feron Cluster", "Gaelis System", "Galmar Belt", "Gryphon Reach",
	"Halion Expanse", "Helios Verge", "Hespera Sector", "Hyden Reach", "Icarion System",
	"Illun Belt", "Istris Cluster", "Jorath System", "Kaelor Expanse", "Kassian Reach",
	"Koralis Rim", "Krynn Sector", "Lunaris Reach", "Lysara System", "Maelor Verge",
	"Magnor Belt", "Mareth Cluster", "Meridian Expanse", "Morthal System", "Myrris Reach",
	"Nadir Verge", "Naos Sector", "Nerath Cluster", "Norian Belt", "Nova Thal",
	"Oblivis Reach", "Odessa Expanse", "Orionis Verge", "Orryx System", "Pallas Belt",
	"Parallax Rim", "Perion Sector", "Pharos System", "Phoenix Reach", "Primis Expanse",
	"Pyra Cluster", "Quaron Belt", "Quiris System", "Ragnar Verge", "Rathor Expanse",
	"Ravenna Sector", "Regalis System", "Remora Reach", "Rydan Belt", "Saren Cluster",
	"Selena Verge", "Seraphis System", "Shadow Rift", "Silvar Reach", "Solara Expanse",
	"Starnis Belt", "Syrion Cluster", "Talion System", "Tarsis Verge", "Tauren Expanse",
	"Tenebris Rim", "Thalassa Reach", "Tharon Belt", "Tirion Sector", "Tritonis Expanse",
	"Umbra Verge", "Valis Reach", "Varon Cluster", "Velora System", "Verrin Belt",
	"Veyra Expanse", "Viridis Rim", "Volnar Sector", "Vortex Reach", "Vulcaris System",
	"Wraith Expanse", "Xandor Cluster", "Xerion Verge", "Ymir Belt", "Zephyra System",
	"Zerath Expanse", "Zyra Prime", "Zyneth Reach", "Zorath System", "Zyphon Rim"
]


var planet_names = [
	"Arcturus","Betelgeuse","Canopus","Deneb","Elnath",
	"Fomalhaut","Gacrux","Hadar","Izar","Jabbah",
	"Kaus","Lesath","Menkent","Nunki","Okul",
	"Pollux","Rigel","Sargas","Toliman","Unukalhai",
	"Vega","Wezen","Xamidimura","Yildun","Zosma"
]

# --- START ---
func _ready():
	randomize()
	_initialize_sectors()
	print("[Manager] Initialized with %d sectors" % SECTOR_COUNT)

func _process(delta):
	update_timer += delta
	if update_timer >= UPDATE_INTERVAL:
		update_timer = 0.0
		_update_planets()

# --- LOSOWANIE UNIKALNEJ NAZWY SEKTORA ---
func get_unique_sector_name() -> String:
	if sector_names.size() == 0:
		return "Unknown Sector"
	var index = randi() % sector_names.size()
	var name = sector_names[index]
	sector_names.remove_at(index)
	return name

# --- INICJALIZACJA SEKTORÓW ---
func _initialize_sectors():
	var screen_size = get_viewport().get_visible_rect().size

	for i in range(SECTOR_COUNT):
		if sectors_data.size() <= i:
			sectors_data.resize(i + 1)
		if sectors_data[i] == null:
			# Pozycja sektora
			var pos = Vector2(
				randf_range(100, screen_size.x - 200),
				randf_range(100, screen_size.y - 200)
			)

			# Nazwa sektora
			var name = get_unique_sector_name()

			# Losowa gwiazda
			var star_texture = _random_star_texture()
			var star_scale = randf_range(0.03, 0.03)

			# Utworzenie sektora
			sectors_data[i] = {
				"name": name,
				"position": pos,
				"planets": [],
				"star": {
					"texture_path": star_texture,
					"scale": star_scale
				}
			}

			# Planety
			var planet_count = randi_range(PLANETS_PER_SECTOR_RANGE.x, PLANETS_PER_SECTOR_RANGE.y)
			for j in range(planet_count):
				_add_random_planet(i)

# --- FUNKCJE PLANET ---
func _add_random_planet(sector_index: int):
	var size = randi_range(1, 3)
	var growth_rate = randf_range(0.1, 1.0)
	var texture_planet: String
	if growth_rate > 0.7:
		texture_planet = "res://assets/planets/p%d.png" % randi_range(1,9)
	else:
		texture_planet = "res://assets/planets/p%d.png" % randi_range(10,18)

	var planet = {
		"name": planet_names[randi() % planet_names.size()],
		"size": size,
		"population": 0,
		"max_population": get_max_population(size),
		"resources": 0.0,
		"mining_rate": randf_range(0.1, 1.0),
		"growth_rate": growth_rate,
		"is_colonized": false,
		"angle": randf() * TAU,
		"rotation_speed": randf_range(0.001, 0.02),
		"texture_path": texture_planet
	}
	sectors_data[sector_index]["planets"].append(planet)

func _update_planets():
	for sector in sectors_data:
		if sector == null:
			continue
		for planet in sector["planets"]:
			if planet["is_colonized"]:
				var growth = int(max(1, planet["population"] * 0.05 * planet["growth_rate"]))
				planet["population"] = min(planet["population"] + growth, planet["max_population"])
				planet["resources"] += get_mined_per_cycle(planet)

func get_mined_per_cycle(planet: Dictionary) -> float:
	return planet["mining_rate"] * pow(planet["population"], 0.5) * 0.05

func get_max_population(size: int) -> int:
	match size:
		1: return 1000
		2: return 5000
		3: return 15000
		4: return 30000
	return 1000

# --- DOSTĘP DO SEKTORÓW I PLANET ---
func get_sector(index: int) -> Dictionary:
	if index >= 0 and index < sectors_data.size():
		return sectors_data[index]
	return {}

func get_planets(index: int) -> Array:
	var sector = get_sector(index)
	if sector.has("planets"):
		return sector["planets"]
	return []

func register_planet(sector_index: int, planet_name: String, size: int, mining_rate: float, growth_rate: float) -> Dictionary:
	if sectors_data.size() <= sector_index:
		sectors_data.resize(sector_index + 1)
	if sectors_data[sector_index] == null:
		sectors_data[sector_index] = {"planets": [], "name":"Unknown", "position": Vector2.ZERO, "star":{}}

	var planet = {
		"name": planet_name,
		"size": size,
		"population": 0,
		"max_population": get_max_population(size),
		"resources": 0.0,
		"mining_rate": mining_rate,
		"growth_rate": growth_rate,
		"is_colonized": false,
		"angle": randf() * TAU,
		"rotation_speed": randf_range(0.01, 0.03),
		"texture_path": "res://assets/planets/p%d.png" % randi_range(1,18)
	}
	sectors_data[sector_index]["planets"].append(planet)
	return planet

# --- LOSOWANIE GWIAZD ---
func _random_star_texture() -> String:
	var id = randi_range(1, 8)
	return "res://assets/stars/s%d.png" % id
	
func generate_non_overlapping_position(existing_positions: Array, min_distance: float, screen_size: Vector2) -> Vector2:
	var pos: Vector2
	var attempts = 0
	while true:
		pos = Vector2(
			randf_range(100, screen_size.x - 200),
			randf_range(100, screen_size.y - 200)
		)
		var overlap = false
		for other in existing_positions:
			if pos.distance_to(other) < min_distance:
				overlap = true
				break
		attempts += 1
		if not overlap or attempts > 100:
			break
	return pos
