"""Referral reward logic.

- Active-batch reward: every N active referrals (first deposit OR purchase)
  pays the referrer REFERRAL_ACTIVE_REWARD.
- Purchase reward: each time the referred user accumulates an additional
  REFERRAL_PURCHASE_MIN ($5) in total purchases, the referrer earns
  REFERRAL_PURCHASE_REWARD ($0.40) — so big spenders keep paying rewards.
"""
from telegram import Bot
from database.db import DB
from config import (REFERRAL_ACTIVE_THRESHOLD, REFERRAL_ACTIVE_REWARD,
                    REFERRAL_PURCHASE_MIN, REFERRAL_PURCHASE_REWARD)
from services.notifications import notify_staff
from utils.helpers import money


async def _credit(referrer_id: int, amount: float):
    await DB.execute(
        "UPDATE users SET balance = balance + ?, "
        "referral_earnings = referral_earnings + ? WHERE user_id=?",
        (amount, amount, referrer_id))


async def mark_active_and_reward(bot: Bot, user_id: int):
    """Mark referral as active (first deposit/purchase) and reward per batch."""
    row = await DB.fetchone(
        "SELECT is_active, referred_by FROM users WHERE user_id=?", (user_id,))
    if not row or row["is_active"]:
        return
    await DB.execute("UPDATE users SET is_active=1 WHERE user_id=?", (user_id,))
    ref = row["referred_by"]
    if not ref:
        return
    cnt = (await DB.fetchone(
        "SELECT COUNT(*) AS c FROM users WHERE referred_by=? AND is_active=1",
        (ref,)))["c"]
    if cnt and cnt % REFERRAL_ACTIVE_THRESHOLD == 0:
        try:
            await DB.execute(
                "INSERT INTO referral_rewards(referrer_id, referred_id, "
                "reward_type, amount) VALUES (?,?,?,?)",
                (ref, user_id, f"active_batch_{cnt}", REFERRAL_ACTIVE_REWARD))
        except Exception:
            return
        await _credit(ref, REFERRAL_ACTIVE_REWARD)
        try:
            await bot.send_message(
                ref,
                f"🎁 <b>Referral Bonus!</b>\n"
                f"{REFERRAL_ACTIVE_THRESHOLD} active referrals reached.\n"
                f"Credited: <b>{money(REFERRAL_ACTIVE_REWARD)}</b>",
                parse_mode="HTML")
        except Exception:
            pass
        await notify_staff(bot,
            f"🎁 <b>Referral Reward</b>\nReferrer: <code>{ref}</code>\n"
            f"Type: {REFERRAL_ACTIVE_THRESHOLD}-active batch\n"
            f"Amount: {money(REFERRAL_ACTIVE_REWARD)}")


async def maybe_purchase_reward(bot: Bot, user_id: int):
    """Pay referrer REFERRAL_PURCHASE_REWARD for every cumulative
    REFERRAL_PURCHASE_MIN the referred user spends."""
    row = await DB.fetchone(
        "SELECT total_purchases, referred_by FROM users WHERE user_id=?",
        (user_id,))
    if not row or not row["referred_by"]:
        return
    ref = row["referred_by"]
    total = row["total_purchases"] or 0
    if total < REFERRAL_PURCHASE_MIN:
        return

    # How many milestones unlocked?
    earned = int(total // REFERRAL_PURCHASE_MIN)
    paid = (await DB.fetchone(
        "SELECT COUNT(*) AS c FROM referral_rewards "
        "WHERE referrer_id=? AND referred_id=? AND reward_type LIKE 'purchase%'",
        (ref, user_id)))["c"]
    new_payouts = earned - paid
    if new_payouts <= 0:
        return

    for i in range(new_payouts):
        milestone = paid + i + 1
        try:
            await DB.execute(
                "INSERT INTO referral_rewards(referrer_id, referred_id, "
                "reward_type, amount) VALUES (?, ?, ?, ?)",
                (ref, user_id, f"purchase_{milestone}", REFERRAL_PURCHASE_REWARD))
        except Exception:
            continue
        await _credit(ref, REFERRAL_PURCHASE_REWARD)
        try:
            await bot.send_message(
                ref,
                f"🎁 <b>Referral Purchase Bonus!</b>\n\n"
                f"Your referral spent {money(milestone * REFERRAL_PURCHASE_MIN)} total.\n"
                f"Credited: <b>{money(REFERRAL_PURCHASE_REWARD)}</b> to your wallet.",
                parse_mode="HTML")
        except Exception:
            pass
        await notify_staff(bot,
            f"🎁 <b>Referral Reward</b>\nReferrer: <code>{ref}</code>\n"
            f"Referred: <code>{user_id}</code>\nType: purchase milestone {milestone}\n"
            f"Amount: {money(REFERRAL_PURCHASE_REWARD)}")
