import json
import os

PORTS_FILE = 'ports.json'
BASE_PORT = 25500
PORTS_PER_USER = 3
MAX_PORTS = 100


def load_ports():
    if not os.path.exists(PORTS_FILE):
        with open(PORTS_FILE, 'w') as f:
            json.dump({}, f)
    with open(PORTS_FILE, 'r') as f:
        return json.load(f)


def save_ports(ports):
    with open(PORTS_FILE, 'w') as f:
        json.dump(ports, f, indent=2)


def assign_ports(username):
    ports = load_ports()
    if username in ports:
        return ports[username]

    used = {p for group in ports.values() for p in group}
    for i in range(0, MAX_PORTS * PORTS_PER_USER, PORTS_PER_USER):
        trial = [BASE_PORT + i + j for j in range(PORTS_PER_USER)]
        if not any(p in used for p in trial):
            ports[username] = trial
            save_ports(ports)
            return trial

    raise Exception("Brak dostępnych portów")


def free_ports_for_user(username):
    if not os.path.exists(PORTS_FILE):
        return

    with open(PORTS_FILE, "r") as f:
        data = json.load(f)

    container_name = f"mc-{username}"
    if container_name in data:
        del data[container_name]
        with open(PORTS_FILE, "w") as f:
            json.dump(data, f, indent=2)

def get_user_ports(username):
    ports = load_ports()
    if username in ports:
        return ports[username]

    return None