from __future__ import annotations

import asyncio
import hmac
import json
import logging
import os
import re
import sys
from dataclasses import dataclass
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from typing import Any, Optional

import aiohttp
from aiohttp import web
import discord
import pyodbc
from discord.ext import commands, tasks
from dotenv import load_dotenv

BASE_DIR = Path(__file__).resolve().parent
os.chdir(BASE_DIR)
(BASE_DIR / "logs").mkdir(exist_ok=True)

load_dotenv(BASE_DIR / ".env")

# -----------------------------------------------------------------------------
# LOG
# -----------------------------------------------------------------------------
logger = logging.getLogger("gigax_bot")
logger.setLevel(logging.INFO)

if not logger.handlers:
    fmt = logging.Formatter(
        "%(asctime)s | %(levelname)s | %(name)s | %(message)s",
        "%Y-%m-%d %H:%M:%S",
    )
    console = logging.StreamHandler(sys.stdout)
    console.setFormatter(fmt)
    logger.addHandler(console)

    file_handler = TimedRotatingFileHandler(
        BASE_DIR / "logs" / "gigax_bot.log",
        when="midnight",
        backupCount=14,
        encoding="utf-8",
    )
    file_handler.setFormatter(fmt)
    logger.addHandler(file_handler)


def env(name: str, default: str = "") -> str:
    return os.getenv(name, default).strip()


def env_int(name: str, default: int) -> int:
    try:
        return int(env(name, str(default)))
    except Exception:
        return default


# -----------------------------------------------------------------------------
# CONFIG
# -----------------------------------------------------------------------------
DISCORD_TOKEN = env("DISCORD_TOKEN")
GUILD_ID = env_int("GUILD_ID", 0)

GIGAX_API_BASE = env("GIGAX_API_BASE", "https://kruxarena.com.br").rstrip("/")
GIGAX_API_TOKEN = env("GIGAX_API_TOKEN")
GIGAX_POLL_SECONDS = max(2, env_int("GIGAX_POLL_SECONDS", 3))
GIGAX_EVENT_HOST = "127.0.0.1"
GIGAX_EVENT_PORT = env_int("GIGAX_EVENT_PORT", 8787)
GIGAX_EVENT_TOKEN = env("GIGAX_SHARED_TOKEN") or env("GIGAX_BOT_SHARED_TOKEN") or GIGAX_API_TOKEN

BOT_DB_DRIVER = env("BOT_DB_ODBC_DRIVER", "ODBC Driver 17 for SQL Server")
BOT_DB_HOST = env("BOT_DB_HOST", "127.0.0.1")
BOT_DB_PORT = env_int("BOT_DB_PORT", 1433)
BOT_DB_DATABASE = env("BOT_DB_DATABASE", "GIGAXBOT")
BOT_DB_USERNAME = env("BOT_DB_USERNAME")
BOT_DB_PASSWORD = env("BOT_DB_PASSWORD")
BOT_DB_ENCRYPT = env("BOT_DB_ENCRYPT", "no")
BOT_DB_TRUST_CERT = env("BOT_DB_TRUST_SERVER_CERTIFICATE", "yes")

DISCORD_MATCH_CATEGORY_ID = env_int("DISCORD_MATCH_CATEGORY_ID", 0)
DISCORD_LOBBY_CHANNEL_ID = env_int("DISCORD_LOBBY_CHANNEL_ID", 0)
ROOM_PREFIX = env("DISCORD_ROOM_PREFIX", "GIGAX PARTIDA")

if not DISCORD_TOKEN:
    raise RuntimeError("DISCORD_TOKEN ausente no .env")
if not GUILD_ID:
    raise RuntimeError("GUILD_ID ausente no .env")


# -----------------------------------------------------------------------------
# INTERNAL SQL SERVER - GIGAXBOT DATABASE
# -----------------------------------------------------------------------------
class BotDatabase:
    def __init__(self) -> None:
        self._lock = asyncio.Lock()

    def _connection_string(self) -> str:
        parts = [
            f"DRIVER={{{BOT_DB_DRIVER}}}",
            f"SERVER={BOT_DB_HOST},{BOT_DB_PORT}",
            f"DATABASE={BOT_DB_DATABASE}",
        ]
        if BOT_DB_USERNAME:
            parts.extend([f"UID={BOT_DB_USERNAME}", f"PWD={BOT_DB_PASSWORD}"])
        else:
            parts.append("Trusted_Connection=yes")
        parts.extend(
            [
                f"Encrypt={BOT_DB_ENCRYPT}",
                f"TrustServerCertificate={BOT_DB_TRUST_CERT}",
            ]
        )
        return ";".join(parts) + ";"

    def connect(self):
        return pyodbc.connect(
            self._connection_string(),
            autocommit=True,
            timeout=10,
        )

    async def ensure_schema(self) -> None:
        async with self._lock:
            await asyncio.to_thread(self._ensure_schema_sync)

    def _ensure_schema_sync(self) -> None:
        conn = self.connect()
        try:
            cur = conn.cursor()
            cur.execute(
                """
                IF OBJECT_ID(N'dbo.gigax_discord_match_rooms', N'U') IS NULL
                BEGIN
                    CREATE TABLE dbo.gigax_discord_match_rooms (
                        id BIGINT IDENTITY(1,1) PRIMARY KEY,
                        match_id BIGINT NOT NULL UNIQUE,
                        guild_id BIGINT NOT NULL,
                        category_id BIGINT NULL,
                        text_channel_id BIGINT NULL,
                        team_a_voice_id BIGINT NULL,
                        team_b_voice_id BIGINT NULL,
                        discord_room_name NVARCHAR(180) NULL,
                        discord_invite_url NVARCHAR(500) NULL,
                        status NVARCHAR(30) NOT NULL DEFAULT 'created',
                        created_at DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
                        updated_at DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
                        deleted_at DATETIME2 NULL
                    );
                END
                """
            )
            cur.execute(
                """
                IF OBJECT_ID(N'dbo.gigax_bot_events', N'U') IS NULL
                BEGIN
                    CREATE TABLE dbo.gigax_bot_events (
                        id BIGINT IDENTITY(1,1) PRIMARY KEY,
                        match_id BIGINT NULL,
                        event_type NVARCHAR(80) NOT NULL,
                        payload NVARCHAR(MAX) NULL,
                        created_at DATETIME2 NOT NULL DEFAULT SYSDATETIME()
                    );
                END
                """
            )
            cur.execute("""
                IF OBJECT_ID(N'dbo.gigax_discord_voice_assignments', N'U') IS NULL
                BEGIN
                    CREATE TABLE dbo.gigax_discord_voice_assignments (
                        match_id BIGINT NOT NULL,
                        discord_user_id BIGINT NOT NULL,
                        team TINYINT NOT NULL,
                        voice_channel_id BIGINT NOT NULL,
                        created_at DATETIME2 NOT NULL DEFAULT SYSDATETIME(),
                        CONSTRAINT PK_gigax_discord_voice_assignments
                            PRIMARY KEY (match_id, discord_user_id)
                    );
                    CREATE INDEX IX_gigax_voice_assignments_user
                        ON dbo.gigax_discord_voice_assignments(discord_user_id);
                END
            """)
        finally:
            conn.close()

    async def save_assignments(self, match_id: int, team_a: list[int], team_b: list[int],
                               voice_a: int, voice_b: int) -> None:
        await asyncio.to_thread(self._save_assignments_sync, match_id, team_a, team_b, voice_a, voice_b)

    def _save_assignments_sync(self, match_id, team_a, team_b, voice_a, voice_b):
        conn = self.connect()
        try:
            cur = conn.cursor()
            cur.execute("DELETE FROM dbo.gigax_discord_voice_assignments WHERE match_id=?", match_id)
            for team, ids, channel in ((1, team_a, voice_a), (2, team_b, voice_b)):
                for discord_id in set(ids):
                    cur.execute("""INSERT INTO dbo.gigax_discord_voice_assignments
                        (match_id, discord_user_id, team, voice_channel_id) VALUES (?, ?, ?, ?)""",
                        match_id, discord_id, team, channel)
        finally:
            conn.close()

    async def assigned_voice(self, discord_id: int) -> Optional[dict]:
        return await asyncio.to_thread(self._assigned_voice_sync, discord_id)

    def _assigned_voice_sync(self, discord_id):
        conn = self.connect()
        try:
            cur = conn.cursor()
            cur.execute("""SELECT TOP 1 a.match_id, a.team, a.voice_channel_id
                FROM dbo.gigax_discord_voice_assignments a
                INNER JOIN dbo.gigax_discord_match_rooms r ON r.match_id=a.match_id
                WHERE a.discord_user_id=? AND r.deleted_at IS NULL AND r.status='created'
                ORDER BY r.created_at DESC""", discord_id)
            row = cur.fetchone()
            return dict(zip([d[0] for d in cur.description], row)) if row else None
        finally:
            conn.close()

    async def active_match_for_channel(self, channel_id: int) -> Optional[int]:
        return await asyncio.to_thread(self._active_match_for_channel_sync, channel_id)

    def _active_match_for_channel_sync(self, channel_id: int) -> Optional[int]:
        conn = self.connect()
        try:
            cur = conn.cursor()
            cur.execute("""SELECT TOP 1 match_id FROM dbo.gigax_discord_match_rooms
                WHERE status='created' AND deleted_at IS NULL
                AND (team_a_voice_id=? OR team_b_voice_id=?)""", channel_id, channel_id)
            row = cur.fetchone()
            return int(row[0]) if row else None
        finally:
            conn.close()

    async def get_room(self, match_id: int) -> Optional[dict]:
        return await asyncio.to_thread(self._get_room_sync, match_id)

    def _get_room_sync(self, match_id: int) -> Optional[dict]:
        conn = self.connect()
        try:
            cur = conn.cursor()
            cur.execute(
                """
                SELECT TOP 1 match_id, guild_id, category_id, text_channel_id,
                    team_a_voice_id, team_b_voice_id, discord_room_name,
                    discord_invite_url, status
                FROM dbo.gigax_discord_match_rooms
                WHERE match_id = ? AND deleted_at IS NULL
                """,
                match_id,
            )
            row = cur.fetchone()
            if not row:
                return None
            cols = [d[0] for d in cur.description]
            return dict(zip(cols, row))
        finally:
            conn.close()

    async def save_room(self, data: dict) -> None:
        await asyncio.to_thread(self._save_room_sync, data)

    def _save_room_sync(self, data: dict) -> None:
        conn = self.connect()
        try:
            cur = conn.cursor()
            cur.execute(
                """
                MERGE dbo.gigax_discord_match_rooms AS target
                USING (
                    SELECT ? AS match_id, ? AS guild_id, ? AS category_id,
                           ? AS text_channel_id, ? AS team_a_voice_id,
                           ? AS team_b_voice_id, ? AS discord_room_name,
                           ? AS discord_invite_url, ? AS status
                ) AS src
                ON target.match_id = src.match_id
                WHEN MATCHED THEN UPDATE SET
                    guild_id = src.guild_id,
                    category_id = src.category_id,
                    text_channel_id = src.text_channel_id,
                    team_a_voice_id = src.team_a_voice_id,
                    team_b_voice_id = src.team_b_voice_id,
                    discord_room_name = src.discord_room_name,
                    discord_invite_url = src.discord_invite_url,
                    status = src.status,
                    updated_at = SYSDATETIME(),
                    deleted_at = NULL
                WHEN NOT MATCHED THEN INSERT (
                    match_id, guild_id, category_id, text_channel_id,
                    team_a_voice_id, team_b_voice_id, discord_room_name,
                    discord_invite_url, status
                ) VALUES (
                    src.match_id, src.guild_id, src.category_id, src.text_channel_id,
                    src.team_a_voice_id, src.team_b_voice_id, src.discord_room_name,
                    src.discord_invite_url, src.status
                );
                """,
                (
                    data["match_id"],
                    data["guild_id"],
                    data.get("category_id"),
                    data.get("text_channel_id"),
                    data.get("team_a_voice_id"),
                    data.get("team_b_voice_id"),
                    data.get("discord_room_name"),
                    data.get("discord_invite_url"),
                    data.get("status", "created"),
                ),
            )
        finally:
            conn.close()

    async def mark_deleted(self, match_id: int) -> None:
        await asyncio.to_thread(self._mark_deleted_sync, match_id)

    def _mark_deleted_sync(self, match_id: int) -> None:
        conn = self.connect()
        try:
            conn.cursor().execute(
                """
                UPDATE dbo.gigax_discord_match_rooms
                SET status='deleted', deleted_at=SYSDATETIME(), updated_at=SYSDATETIME()
                WHERE match_id=?
                """,
                match_id,
            )
            conn.cursor().execute(
                "DELETE FROM dbo.gigax_discord_voice_assignments WHERE match_id=?", match_id
            )
        finally:
            conn.close()

    async def log_event(self, match_id: Optional[int], event_type: str, payload: Any = None) -> None:
        await asyncio.to_thread(self._log_event_sync, match_id, event_type, payload)

    def _log_event_sync(self, match_id, event_type, payload):
        conn = self.connect()
        try:
            conn.cursor().execute(
                "INSERT INTO dbo.gigax_bot_events(match_id,event_type,payload) VALUES(?,?,?)",
                match_id,
                event_type,
                json.dumps(payload, ensure_ascii=False, default=str) if payload is not None else None,
            )
        finally:
            conn.close()


db = BotDatabase()


# -----------------------------------------------------------------------------
# LARAVEL GIGAX API
# -----------------------------------------------------------------------------
class GigaxApi:
    def __init__(self) -> None:
        self.session: Optional[aiohttp.ClientSession] = None

    async def start(self):
        if self.session is None or self.session.closed:
            timeout = aiohttp.ClientTimeout(total=15)
            self.session = aiohttp.ClientSession(timeout=timeout)

    async def close(self):
        if self.session and not self.session.closed:
            await self.session.close()

    def headers(self) -> dict:
        h = {
            "Accept": "application/json",
            "User-Agent": "GIGAX-Discord-Bot/2.0",
        }
        if GIGAX_API_TOKEN:
            h["Authorization"] = f"Bearer {GIGAX_API_TOKEN}"
            h["X-GIGAX-BOT-TOKEN"] = GIGAX_API_TOKEN
        return h

    async def get(self, path: str) -> dict:
        await self.start()
        assert self.session
        url = f"{GIGAX_API_BASE}{path}"
        async with self.session.get(url, headers=self.headers()) as r:
            text = await r.text()
            if r.status >= 400:
                raise RuntimeError(f"GET {path} -> HTTP {r.status}: {text[:300]}")
            return json.loads(text or "{}")

    async def post(self, path: str, payload: dict) -> dict:
        await self.start()
        assert self.session
        url = f"{GIGAX_API_BASE}{path}"
        async with self.session.post(url, headers=self.headers(), json=payload) as r:
            text = await r.text()
            if r.status >= 400:
                raise RuntimeError(f"POST {path} -> HTTP {r.status}: {text[:300]}")
            return json.loads(text or "{}")

    async def pending_voice_matches(self) -> list[dict]:
        data = await self.get("/api/gigax-bot/matches/pending-voice")
        return list(data.get("matches") or [])

    async def report_voice_ready(self, match_id: int, payload: dict) -> dict:
        return await self.post(f"/api/gigax-bot/matches/{match_id}/voice-created", payload)

    async def report_voice_deleted(self, match_id: int) -> dict:
        return await self.post(f"/api/gigax-bot/matches/{match_id}/voice-deleted", {})

    async def cleanup_matches(self) -> list[dict]:
        data = await self.get("/api/gigax-bot/matches/cleanup-voice")
        return list(data.get("matches") or [])


api = GigaxApi()


# -----------------------------------------------------------------------------
# DISCORD BOT
# -----------------------------------------------------------------------------
intents = discord.Intents.default()
intents.guilds = True
intents.members = True
intents.voice_states = True

bot = commands.Bot(command_prefix="!", intents=intents)


def safe_channel_name(value: str, fallback: str) -> str:
    value = (value or fallback).strip().lower()
    value = re.sub(r"[^a-z0-9áéíóúãõâêôç_-]+", "-", value, flags=re.IGNORECASE)
    value = re.sub(r"-{2,}", "-", value).strip("-")
    return value[:90] or fallback


def member_overwrites(guild: discord.Guild, discord_ids: list[int]) -> dict:
    overwrites: dict[Any, discord.PermissionOverwrite] = {
        guild.default_role: discord.PermissionOverwrite(
            view_channel=False,
            connect=False,
        )
    }

    me = guild.me
    if me:
        overwrites[me] = discord.PermissionOverwrite(
            view_channel=True,
            connect=True,
            manage_channels=True,
            create_instant_invite=True,
            send_messages=True,
        )

    for discord_id in discord_ids:
        member = guild.get_member(int(discord_id))
        if member:
            overwrites[member] = discord.PermissionOverwrite(
                view_channel=True,
                connect=True,
                send_messages=True,
                read_message_history=True,
            )

    return overwrites


def gigax_match_title(match: dict) -> str:
    match_id = int(match["match_id"])
    label = str(match.get("display_mode") or "PARTIDA").strip().upper()
    label = re.sub(r"[^A-Z0-9À-Ú /_-]", "", label)[:65].strip() or "PARTIDA"
    return f"GIGAX #{match_id} - {label}"


async def get_or_create_category(guild: discord.Guild, match_id: int, title: str) -> discord.CategoryChannel:
    if DISCORD_MATCH_CATEGORY_ID:
        existing = guild.get_channel(DISCORD_MATCH_CATEGORY_ID)
        if isinstance(existing, discord.CategoryChannel):
            return existing

    name = title
    return await guild.create_category(name=name, reason=f"GIGAX partida #{match_id}")


# Partidas em limpeza nao podem receber movimentacao automatica.
closing_match_ids = set()
room_operation_lock = asyncio.Lock()
event_runner = None


async def move_assigned_member(member: discord.Member, assignment: dict, *, reason: str) -> bool:
    """Move only assigned users in this guild; never pull from another active match."""
    if member.bot or member.guild.id != GUILD_ID or not member.voice or not member.voice.channel:
        return False
    if int(assignment["match_id"]) in closing_match_ids:
        return False
    target_id = int(assignment["voice_channel_id"])
    current_id = member.voice.channel.id
    if current_id == target_id:
        return False
    target = member.guild.get_channel(target_id)
    if not isinstance(target, discord.VoiceChannel):
        logger.warning("Partida %s: canal de destino %s ausente", assignment["match_id"], target_id)
        return False
    other_match = await db.active_match_for_channel(current_id)
    if other_match is not None and other_match != int(assignment["match_id"]):
        logger.info("Jogador %s permanece na partida ativa %s", member.id, other_match)
        return False
    # Confirm assignment again immediately before the move.
    latest = await db.assigned_voice(member.id)
    if (not latest or int(latest["match_id"]) != int(assignment["match_id"])
            or int(latest["voice_channel_id"]) != target_id):
        logger.warning("Jogador %s: atribuicao mudou antes da movimentacao", member.id)
        return False
    if not member.voice or not member.voice.channel or member.voice.channel.id != current_id:
        return False
    if int(assignment["match_id"]) in closing_match_ids:
        return False
    try:
        await member.move_to(target, reason=reason)
        logger.info("Jogador %s movido: partida=%s time=%s origem=%s destino=%s",
                    member.id, assignment["match_id"], assignment["team"], current_id, target_id)
        return True
    except discord.Forbidden:
        logger.exception("Sem permissao para mover jogador %s", member.id)
    except discord.HTTPException:
        logger.exception("Discord recusou movimentacao do jogador %s", member.id)
    except Exception:
        logger.exception("Falha ao mover jogador %s", member.id)
    return False


async def move_connected_players(guild: discord.Guild, match_id: int,
                                 team_a: list[int], team_b: list[int],
                                 voice_a: int, voice_b: int) -> None:
    """On READY, move assigned players from any guild voice channel except another active match."""
    moved = connected = 0
    for team, ids, channel_id in ((1, set(team_a), voice_a), (2, set(team_b), voice_b)):
        for discord_id in ids:
            member = guild.get_member(discord_id)
            if member is None:
                try:
                    member = await guild.fetch_member(discord_id)
                except (discord.NotFound, discord.Forbidden, discord.HTTPException):
                    logger.warning("Partida %s: membro Discord %s indisponivel", match_id, discord_id)
                    continue
            if not member.voice or not member.voice.channel:
                logger.info("Partida %s: jogador %s desconectado da voz; aguardando", match_id, discord_id)
                continue
            connected += 1
            assignment = {"match_id": match_id, "team": team, "voice_channel_id": channel_id}
            if await move_assigned_member(member, assignment, reason=f"GIGAX partida #{match_id} READY"):
                moved += 1
    logger.info("Partida %s: movimentacao inicial conectados=%s movidos=%s", match_id, connected, moved)


async def create_match_room(guild: discord.Guild, match: dict) -> dict:
    match_id = int(match["match_id"])
    existing = await db.get_room(match_id)
    if existing and existing.get("status") == "created":
        channel_ids = [existing.get("text_channel_id"), existing.get("team_a_voice_id"),
                       existing.get("team_b_voice_id")]
        if all(cid and guild.get_channel(int(cid)) for cid in channel_ids):
            team_a = [int(x) for x in (match.get("team_a_discord_ids") or []) if str(x).isdigit()]
            team_b = [int(x) for x in (match.get("team_b_discord_ids") or []) if str(x).isdigit()]
            await db.save_assignments(match_id, team_a, team_b,
                                      int(existing["team_a_voice_id"]), int(existing["team_b_voice_id"]))
            await move_connected_players(guild, match_id, team_a, team_b,
                                       int(existing["team_a_voice_id"]), int(existing["team_b_voice_id"]))
            return existing
        logger.error("Partida %s tem registro de sala incompleto; exige reconciliacao manual", match_id)
        return existing

    team_a = [int(x) for x in (match.get("team_a_discord_ids") or []) if str(x).isdigit()]
    team_b = [int(x) for x in (match.get("team_b_discord_ids") or []) if str(x).isdigit()]
    everyone = sorted(set(team_a + team_b))
    overwrites = member_overwrites(guild, everyone)

    category = await get_or_create_category(guild, match_id, gigax_match_title(match))

    text_name = safe_channel_name(f"GX-{match_id}", f"gx-{match_id}")
    text_channel = await guild.create_text_channel(
        text_name,
        category=category,
        overwrites=overwrites,
        reason=f"GIGAX partida #{match_id}",
    )

    voice_a = await guild.create_voice_channel(
        f"Time-A-(BL)-{match_id}",
        category=category,
        overwrites=member_overwrites(guild, team_a),
        reason=f"GIGAX Time A #{match_id}",
    )

    voice_b = await guild.create_voice_channel(
        f"Time-B-(GR)-{match_id}",
        category=category,
        overwrites=member_overwrites(guild, team_b),
        reason=f"GIGAX Time B #{match_id}",
    )

    invite = await text_channel.create_invite(
        max_age=0,
        max_uses=0,
        unique=True,
        reason=f"GIGAX partida #{match_id}",
    )

    map_name = match.get("map_name") or "Mapa definido"
    await text_channel.send(
        f"🎮 **GIGAX • PARTIDA #{match_id}**\n"
        f"🗺️ **Mapa:** {map_name}\n"
        f"✅ Ready Check concluído\n"
        f"🎙️ Canais de voz dos Times A e B criados."
    )

    result = {
        "match_id": match_id,
        "guild_id": guild.id,
        "category_id": category.id,
        "text_channel_id": text_channel.id,
        "team_a_voice_id": voice_a.id,
        "team_b_voice_id": voice_b.id,
        "discord_room_name": gigax_match_title(match),
        "discord_invite_url": str(invite.url),
        "status": "created",
    }

    await db.save_room(result)
    await db.save_assignments(match_id, team_a, team_b, voice_a.id, voice_b.id)
    await move_connected_players(guild, match_id, team_a, team_b, voice_a.id, voice_b.id)
    await db.log_event(match_id, "discord_room_created", result)

    # Retorna ao Laravel; o Aero Modal passa de "CRIANDO SALA" para "SALA PRONTA".
    if not (990000 <= match_id <= 999999):
        await api.report_voice_ready(
            match_id,
            {
                "voice_mode": "discord",
                "discord_room_name": result["discord_room_name"],
                "discord_invite_url": result["discord_invite_url"],
                "discord_category_id": result["category_id"],
                "discord_text_channel_id": result["text_channel_id"],
                "discord_team_a_voice_id": result["team_a_voice_id"],
                "discord_team_b_voice_id": result["team_b_voice_id"],
            },
        )

    return result


async def delete_match_room(guild: discord.Guild, match_id: int) -> None:
    room = await db.get_room(match_id)
    if not room:
        return

    # Bloqueia o evento de entrada tardia ANTES de devolver jogadores.
    closing_match_ids.add(int(match_id))
    try:
        voice_ids = [int(x) for x in (room.get("team_a_voice_id"), room.get("team_b_voice_id")) if x]
        waiting = guild.get_channel(DISCORD_LOBBY_CHANNEL_ID) if DISCORD_LOBBY_CHANNEL_ID else None
        if not isinstance(waiting, discord.VoiceChannel) or waiting.guild.id != guild.id:
            raise RuntimeError(f"Partida {match_id}: sala de espera {DISCORD_LOBBY_CHANNEL_ID} nao encontrada; limpeza bloqueada")
    
        # Confirma acesso ao destino antes de iniciar qualquer exclusao.
        bot_member = guild.me
        if bot_member is None or not waiting.permissions_for(bot_member).connect or not waiting.permissions_for(bot_member).view_channel:
            raise RuntimeError(f"Partida {match_id}: bot sem acesso a sala de espera; limpeza bloqueada")
    
        # Aguarda eventos de movimentacao ja iniciados antes do bloqueio.
        await asyncio.sleep(0.7)
        for voice_id in voice_ids:
            channel = guild.get_channel(voice_id)
            if not isinstance(channel, discord.VoiceChannel):
                continue
            for member in list(channel.members):
                if member.voice and member.voice.channel and member.voice.channel.id == channel.id:
                    try:
                        await member.move_to(waiting, reason=f"GIGAX partida #{match_id} encerrada")
                        logger.info("Partida %s: jogador %s devolvido a espera %s", match_id, member.id, waiting.id)
                    except Exception:
                        logger.exception("Partida %s: falha ao devolver jogador %s; limpeza bloqueada", match_id, member.id)
                        raise RuntimeError(f"Partida {match_id}: falha ao devolver jogadores; limpeza adiada")
    
        # NUNCA exclua um canal com jogadores: isso desconecta quem estiver nele.
        await asyncio.sleep(0.7)
        for voice_id in voice_ids:
            channel = guild.get_channel(voice_id)
            if isinstance(channel, discord.VoiceChannel) and channel.members:
                logger.warning("Partida %s: canal %s ainda ocupado (%s); limpeza adiada", match_id, voice_id, len(channel.members))
                raise RuntimeError(f"Partida {match_id}: canal de voz ainda ocupado; limpeza adiada")
    
        deletion_failed = False
        for cid in (room.get("text_channel_id"), room.get("team_a_voice_id"), room.get("team_b_voice_id")):
            if cid:
                channel = guild.get_channel(int(cid))
                if channel:
                    try:
                        if isinstance(channel, discord.VoiceChannel) and channel.members:
                            raise RuntimeError("Canal ocupado: exclusao proibida")
                        await channel.delete(reason=f"GIGAX partida #{match_id} encerrada")
                    except Exception:
                        deletion_failed = True
                        logger.exception("Falha ao remover canal %s da partida %s", cid, match_id)
    
        category_id = room.get("category_id")
        if category_id and not DISCORD_MATCH_CATEGORY_ID:
            category = guild.get_channel(int(category_id))
            if isinstance(category, discord.CategoryChannel):
                try:
                    if not category.channels:
                        await category.delete(reason=f"GIGAX partida #{match_id} encerrada")
                except Exception:
                    deletion_failed = True
                    logger.exception("Falha ao remover categoria da partida %s", match_id)
    
        if deletion_failed:
            raise RuntimeError(f"Limpeza parcial da partida {match_id}; tentara novamente")
        if not (990000 <= match_id <= 999999):
            await api.report_voice_deleted(match_id)
        await db.mark_deleted(match_id)
        await db.log_event(match_id, "discord_room_deleted")
        closing_match_ids.discard(int(match_id))
    finally:
        closing_match_ids.discard(int(match_id))



# HTTP API local para o painel administrativo Laravel.
# O servidor compartilha o MESMO bot e o MESMO loop asyncio.
def _event_auth(request: web.Request) -> bool:
    supplied = request.headers.get("X-GIGAX-BOT-TOKEN", "")
    return bool(GIGAX_EVENT_TOKEN and supplied and hmac.compare_digest(supplied, GIGAX_EVENT_TOKEN))


@web.middleware
async def _event_middleware(request: web.Request, handler):
    if not _event_auth(request):
        return web.json_response({"ok": False, "error": "unauthorized"}, status=401)
    try:
        return await handler(request)
    except (ValueError, KeyError, TypeError) as exc:
        return web.json_response({"ok": False, "error": "invalid request"}, status=400)
    except Exception:
        logger.exception("GIGAX Event API: falha em %s", request.path)
        return web.json_response({"ok": False, "error": "internal error"}, status=500)


def _event_guild():
    guild = bot.get_guild(GUILD_ID)
    if not bot.is_ready() or guild is None:
        raise RuntimeError("bot/guild not ready")
    return guild


def _event_ids(value):
    if not isinstance(value, list) or len(value) > 20:
        raise ValueError("invalid ids")
    ids = []
    for item in value:
        v = str(item)
        if not v.isdigit() or not 15 <= len(v) <= 20:
            raise ValueError("invalid discord id")
        ids.append(int(v))
    return list(dict.fromkeys(ids))


def _event_match_id(data):
    mid = int(data.get("match_id", 0))
    if mid <= 0:
        raise ValueError("invalid match id")
    return mid


def _event_db_snapshot():
    conn = db.connect()
    try:
        cur = conn.cursor()
        cur.execute("SELECT TOP 100 match_id, category_id, text_channel_id, team_a_voice_id, team_b_voice_id, status FROM dbo.gigax_discord_match_rooms WHERE deleted_at IS NULL ORDER BY updated_at DESC")
        rooms = [dict(zip([c[0] for c in cur.description], row)) for row in cur.fetchall()]
        cur.execute("SELECT TOP 50 id, match_id, event_type, created_at FROM dbo.gigax_bot_events ORDER BY id DESC")
        events = [dict(zip([c[0] for c in cur.description], row)) for row in cur.fetchall()]
        for ev in events:
            ev["created_at"] = str(ev["created_at"])
        return rooms, events
    finally:
        conn.close()


async def _event_health(request):
    guild = bot.get_guild(GUILD_ID)
    return web.json_response({"ok": bool(bot.is_ready() and guild), "online": bot.is_ready(),
                              "guild_id": str(GUILD_ID), "guild_name": guild.name if guild else None})


async def _event_status(request):
    rooms, events = await asyncio.to_thread(_event_db_snapshot)
    guild = bot.get_guild(GUILD_ID)
    return web.json_response({"ok": bool(bot.is_ready() and guild), "online": bot.is_ready(),
                              "guild_id": str(GUILD_ID), "guild_name": guild.name if guild else None,
                              "rooms": rooms, "rooms_count": len(rooms), "events_count": len(events),
                              "pending": 0})


async def _event_events(request):
    _, events = await asyncio.to_thread(_event_db_snapshot)
    return web.json_response({"ok": True, "events": events})


async def _event_create(request):
    data = await request.json()
    mid = _event_match_id(data)
    # Testes isolados em faixa reservada, sem reaproveitar IDs de partidas reais.
    if mid < 990000 or mid > 999999:
        return web.json_response({"ok": False, "error": "test match id must be 990000..999999"}, status=400)
    a = _event_ids(data.get("team_a_discord_ids", []))
    b = _event_ids(data.get("team_b_discord_ids", []))
    if set(a) & set(b):
        raise ValueError("overlapping teams")
    guild = _event_guild()
    async with room_operation_lock:
        room = await create_match_room(guild, {"match_id": mid, "display_mode": "TESTE ADMIN",
                                               "map_name": "TESTE ADMIN", "team_a_discord_ids": a,
                                               "team_b_discord_ids": b})
    return web.json_response({"ok": True, "match_id": mid, "room": room})


async def _event_move(request):
    data = await request.json()
    mid = _event_match_id(data)
    a = _event_ids(data.get("team_a_discord_ids", []))
    b = _event_ids(data.get("team_b_discord_ids", []))
    if set(a) & set(b):
        raise ValueError("overlapping teams")
    guild = _event_guild()
    async with room_operation_lock:
        room = await db.get_room(mid)
        if not room or room.get("status") != "created":
            return web.json_response({"ok": False, "error": "room not found"}, status=404)
        va, vb = int(room["team_a_voice_id"]), int(room["team_b_voice_id"])
        if not isinstance(guild.get_channel(va), discord.VoiceChannel) or not isinstance(guild.get_channel(vb), discord.VoiceChannel):
            return web.json_response({"ok": False, "error": "voice channels missing"}, status=409)
        await db.save_assignments(mid, a, b, va, vb)
        await move_connected_players(guild, mid, a, b, va, vb)
    return web.json_response({"ok": True, "match_id": mid})


async def _event_cleanup(request):
    data = await request.json()
    mid = _event_match_id(data)
    # Exclusao administrativa so para salas de TESTE; partidas reais continuam no fluxo automatico.
    if mid < 990000 or mid > 999999:
        return web.json_response({"ok": False, "error": "admin cleanup restricted to test rooms"}, status=403)
    guild = _event_guild()
    async with room_operation_lock:
        await delete_match_room(guild, mid)
    return web.json_response({"ok": True, "match_id": mid})


async def _event_veto(request):
    # O bot atual ja faz polling do Laravel; nao disparar criacao duplicada por webhook.
    return web.json_response({"ok": True, "accepted": True, "mode": "polling"})


async def _event_match_ended(request):
    # Limpeza real fica a cargo do endpoint Laravel cleanup-voice.
    return web.json_response({"ok": True, "accepted": True, "mode": "polling"})


async def start_event_server():
    global event_runner
    if event_runner is not None:
        return
    if not GIGAX_EVENT_TOKEN:
        logger.error("Event Server nao iniciado: token compartilhado ausente no .env do BOT")
        return
    app = web.Application(middlewares=[_event_middleware], client_max_size=16 * 1024)
    app.router.add_get("/health", _event_health)
    app.router.add_get("/admin/status", _event_status)
    app.router.add_get("/admin/events", _event_events)
    app.router.add_post("/admin/test-create", _event_create)
    app.router.add_post("/admin/move", _event_move)
    app.router.add_post("/admin/cleanup", _event_cleanup)
    app.router.add_post("/events/veto-finished", _event_veto)
    app.router.add_post("/events/match-ended", _event_match_ended)
    runner = web.AppRunner(app, access_log=None)
    await runner.setup()
    try:
        await web.TCPSite(runner, GIGAX_EVENT_HOST, GIGAX_EVENT_PORT).start()
    except Exception:
        await runner.cleanup()
        raise
    event_runner = runner
    logger.info("GIGAX Event Server ativo em http://%s:%s", GIGAX_EVENT_HOST, GIGAX_EVENT_PORT)

@tasks.loop(seconds=GIGAX_POLL_SECONDS)
async def match_worker():
    guild = bot.get_guild(GUILD_ID)
    if guild is None:
        logger.warning("Guild %s ainda não disponível.", GUILD_ID)
        return

    try:
        matches = await api.pending_voice_matches()
        for match in matches:
            try:
                async with room_operation_lock:
                    await create_match_room(guild, match)
            except Exception:
                logger.exception("Falha ao provisionar Discord para partida %s", match.get("match_id"))
    except Exception:
        logger.exception("Falha consultando partidas pendentes no Laravel.")

    try:
        cleanup = await api.cleanup_matches()
        for match in cleanup:
            try:
                async with room_operation_lock:
                    await delete_match_room(guild, int(match["match_id"]))
            except Exception:
                logger.exception("Falha no cleanup da partida %s", match.get("match_id"))
    except Exception:
        logger.exception("Falha consultando cleanup de salas.")


@match_worker.before_loop
async def before_match_worker():
    await bot.wait_until_ready()


@bot.event
async def on_ready():
    logger.info("GIGAX Bot conectado como %s (%s)", bot.user, getattr(bot.user, "id", "?"))
    logger.info("Servidor configurado: %s", GUILD_ID)

    await db.ensure_schema()
    await api.start()
    await start_event_server()

    if not match_worker.is_running():
        match_worker.start()


@bot.event
async def on_voice_state_update(member: discord.Member, before: discord.VoiceState,
                                after: discord.VoiceState):
    # Late join: any voice channel in the configured guild, not only waiting room.
    if member.bot or member.guild.id != GUILD_ID or after.channel is None:
        return
    if before.channel is not None and before.channel.id == after.channel.id:
        return
    try:
        assignment = await db.assigned_voice(member.id)
        if not assignment or int(assignment["match_id"]) in closing_match_ids:
            return
        await move_assigned_member(member, assignment,
                                   reason=f"GIGAX partida #{assignment['match_id']} entrada na voz")
    except Exception:
        logger.exception("Falha ao processar estado de voz do jogador %s", member.id)


@bot.command(name="gigaxstatus")
@commands.has_permissions(administrator=True)
async def gigaxstatus(ctx: commands.Context):
    await ctx.reply(
        f"✅ GIGAX Discord Bot online\n"
        f"Servidor: `{ctx.guild.name if ctx.guild else GUILD_ID}`\n"
        f"API: `{GIGAX_API_BASE}`\n"
        f"Banco interno: `{BOT_DB_DATABASE}`"
    )


async def shutdown():
    global event_runner
    if event_runner is not None:
        await event_runner.cleanup()
        event_runner = None
    try:
        if match_worker.is_running():
            match_worker.cancel()
    except Exception:
        pass
    await api.close()


def main():
    try:
        bot.run(DISCORD_TOKEN, log_handler=None)
    finally:
        try:
            asyncio.run(shutdown())
        except Exception:
            pass


if __name__ == "__main__":
    main()
