import os
import subprocess
from flask import Blueprint, render_template, request, redirect, url_for, flash

bp = Blueprint('server', __name__, url_prefix='/server')

# RCON 정보
RCON_HOST = "127.0.0.1"
RCON_PORT = "25575"
RCON_PASSWORD = "init1234!"

# Minecraft 서버 경로 및 실행 스크립트
SERVER_DIR = "/home/minecraft/server"
SERVER_START_SCRIPT = "bash run.sh"

def run_rcon_command(command):
    """RCON 명령 실행"""
    try:
        mcrcon_path = "/usr/local/bin/mcrcon"  # 절대 경로 사용
        full_command = f'{mcrcon_path} -H {RCON_HOST} -P {RCON_PORT} -p {RCON_PASSWORD} {command}'
        print(f"Executing RCON command: {full_command}")  # 디버깅 로그 추가
        result = subprocess.check_output(full_command, shell=True, stderr=subprocess.STDOUT).decode('utf-8')
        return result
    except subprocess.CalledProcessError as e:
        error_message = e.output.decode('utf-8') if e.output else str(e)
        raise Exception(f"Failed to execute RCON command: {error_message}")

def check_server_status():
    """서버 상태 확인"""
    try:
        response = run_rcon_command("list")
        return "online" if "players online" in response else "offline"
    except Exception:
        return "offline"

@bp.route('/')
def server():
    """서버 관리 페이지"""
    server_status = check_server_status()
    return render_template('server.html', server_status=server_status)

@bp.route('/start', methods=['POST'])
def start_server():
    """서버 시작"""
    try:
        os.chdir(SERVER_DIR)
        subprocess.Popen(SERVER_START_SCRIPT, shell=True)
        flash("Server is starting.", "success")
    except Exception as e:
        flash(f"Failed to start server: {e}", "danger")
    return redirect(url_for('server.server'))

@bp.route('/stop', methods=['POST'])
def stop_server():
    """서버 중지"""
    try:
        run_rcon_command("stop")
        flash("Server is stopping.", "success")
    except Exception as e:
        flash(f"Failed to stop server: {e}", "danger")
    return redirect(url_for('server.server'))

@bp.route('/restart', methods=['POST'])
def restart_server():
    """서버 재시작"""
    try:
        run_rcon_command("stop")
        os.chdir(SERVER_DIR)
        subprocess.Popen(SERVER_START_SCRIPT, shell=True)
        flash("Server is restarting.", "success")
    except Exception as e:
        flash(f"Failed to restart server: {e}", "danger")
    return redirect(url_for('server.server'))

@bp.route('/announce', methods=['POST'])
def announce():
    """공지 설정"""
    message = request.form.get('announcement')
    try:
        run_rcon_command(f"title @a title \"{message}\"")
        flash("Announcement sent successfully.", "success")
    except Exception as e:
        flash(f"Failed to send announcement: {e}", "danger")
    return redirect(url_for('server.server'))
