import os
from PIL import Image
from django.conf import settings

# 🚩 IMPORTANT: Is file ke TOP par koi bhi model import nahi hona chahiye (Circular Import se bachne ke liye)

def apply_videsh_chalo_watermark(image_path):
    """
    Universal Watermark Engine v2.6 (Flexible Positioning)
    Removed emojis to prevent UnicodeEncodeError.
    """
    if not image_path or not os.path.exists(image_path):
        return

    try:
        # 1. Main image load karein
        main_img = Image.open(image_path).convert("RGBA")
        img_w, img_h = main_img.size

        # 2. Logo path
        logo_path = os.path.join(settings.BASE_DIR, 'static/images/videsh_chalo_logo.png')
        
        if not os.path.exists(logo_path):
            print(f"LOG: Watermark Logo not found at {logo_path}")
            return

        logo = Image.open(logo_path).convert("RGBA")
        logo_w, logo_h = logo.size

        # 3. Logo Resize (Image width ka 15-20% - Adjust as needed)
        target_width = int(img_w * 0.18) 
        target_height = int(logo_h * (target_width / logo_w))
        logo = logo.resize((target_width, target_height), Image.Resampling.LANCZOS)

        # 4. Opacity 60%
        alpha = logo.split()[3]
        alpha = alpha.point(lambda p: p * 0.6)
        logo.putalpha(alpha)

        # 5. 🚩 POSITIONING LOGIC (Yahan se 'idhar-udhar' karein)
        margin = 30 # Kono se kitna gap chahiye
        
        # --- Option A: CENTER (Current) ---
        # pos_x = (img_w - target_width) // 2
        # pos_y = (img_h - target_height) // 2

        # --- Option B: BOTTOM RIGHT (Professional Choice) ---
        pos_x = img_w - target_width - margin
        pos_y = img_h - target_height - margin

        # --- Option C: TOP RIGHT ---
        # pos_x = img_w - target_width - margin
        # pos_y = margin

        # --- Option D: BOTTOM LEFT ---
        # pos_x = margin
        # pos_y = img_h - target_height - margin

        # 6. Paste Logo
        main_img.paste(logo, (pos_x, pos_y), logo)
        
        # 7. Final Save
        if image_path.lower().endswith(('.jpg', '.jpeg')):
            main_img = main_img.convert("RGB")
        
        main_img.save(image_path, quality=90, optimize=True)
        print(f"SUCCESS: Watermark applied to {os.path.basename(image_path)}")

    except Exception as e:
        print(f"ERROR: Watermark process failed: {str(e)}")


# --- 💰 WALLET SYSTEM FUNCTIONS (Clean Logs) ---

def add_v_coins(user, amount, reason):
    try:
        from .models import CandidateWallet, CoinTransaction
        wallet, _ = CandidateWallet.objects.get_or_create(user=user)
        wallet.coins += amount
        wallet.save()

        CoinTransaction.objects.create(
            wallet=wallet,
            amount=amount,
            transaction_type='Credit',
            reason=reason
        )
        print(f"WALLET: Added {amount} coins to {user.username}")
        return True
    except Exception as e:
        print(f"WALLET_ERROR: Could not add coins: {str(e)}")
        return False

def deduct_v_coins(user, amount, reason):
    try:
        from .models import CandidateWallet, CoinTransaction
        wallet, created = CandidateWallet.objects.get_or_create(user=user)
        
        if wallet.coins >= amount:
            wallet.coins -= amount
            wallet.save()
            
            CoinTransaction.objects.create(
                wallet=wallet,
                amount=amount,
                transaction_type='Debit',
                reason=reason
            )
            print(f"WALLET: Deducted {amount} coins from {user.username}")
            return True
        
        print(f"WALLET: Low balance for {user.username}")
        return False
        
    except Exception as e:
        print(f"WALLET_ERROR: Could not deduct coins: {str(e)}")
        return False