extends Node
# Autoload: Manager

# --- KONFIGURACJA ---
@export var SECTOR_COUNT: int = 17
@export var PLANETS_PER_SECTOR_RANGE: Vector2 = Settings.PLANET_NUMBER


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

# Timer aktualizacji
var update_timer := 0.0

# Nazwy sektorów i planet



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():
	print("test sss")
	randomize()
	_initialize_sectors()
	print("[Manager] Initialized with %d sectors" % SECTOR_COUNT)

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

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

# --- INICJALIZACJA SEKTORÓW ---
func _initialize_sectors():
	

	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 = find_safe_position()
			if pos != Vector2.ZERO:  
				print("Udało się znaleźć miejsca dla gwiazdy.")
				placed_star_positions.append(pos)
			else:
				print("Nie udało się znaleźć miejsca dla wszystkich gwiazd.")

			# Nazwa sektora
			var name = get_unique_sector_name()

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

			# 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 find_safe_position() -> Vector2:
	var screen_size = get_viewport().get_visible_rect().size
	for attempt in range(Settings.MAX_ATTEMPTS):
		# 1. Losowanie potencjalnej pozycji w obszarze (zgodnie z Twoimi marginesami)
		var potential_pos = Vector2(
			randf_range(50, screen_size.x - 50),
			randf_range(50, screen_size.y - 50)
			)
		
		# 2. Sprawdzenie, czy pozycja jest bezpieczna
		if is_position_safe(potential_pos):
			return potential_pos # Znaleziono bezpieczną pozycję!

	# 3. Jeśli po MAX_ATTEMPTS nie znaleziono miejsca
	print("Osiągnięto limit prób, nie można znaleźć bezpiecznego miejsca.")
	return Vector2.ZERO # Zwróć zero, aby zasygnalizować błąd
	
func is_position_safe(potential_pos: Vector2) -> bool:
	for existing_pos in placed_star_positions:
		var distance = potential_pos.distance_to(existing_pos)
		if distance < Settings.MIN_DISTANCE:
			return false # Kolizja znaleziona
	return true # Brak kolizji z żadną istniejącą gwiazdą
	
