import os
import subprocess
from dotenv import load_dotenv
from flask import Blueprint, render_template
from supabase import create_client, Client

# 환경 변수 로드
load_dotenv()

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

# Supabase 클라이언트 초기화
SUPABASE_URL = os.getenv('SUPABASE_URL')
SUPABASE_KEY = os.getenv('SUPABASE_KEY')
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

RCON_HOST = "127.0.0.1"
RCON_PORT = 25575
RCON_PASSWORD = "init1234!"

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, text=True).strip()
        return result
    except subprocess.CalledProcessError as e:
        error_message = e.output.strip() if e.output else str(e)
        raise Exception(f"Failed to execute RCON command: {error_message}")

@bp.route('/')
def dashboard():
    """대시보드 렌더링."""
    server_status = "온라인" if check_server_status() else "오프라인"
    player_count = get_online_players()
    mod_request_count = get_mod_request_count()

    return render_template(
        'dashboard.html',
        server_status=server_status,
        player_count=player_count,
        mod_request_count=mod_request_count
    )

def check_server_status():
    """서버 상태 확인."""
    try:
        response = run_rcon_command("list")
        return True if response else False
    except Exception as e:
        print(f"RCON connection failed: {e}")
        return False

def get_online_players():
    """현재 접속 중인 플레이어 수 반환."""
    try:
        response = run_rcon_command("list")
        print(f"RCON response for 'list': {response}")  # 디버깅용 로그

        # "There are 1 of a max of 20 players online: Player1" 형태의 응답 처리
        if response and "players online" in response:
            # "There are X of a max of Y players online"에서 X 추출
            start_index = response.find("There are") + len("There are")
            end_index = response.find("players online")
            players_online = response[start_index:end_index].strip().split()[0]
            return int(players_online)
    except ValueError as ve:
        print(f"Failed to parse player count: {ve}")
    except Exception as e:
        print(f"Failed to retrieve player count: {e}")
    return 0


def get_mod_request_count():
    """Supabase에서 승인 대기 중인 모드 요청 수를 반환."""
    try:
        response = supabase.table('mod_requests').select('id', 'status').eq('status', 'pending').execute()
        return len(response.data)
    except Exception as e:
        print(f"Failed to fetch mod request count from Supabase: {e}")
        return 0
