#!/usr/bin/env python3
import os
import sys
import json
import time
import uuid
import struct
import socket
import shutil
import logging
import subprocess
import re
from datetime import datetime
from zoneinfo import ZoneInfo

TZ_PERU = ZoneInfo("America/Lima")
from http.server import HTTPServer, ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

BASE_DIR = "/opt/minecraft/server"
CONFIG_FILE = os.path.join(BASE_DIR, "admin_panel", "config.json")

# Default Config
config = {
    "host": "0.0.0.0",
    "port": 8080,
    "rcon_host": "127.0.0.1",
    "rcon_port": 25575,
    "rcon_password": "novaterras_rcon_2026",
    "bluemap_port": 8100,
    "mc_port": 25565,
    "username": "gestor"
}

if os.path.exists(CONFIG_FILE):
    try:
        with open(CONFIG_FILE, "r") as f:
            config.update(json.load(f))
    except Exception as e:
        print(f"Error loading config: {e}")

# Save initial config if missing
if not os.path.exists(CONFIG_FILE):
    try:
        with open(CONFIG_FILE, "w") as f:
            json.dump(config, f, indent=2)
    except Exception as e:
        print(f"Error writing config: {e}")

# Session storage: token -> expiration_time
sessions = {}
SESSION_TTL = 86400  # 24 hours

def authenticate_user(username, password):
    if username.strip().lower() != config["username"].lower():
        return False
    # Validate via unix_chkpwd for system user 'gestor'
    try:
        p = subprocess.Popen(
            ["/usr/sbin/unix_chkpwd", config["username"], "nullok"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        p.communicate(input=password.encode("utf-8") + b"\x00")
        if p.returncode == 0:
            return True
    except Exception as e:
        print(f"PAM check error: {e}")
    
    # Fallback to config password if set and unix_chkpwd fails
    fallback_pwd = config.get("fallback_password")
    if fallback_pwd and password == fallback_pwd:
        return True

    return False

def ping_minecraft(host="127.0.0.1", port=25565, timeout=3.0):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        s.connect((host, port))
        
        host_bytes = host.encode("utf-8")
        data = b"\x00\xff\x05" + struct.pack(">B", len(host_bytes)) + host_bytes + struct.pack(">H", port) + b"\x01"
        packet = struct.pack(">B", len(data)) + data
        s.sendall(packet)
        s.sendall(b"\x01\x00")
        
        resp = b""
        while True:
            chunk = s.recv(4096)
            if not chunk: break
            resp += chunk
            if len(chunk) < 4096: break
        s.close()
        
        # Parse response
        idx = 0
        length = 0
        shift = 0
        while True:
            b = resp[idx]; idx += 1
            length |= (b & 0x7f) << shift
            if not (b & 0x80): break
            shift += 7
        pid = resp[idx]; idx += 1
        slen = 0
        shift = 0
        while True:
            b = resp[idx]; idx += 1
            slen |= (b & 0x7f) << shift
            if not (b & 0x80): break
            shift += 7
        payload = resp[idx:idx+slen].decode("utf-8", errors="replace")
        return json.loads(payload)
    except Exception as e:
        return None

def execute_rcon_cmd(command):
    host = config["rcon_host"]
    port = int(config["rcon_port"])
    pwd = config["rcon_password"]
    
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(2.5)
        s.connect((host, port))
        
        # Auth packet: id=1, type=3
        body_bytes = pwd.encode("utf-8") + b"\x00\x00"
        s.sendall(struct.pack("<iii", len(body_bytes) + 8, 1, 3) + body_bytes)
        
        # Read auth response
        data = s.recv(4)
        if not data: return False, "No response from RCON"
        length = struct.unpack("<i", data)[0]
        resp = s.recv(length)
        resp_id = struct.unpack("<i", resp[0:4])[0]
        if resp_id == -1:
            s.close()
            return False, "RCON password incorrect"
        
        # Send command: id=2, type=2
        cmd_bytes = command.encode("utf-8") + b"\x00\x00"
        s.sendall(struct.pack("<iii", len(cmd_bytes) + 8, 2, 2) + cmd_bytes)
        
        # Read command response
        data = s.recv(4)
        if not data: 
            s.close()
            return True, ""
        length = struct.unpack("<i", data)[0]
        payload = b""
        while len(payload) < length:
            chunk = s.recv(min(length - len(payload), 4096))
            if not chunk: break
            payload += chunk
        s.close()
        
        out = payload[8:-2].decode("utf-8", errors="replace")
        return True, out
    except ConnectionRefusedError:
        return False, "RCON no está conectado. El servidor Minecraft debe reiniciarse para activar RCON."
    except Exception as e:
        return False, f"Error RCON: {str(e)}"

def get_system_stats():
    # RAM
    ram_total = 0
    ram_avail = 0
    try:
        with open("/proc/meminfo") as f:
            mem = {}
            for line in f:
                parts = line.split(":")
                if len(parts) == 2:
                    mem[parts[0].strip()] = int(parts[1].split()[0])
            ram_total = mem.get("MemTotal", 0) / 1024  # MB
            ram_avail = mem.get("MemAvailable", 0) / 1024  # MB
            ram_used = ram_total - ram_avail
            ram_pct = round((ram_used / ram_total) * 100, 1) if ram_total > 0 else 0
    except Exception:
        ram_used, ram_total, ram_pct = 0, 0, 0
    
    # Disk
    try:
        du = shutil.disk_usage(BASE_DIR)
        disk_total_gb = round(du.total / (1024**3), 1)
        disk_used_gb = round(du.used / (1024**3), 1)
        disk_pct = round((du.used / du.total) * 100, 1)
    except Exception:
        disk_total_gb, disk_used_gb, disk_pct = 0, 0, 0

    # CPU load average
    try:
        load1, load5, load15 = os.getloadavg()
    except Exception:
        load1 = 0.0

    # Server Uptime
    uptime_str = "Desconocido"
    try:
        with open("/proc/uptime") as f:
            up_secs = float(f.readline().split()[0])
            days = int(up_secs // 86400)
            hours = int((up_secs % 86400) // 3600)
            mins = int((up_secs % 3600) // 60)
            uptime_str = f"{days}d {hours}h {mins}m"
    except Exception:
        pass

    return {
        "ram_used_mb": round(ram_used, 1),
        "ram_total_mb": round(ram_total, 1),
        "ram_percent": ram_pct,
        "disk_used_gb": disk_used_gb,
        "disk_total_gb": disk_total_gb,
        "disk_percent": disk_pct,
        "cpu_load": round(load1, 2),
        "uptime": uptime_str
    }

def get_player_extended_data(uuid_str):
    """Parses Essentials userdata to get last coordinates and logout/login timestamps."""
    userdata_file = os.path.join(BASE_DIR, "plugins", "Essentials", "userdata", f"{uuid_str}.yml")
    res = {
        "logout_ts": 0,
        "login_ts": 0,
        "last_seen_ts": 0,
        "last_seen_str": "Desconocido",
        "relative_time": "Desconocido",
        "coords": None,
        "dimension": "Overworld",
        "dimension_raw": "world"
    }
    if not os.path.exists(userdata_file):
        dat_file = os.path.join(BASE_DIR, "world", "playerdata", f"{uuid_str}.dat")
        if os.path.exists(dat_file):
            try:
                mtime = os.path.getmtime(dat_file)
                res["last_seen_ts"] = int(mtime)
                res["last_seen_str"] = datetime.fromtimestamp(mtime, tz=TZ_PERU).strftime("%d/%m/%Y %I:%M %p")
                now = time.time()
                diff = max(0, int(now - mtime))
                if diff < 60:
                    res["relative_time"] = "Hace un momento"
                elif diff < 3600:
                    res["relative_time"] = f"Hace {diff // 60} min"
                elif diff < 86400:
                    res["relative_time"] = f"Hace {diff // 3600}h"
                else:
                    res["relative_time"] = f"Hace {diff // 86400}d"
            except Exception:
                pass
        return res

    try:
        with open(userdata_file, "r", encoding="utf-8", errors="ignore") as f:
            content = f.read()

        m_login = re.search(r"login:\s*(\d+)", content)
        if m_login:
            res["login_ts"] = int(m_login.group(1)) // 1000

        m_logout = re.search(r"logout:\s*(\d+)", content)
        if m_logout:
            res["logout_ts"] = int(m_logout.group(1)) // 1000

        last_ts = max(res["logout_ts"], res["login_ts"])
        if last_ts == 0:
            last_ts = int(os.path.getmtime(userdata_file))
        res["last_seen_ts"] = last_ts

        dt = datetime.fromtimestamp(last_ts, tz=TZ_PERU)
        res["last_seen_str"] = dt.strftime("%d/%m/%Y %I:%M %p")

        now = time.time()
        diff = max(0, int(now - last_ts))
        if diff < 60:
            res["relative_time"] = "Hace un momento"
        elif diff < 3600:
            res["relative_time"] = f"Hace {diff // 60} min"
        elif diff < 86400:
            res["relative_time"] = f"Hace {diff // 3600}h"
        else:
            res["relative_time"] = f"Hace {diff // 86400}d"

        # Coordinates: prefer logoutlocation, fallback to lastlocation
        loc_sec = None
        if "logoutlocation:" in content:
            loc_sec = content.split("logoutlocation:", 1)[1]
        elif "lastlocation:" in content:
            loc_sec = content.split("lastlocation:", 1)[1]

        if loc_sec:
            mx = re.search(r"x:\s*([-\d\.]+)", loc_sec)
            my = re.search(r"y:\s*([-\d\.]+)", loc_sec)
            mz = re.search(r"z:\s*([-\d\.]+)", loc_sec)
            mw = re.search(r"world-name:\s*([^\s\n\r]+)", loc_sec)

            raw_w = mw.group(1) if mw else "world"
            res["dimension_raw"] = raw_w
            if "nether" in raw_w.lower():
                res["dimension"] = "Nether"
            elif "end" in raw_w.lower():
                res["dimension"] = "The End"
            else:
                res["dimension"] = "Overworld"

            if mx and my and mz:
                res["coords"] = {
                    "x": round(float(mx.group(1))),
                    "y": round(float(my.group(1))),
                    "z": round(float(mz.group(1)))
                }
    except Exception:
        pass

    return res

def get_server_players():
    # Cache, OP and Ban files
    ops = set()
    ops_file = os.path.join(BASE_DIR, "ops.json")
    if os.path.exists(ops_file):
        try:
            with open(ops_file, "r") as f:
                for item in json.load(f):
                    ops.add(item.get("name", "").lower())
        except Exception:
            pass

    banned = {}
    banned_file = os.path.join(BASE_DIR, "banned-players.json")
    if os.path.exists(banned_file):
        try:
            with open(banned_file, "r", encoding="utf-8", errors="ignore") as f:
                for item in json.load(f):
                    name_k = item.get("name", "").lower()
                    uuid_k = item.get("uuid", "")
                    b_info = {
                        "reason": item.get("reason", "Baneado"),
                        "source": re.sub(r"§[0-9a-fk-orx]", "", item.get("source", "Admin")),
                        "expires": item.get("expires", "Permanente")
                    }
                    if name_k: banned[name_k] = b_info
                    if uuid_k: banned[uuid_k] = b_info
        except Exception:
            pass

    usercache = []
    uc_file = os.path.join(BASE_DIR, "usercache.json")
    if os.path.exists(uc_file):
        try:
            with open(uc_file, "r") as f:
                usercache = json.load(f)
        except Exception:
            pass

    # Real-time online check via SLP
    slp = ping_minecraft()
    online_names = set()
    online_count = 0
    max_players = 50
    motd = "Nova Terras"
    version = "Paper 26.3"
    server_online = slp is not None

    if slp:
        players_data = slp.get("players", {})
        online_count = players_data.get("online", 0)
        max_players = players_data.get("max", 50)
        sample = players_data.get("sample", [])
        for p in sample:
            online_names.add(p.get("name"))
        version = slp.get("version", {}).get("name", version)
    else:
        # Fallback RCON check in case SLP took slightly longer during TPS lag
        ok, res = execute_rcon_cmd("list")
        if ok:
            server_online = True
            m = re.search(r"There are (\d+) out of maximum (\d+)", res)
            if m:
                online_count = int(m.group(1))
                max_players = int(m.group(2))
            if ":" in res:
                after_colon = res.split(":", 1)[1]
                for raw_name in after_colon.split(","):
                    clean = re.sub(r"§[0-9a-fk-orx]", "", raw_name).strip()
                    if clean:
                        online_names.add(clean)

    # Format players list
    all_players = []
    seen = set()
    for entry in usercache:
        name = entry.get("name")
        p_uuid = entry.get("uuid")
        if not name or name in seen:
            continue
        seen.add(name)
        is_online = name in online_names
        ext = get_player_extended_data(p_uuid)
        b_data = banned.get(name.lower()) or (banned.get(p_uuid) if p_uuid else None)
        is_banned = b_data is not None
        all_players.append({
            "name": name,
            "uuid": p_uuid,
            "online": is_online,
            "is_op": name.lower() in ops,
            "is_banned": is_banned,
            "ban_reason": b_data["reason"] if is_banned else None,
            "ban_source": b_data["source"] if is_banned else None,
            "avatar": f"https://mc-heads.net/avatar/{name}/64",
            "last_seen_ts": ext["last_seen_ts"],
            "last_seen_str": ext["last_seen_str"],
            "relative_time": ext["relative_time"],
            "coords": ext["coords"],
            "dimension": ext["dimension"],
            "dimension_raw": ext["dimension_raw"]
        })

    # Sort: online first, then active/recent, then banned
    all_players.sort(key=lambda x: (not x["online"], x["is_banned"], -x["last_seen_ts"], x["name"].lower()))

    return {
        "online_count": online_count,
        "max_players": max_players,
        "version": version,
        "server_online": server_online,
        "players": all_players
    }

def get_recent_logs(lines_count=100):
    log_file = os.path.join(BASE_DIR, "logs", "latest.log")
    if not os.path.exists(log_file):
        return []
    try:
        with open(log_file, "r", encoding="utf-8", errors="replace") as f:
            lines = f.readlines()
            return [l.rstrip("\r\n") for l in lines[-lines_count:]]
    except Exception as e:
        return [f"Error al leer logs: {str(e)}"]

class AdminHandler(BaseHTTPRequestHandler):
    def send_json(self, data, status=200):
        body = json.dumps(data).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
        self.end_headers()
        self.wfile.write(body)

    def send_html(self, html_content, status=200):
        body = html_content.encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def get_cookie(self, name):
        cookie_header = self.headers.get("Cookie")
        if not cookie_header:
            return None
        for item in cookie_header.split(";"):
            parts = item.strip().split("=")
            if len(parts) == 2 and parts[0] == name:
                return parts[1]
        return None

    def is_authenticated(self):
        token = self.get_cookie("nova_session")
        if not token:
            return False
        exp = sessions.get(token)
        if exp and exp > time.time():
            return True
        if token in sessions:
            del sessions[token]
        return False

    def do_HEAD(self):
        parsed = urlparse(self.path)
        if parsed.path in ["/resourcepack.zip", "/novaterras_pack.zip"]:
            self.send_response(200)
            self.send_header("Content-Type", "application/zip")
            self.end_headers()
            return
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.end_headers()

    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path

        if path in ["/resourcepack.zip", "/novaterras_pack.zip"]:
            pack_file = os.path.join(BASE_DIR, "admin_panel", "novaterras_pack.zip")
            if not os.path.exists(pack_file):
                pack_file = os.path.join(BASE_DIR, "admin_panel", "resourcepack.zip")
            if os.path.exists(pack_file):
                with open(pack_file, "rb") as f:
                    content = f.read()
                self.send_response(200)
                self.send_header("Content-Type", "application/zip")
                self.send_header("Content-Disposition", 'attachment; filename="novaterras_pack.zip"')
                self.send_header("Content-Length", str(len(content)))
                self.end_headers()
                self.wfile.write(content)
                return

        if path == "/login":
            if self.is_authenticated():
                self.send_response(302)
                self.send_header("Location", "/")
                self.end_headers()
                return
            html = get_login_html()
            self.send_html(html)
            return

        # Protected pages and APIs
        if not self.is_authenticated():
            if path.startswith("/api/"):
                self.send_json({"error": "No autorizado"}, 401)
            else:
                self.send_response(302)
                self.send_header("Location", "/login")
                self.end_headers()
            return

        if path == "/" or path == "/dashboard":
            html = get_dashboard_html()
            self.send_html(html)
            return

        if path == "/api/status":
            stats = get_system_stats()
            player_info = get_server_players()
            self.send_json({
                "system": stats,
                "minecraft": player_info,
                "bluemap_port": config["bluemap_port"]
            })
            return

        if path == "/api/logs":
            logs = get_recent_logs(150)
            self.send_json({"logs": logs})
            return

        self.send_error(404, "Página no encontrada")

    def do_POST(self):
        parsed = urlparse(self.path)
        path = parsed.path
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length).decode("utf-8", errors="replace") if length > 0 else ""
        
        try:
            data = json.loads(body) if body else {}
        except Exception:
            data = {}

        if path == "/api/login":
            user = data.get("username", "")
            pwd = data.get("password", "")
            if authenticate_user(user, pwd):
                token = str(uuid.uuid4())
                sessions[token] = time.time() + SESSION_TTL
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Set-Cookie", f"nova_session={token}; Path=/; HttpOnly; Max-Age={SESSION_TTL}")
                self.end_headers()
                self.wfile.write(json.dumps({"success": True}).encode("utf-8"))
            else:
                self.send_json({"success": False, "error": "Credenciales inválidas"}, 401)
            return

        if path == "/api/logout":
            token = self.get_cookie("nova_session")
            if token in sessions:
                del sessions[token]
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Set-Cookie", "nova_session=; Path=/; Max-Age=0")
            self.end_headers()
            self.wfile.write(b'{"success": true}')
            return

        # Must be authenticated for other POST routes
        if not self.is_authenticated():
            self.send_json({"error": "No autorizado"}, 401)
            return

        if path == "/api/command":
            cmd = data.get("command", "").strip()
            if not cmd:
                self.send_json({"success": False, "error": "Comando vacío"}, 400)
                return
            if cmd.startswith("/"):
                cmd = cmd[1:]
            success, output = execute_rcon_cmd(cmd)
            self.send_json({"success": success, "output": output})
            return

        self.send_error(404, "Endpoint no encontrado")

def get_login_html():
    return """<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Nova Terras - Login de Administración</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Inter', sans-serif;
      background: radial-gradient(circle at 50% 20%, #1e1b4b 0%, #0f172a 60%, #020617 100%);
      color: #f8fafc;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 1rem;
    }
    .login-card {
      background: rgba(30, 41, 59, 0.7);
      backdrop-filter: blur(16px);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 16px;
      padding: 2.5rem;
      width: 100%;
      max-width: 420px;
      box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
    }
    .logo-badge {
      display: inline-block;
      background: linear-gradient(135deg, #f59e0b, #d97706);
      color: #000;
      font-weight: 700;
      font-size: 0.8rem;
      padding: 0.3rem 0.8rem;
      border-radius: 9999px;
      margin-bottom: 1rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }
    h1 { font-size: 1.8rem; font-weight: 700; margin-bottom: 0.5rem; color: #fff; }
    p.subtitle { color: #94a3b8; font-size: 0.95rem; margin-bottom: 2rem; }
    .form-group { margin-bottom: 1.25rem; }
    label { display: block; font-size: 0.85rem; font-weight: 500; color: #cbd5e1; margin-bottom: 0.5rem; }
    input {
      width: 100%;
      padding: 0.75rem 1rem;
      background: rgba(15, 23, 42, 0.8);
      border: 1px solid #334155;
      border-radius: 8px;
      color: #fff;
      font-size: 1rem;
      outline: none;
      transition: border-color 0.2s, box-shadow 0.2s;
    }
    input:focus {
      border-color: #38bdf8;
      box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.2);
    }
    button {
      width: 100%;
      padding: 0.85rem;
      background: linear-gradient(135deg, #0284c7, #2563eb);
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 1rem;
      font-weight: 600;
      cursor: pointer;
      transition: opacity 0.2s, transform 0.1s;
      margin-top: 0.5rem;
    }
    button:hover { opacity: 0.95; }
    button:active { transform: scale(0.99); }
    .error-msg {
      background: rgba(239, 68, 68, 0.2);
      border: 1px solid rgba(239, 68, 68, 0.4);
      color: #fca5a5;
      padding: 0.75rem;
      border-radius: 8px;
      font-size: 0.9rem;
      margin-bottom: 1.25rem;
      display: none;
    }
  </style>
</head>
<body>
  <div class="login-card">
    <span class="logo-badge">✦ Panel de Control</span>
    <h1>Nova Terras</h1>
    <p class="subtitle">Acceso exclusivo para administradores</p>
    <div id="errorBox" class="error-msg"></div>
    <form id="loginForm">
      <div class="form-group">
        <label for="username">Usuario</label>
        <input type="text" id="username" value="gestor" required autocomplete="username">
      </div>
      <div class="form-group">
        <label for="password">Contraseña</label>
        <input type="password" id="password" required autocomplete="current-password" placeholder="Tu contraseña de gestor">
      </div>
      <button type="submit" id="btnSubmit">Iniciar Sesión</button>
    </form>
  </div>
  <script>
    document.getElementById('loginForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const btn = document.getElementById('btnSubmit');
      const err = document.getElementById('errorBox');
      btn.disabled = true;
      btn.innerText = 'Verificando...';
      err.style.display = 'none';

      try {
        const res = await fetch('/api/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            username: document.getElementById('username').value,
            password: document.getElementById('password').value
          })
        });
        const data = await res.json();
        if (res.ok && data.success) {
          window.location.href = '/';
        } else {
          err.innerText = data.error || 'Credenciales incorrectas';
          err.style.display = 'block';
          btn.disabled = false;
          btn.innerText = 'Iniciar Sesión';
        }
      } catch (e) {
        err.innerText = 'Error al conectar con el servidor';
        err.style.display = 'block';
        btn.disabled = false;
        btn.innerText = 'Iniciar Sesión';
      }
    });
  </script>
</body>
</html>"""

def get_dashboard_html():
    tmpl = os.path.join(BASE_DIR, "admin_panel", "dashboard.html")
    if os.path.exists(tmpl):
        with open(tmpl, "r", encoding="utf-8") as f:
            return f.read()
    return "<h1>Error: dashboard.html no encontrado</h1>"

def run():
    server_address = (config["host"], int(config["port"]))
    httpd = ThreadingHTTPServer(server_address, AdminHandler)
    print(f"=====================================================")
    print(f" Nova Terras Admin Panel iniciado en http://{config['host']}:{config['port']}")
    print(f" Usuario administrador: {config['username']}")
    print(f"=====================================================")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nCerrando servidor web...")
        httpd.server_close()

if __name__ == "__main__":
    run()
