import logging
import discord
from datetime import datetime
import config
from database import db

# Set up local system logger
logger = logging.getLogger("gamble_bot")
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')

# File handler
file_handler = logging.FileHandler('gamble_bot.log', encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

# Console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

async def send_embed_to_channel(bot: discord.Client, channel_id: int, embed: discord.Embed):
    """Safely sends an embed to a specific channel."""
    if not channel_id:
        return
    try:
        channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id)
        if channel:
            await channel.send(embed=embed)
    except Exception as e:
        logger.error(f"Failed to send embed to channel {channel_id}: {e}")

async def log_suspicious_activity(bot: discord.Client, user: discord.User, activity_type: str, details: str):
    """Logs suspicious activity to the database and alerts admins via Discord log channel."""
    # Write to database
    await db.log_suspicious(user.id, user.name, activity_type, details)
    
    # Create Embed Alert
    embed = discord.Embed(
        title="🚨 ŞÜPHELİ AKTİVİTE TESPİT EDİLDİ",
        color=discord.Color.red(),
        timestamp=datetime.utcnow()
    )
    embed.add_field(name="Kullanıcı", value=f"{user.mention} ({user.name})", inline=True)
    embed.add_field(name="ID", value=f"`{user.id}`", inline=True)
    embed.add_field(name="Aktivite Tipi", value=f"**{activity_type}**", inline=False)
    embed.add_field(name="Detaylar", value=details, inline=False)
    
    # Send to admin log channel
    await send_embed_to_channel(bot, config.ADMIN_LOG_CHANNEL_ID, embed)

async def log_transaction(bot: discord.Client, user: discord.User, tx_type: str, amount: float, status: str, details: str = "") -> None:
    """Logs database economy transactions to the admin logs channel."""
    color = discord.Color.green() if tx_type == "deposit" else discord.Color.gold()
    if status == "rejected":
        color = discord.Color.red()
    elif status == "pending":
        color = discord.Color.blue()
        
    embed = discord.Embed(
        title=f"💸 İŞLEM GÜNLÜĞÜ: {tx_type.upper()}",
        color=color,
        timestamp=datetime.utcnow()
    )
    embed.add_field(name="Kullanıcı", value=f"{user.mention} ({user.name})", inline=True)
    embed.add_field(name="Discord ID", value=f"`{user.id}`", inline=True)
    embed.add_field(name="Miktar", value=f"**{amount:,.2f}** birim", inline=True)
    embed.add_field(name="Durum", value=f"`{status.upper()}`", inline=True)
    if details:
        embed.add_field(name="Detaylar/Not", value=details, inline=False)
        
    await send_embed_to_channel(bot, config.ADMIN_LOG_CHANNEL_ID, embed)
