import os
import random

from flask import Blueprint, render_template, jsonify
from .auth import oidc
from .port_utils import get_user_ports
from .docker_utils import client
from docker.errors import NotFound
from dotenv import load_dotenv

main = Blueprint('main', __name__, static_folder='static')

load_dotenv()


@main.route("/")
def home():
    is_logged_in = oidc.user_loggedin
    has_server = False
    if is_logged_in:
        username = oidc.user_getfield("preferred_username")
        server_path = f"./servers/mc-{username}"
        has_server = os.path.exists(server_path)
    return render_template("home.html", has_server=has_server, is_logged_in=is_logged_in)


@main.route('/setup')
@oidc.require_login
def setup():
    return render_template('setup.html')


@main.route('/dashboard')
@oidc.require_login
def dashboard():
    username = oidc.user_getfield('preferred_username')
    server_path = f"./servers/mc-{username}"
    has_server = os.path.exists(server_path)
    ip = os.getenv("SERVER_IP")
    ports = get_user_ports(username)

    if has_server:
        return render_template('dashboard.html', username=username, ip=ip, ports=ports)
    else:
        return render_template('setup.html', username=username, ip=ip, ports=ports)


@main.route('/donate')
def donate():
    return render_template('donate.html')


@main.route("/ads/list")
def list_ads():
    ads_dir = os.path.join(main.static_folder, "ads")
    files = [
        f"/static/ads/{f}"
        for f in os.listdir(ads_dir)
        if f.lower().endswith(".png")
    ]
    return jsonify(files)


@main.route("/status")
def servers_status():
    servers_dir = "./servers"
    server_dirs = [
        d for d in os.listdir(servers_dir) 
        if os.path.isdir(os.path.join(servers_dir, d)) and d.startswith('mc-')
    ]
    
    server_data = []
    
    for server_dir in server_dirs:
        server_name = server_dir
        server_status = "Offline"
        
        try:
            container = client.containers.get(server_name)
            if container.status == "running":
                server_status = "Online"
        except NotFound:
            pass
        
        server_data.append({"name": server_name, "status": server_status})

    return render_template('servers_list.html', servers=server_data)


@main.app_errorhandler(404)
def page_not_found(e):
    return render_template("404.html"), 404
