"""
Service de gestion des recharges TIM BUSINESS
Gestion des commissions 10% (4% TIM BUSINESS + 6% TIM CASH)
"""

import json
from fastapi import HTTPException
from sqlalchemy.orm import Session
from datetime import datetime
from typing import Dict, Any, Optional
import uuid
import logging

from models.models import Notification, NotificationPriority, PrelevementRequest, Transaction, TransactionStatus, TransactionType, User
# from models.tim_business import (
#     TIMBusinessRecharge,
#     RechargeStatus,
#     RechargeCommission,
#     CommissionType,
#     TIMCashCompanyAccount
# )
from schemas.transaction import WalletTransactionRequest
from utility.stock import get_admin_stock
from utility.stock import get_admin_stock
from services.users import get_user_wallet
logger = logging.getLogger(__name__)


# class TIMBusinessRechargeService:
#     """Service pour gérer les recharges TIM BUSINESS"""
    
#     # Configuration des taux de commission
#     TOTAL_COMMISSION_RATE = 0.10  # 10%
#     BUSINESS_COMMISSION_RATE = 0.04  # 4% pour TIM BUSINESS
#     TIMCASH_COMMISSION_RATE = 0.06  # 6% pour TIM CASH
    
#     def __init__(self, db: Session):
#         self.db = db
    
#     def calculate_commission(self, amount: float) -> Dict[str, float]:
#         """
#         Calculer les commissions pour une recharge
        
#         Args:
#             amount: Montant de la recharge
            
#         Returns:
#             Dict avec les montants calculés
#         """
#         total_commission = amount * self.TOTAL_COMMISSION_RATE
#         business_commission = amount * self.BUSINESS_COMMISSION_RATE
#         timcash_commission = amount * self.TIMCASH_COMMISSION_RATE
#         total_amount = amount + total_commission
        
#         return {
#             "amount": amount,
#             "total_commission": round(total_commission, 2),
#             "business_commission": round(business_commission, 2),
#             "timcash_commission": round(timcash_commission, 2),
#             "total_amount": round(total_amount, 2)
#         }
    
#     def validate_recharge(
#         self,
#         business_user: Any,
#         beneficiary_user: Any,
#         amount: float
#     ) -> Dict[str, Any]:
#         """
#         Valider une recharge avant traitement
        
#         Returns:
#             Dict avec success (bool) et message (str)
#         """
#         # Vérifier que le rechargeur est TIM BUSINESS
#         if business_user.account_type != "TIM_BUSINESS":
#             return {
#                 "success": False,
#                 "message": "Seuls les comptes TIM BUSINESS peuvent effectuer des recharges"
#             }
        
#         # Vérifier que le bénéficiaire est TIM MINI ou TIM MAXI
#         if beneficiary_user.account_type not in ["TIM_MINI", "TIM_MAXI"]:
#             return {
#                 "success": False,
#                 "message": "Les recharges sont uniquement possibles vers TIM MINI ou TIM MAXI"
#             }
        
#         # Vérifier le montant minimum
#         if amount < 100:
#             return {
#                 "success": False,
#                 "message": "Le montant minimum de recharge est de 100 FCFA"
#             }
        
#         # Calculer le montant total à débiter
#         calculations = self.calculate_commission(amount)
#         total_to_debit = calculations["total_amount"]
        
#         # Vérifier le solde du compte TIM BUSINESS
#         if business_user.balance < total_to_debit:
#             return {
#                 "success": False,
#                 "message": f"Solde insuffisant. Vous avez besoin de {total_to_debit} FCFA (recharge + commission 10%)"
#             }
        
#         # Vérifier les limites du compte bénéficiaire
#         if beneficiary_user.account_type == "TIM_MINI":
#             max_balance = 2000000  # 2M FCFA
#             if beneficiary_user.balance + amount > max_balance:
#                 return {
#                     "success": False,
#                     "message": f"Le compte TIM MINI ne peut pas dépasser {max_balance} FCFA"
#                 }
#         elif beneficiary_user.account_type == "TIM_MAXI":
#             max_balance = 2000000  # 2M FCFA
#             if beneficiary_user.balance + amount > max_balance:
#                 return {
#                     "success": False,
#                     "message": f"Le compte TIM MAXI ne peut pas dépasser {max_balance} FCFA"
#                 }
        
#         return {
#             "success": True,
#             "message": "Validation réussie",
#             "calculations": calculations
#         }
    
#     def process_recharge(
#         self,
#         business_user_id: str,
#         beneficiary_user_id: str,
#         beneficiary_phone: str,
#         amount: float,
#         description: Optional[str] = None,
#         metadata: Optional[Dict] = None
#     ) -> Dict[str, Any]:
#         """
#         Traiter une recharge TIM BUSINESS
        
#         Args:
#             business_user_id: ID du compte TIM BUSINESS
#             beneficiary_user_id: ID du bénéficiaire
#             beneficiary_phone: Téléphone du bénéficiaire
#             amount: Montant de la recharge
#             description: Description optionnelle
#             metadata: Métadonnées (IP, device, location)
            
#         Returns:
#             Dict avec le résultat de la transaction
#         """
#         try:
#             # Récupérer les utilisateurs  from models.user import User
#             business_user = self.db.query(User).filter(User.id == business_user_id).first()
#             beneficiary_user = self.db.query(User).filter(User.id == beneficiary_user_id).first()
            
#             if not business_user or not beneficiary_user:
#                 return {
#                     "success": False,
#                     "message": "Utilisateur non trouvé"
#                 }
            
#             # Valider la recharge
#             validation = self.validate_recharge(business_user, beneficiary_user, amount)
#             if not validation["success"]:
#                 return validation
            
#             calculations = validation["calculations"]
            
#             # Générer une référence unique
#             reference = f"TBR-{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:8].upper()}"
            
#             # Créer la transaction de recharge
#             recharge = TIMBusinessRecharge(
#                 id=str(uuid.uuid4()),
#                 business_user_id=business_user_id,
#                 business_account_type=business_user.account_type,
#                 beneficiary_user_id=beneficiary_user_id,
#                 beneficiary_phone=beneficiary_phone,
#                 beneficiary_account_type=beneficiary_user.account_type,
#                 amount=calculations["amount"],
#                 total_commission=calculations["total_commission"],
#                 business_commission=calculations["business_commission"],
#                 timcash_commission=calculations["timcash_commission"],
#                 total_amount=calculations["total_amount"],
#                 business_balance_before=business_user.balance,
#                 beneficiary_balance_before=beneficiary_user.balance,
#                 status=RechargeStatus.PROCESSING,
#                 reference=reference,
#                 description=description,
#                 ip_address=metadata.get("ip_address") if metadata else None,
#                 device_info=metadata.get("device_info") if metadata else None,
#                 location=metadata.get("location") if metadata else None
#             )
            
#             # Débiter le compte TIM BUSINESS (montant + commission totale)
#             business_user.balance -= calculations["total_amount"]
            
#             # Créditer le compte bénéficiaire (montant sans commission)
#             beneficiary_user.balance += calculations["amount"]
            
#             # Mettre à jour les soldes après transaction
#             recharge.business_balance_after = business_user.balance
#             recharge.beneficiary_balance_after = beneficiary_user.balance
            
#             # Créer les commissions
#             # 1. Commission TIM BUSINESS (4%) - reste sur le wallet
#             business_commission_record = RechargeCommission(
#                 id=str(uuid.uuid4()),
#                 recharge_id=recharge.id,
#                 commission_type=CommissionType.TIM_BUSINESS,
#                 recipient_user_id=business_user_id,
#                 recipient_type="tim_business",
#                 amount=calculations["business_commission"],
#                 percentage=self.BUSINESS_COMMISSION_RATE * 100,
#                 status="credited",
#                 credited_at=datetime.utcnow()
#             )
            
#             # Créditer la commission sur le wallet TIM BUSINESS
#             business_user.balance += calculations["business_commission"]
#             business_user.total_commissions_earned = (
#                 getattr(business_user, 'total_commissions_earned', 0) + 
#                 calculations["business_commission"]
#             )
            
#             # 2. Commission TIM CASH (6%) - reversée sur CinetPay
#             timcash_commission_record = RechargeCommission(
#                 id=str(uuid.uuid4()),
#                 recharge_id=recharge.id,
#                 commission_type=CommissionType.TIM_CASH,
#                 recipient_user_id=None,  # Pas d'utilisateur, c'est l'entreprise
#                 recipient_type="tim_cash",
#                 amount=calculations["timcash_commission"],
#                 percentage=self.TIMCASH_COMMISSION_RATE * 100,
#                 status="credited",
#                 credited_at=datetime.utcnow()
#             )
            
#             # Créditer le compte de l'entreprise TIM CASH
#             self._credit_timcash_account(calculations["timcash_commission"])
            
#             # Marquer la recharge comme complétée
#             recharge.status = RechargeStatus.COMPLETED
#             recharge.completed_at = datetime.utcnow()
            
#             # Sauvegarder tout
#             self.db.add(recharge)
#             self.db.add(business_commission_record)
#             self.db.add(timcash_commission_record)
#             self.db.commit()
#             self.db.refresh(recharge)
            
#             return {
#                 "success": True,
#                 "message": "Recharge effectuée avec succès",
#                 "data": {
#                     "recharge_id": recharge.id,
#                     "reference": recharge.reference,
#                     "amount": calculations["amount"],
#                     "total_commission": calculations["total_commission"],
#                     "business_commission": calculations["business_commission"],
#                     "timcash_commission": calculations["timcash_commission"],
#                     "total_debited": calculations["total_amount"],
#                     "business_new_balance": business_user.balance,
#                     "beneficiary_new_balance": beneficiary_user.balance,
#                     "status": recharge.status.value,
#                     "completed_at": recharge.completed_at.isoformat()
#                 }
#             }
            
#         except Exception as e:
#             self.db.rollback()
#             return {
#                 "success": False,
#                 "message": f"Erreur lors du traitement de la recharge: {str(e)}"
#             }
    
#     def _credit_timcash_account(self, amount: float):
#         """
#         Créditer le compte de l'entreprise TIM CASH
        
#         Args:
#             amount: Montant à créditer (6% de commission)
#         """
#         # Récupérer ou créer le compte TIM CASH
#         company_account = self.db.query(TIMCashCompanyAccount).first()
        
#         if not company_account:
#             company_account = TIMCashCompanyAccount(
#                 id=str(uuid.uuid4()),
#                 balance=0.0,
#                 total_commissions_received=0.0,
#                 total_transferred_to_cinetpay=0.0,
#                 total_recharges_count=0
#             )
#             self.db.add(company_account)
        
#         # Créditer le compte
#         company_account.balance += amount
#         company_account.total_commissions_received += amount
#         company_account.total_recharges_count += 1
#         company_account.last_recharge_at = datetime.utcnow()
#         company_account.updated_at = datetime.utcnow()
        
#         self.db.commit()
    
#     def get_recharge_history(
#         self,
#         user_id: str,
#         user_type: str = "business",
#         limit: int = 50,
#         offset: int = 0
#     ) -> Dict[str, Any]:
#         """
#         Récupérer l'historique des recharges
        
#         Args:
#             user_id: ID de l'utilisateur
#             user_type: "business" ou "beneficiary"
#             limit: Nombre de résultats
#             offset: Décalage
            
#         Returns:
#             Dict avec l'historique
#         """
#         query = self.db.query(TIMBusinessRecharge)
        
#         if user_type == "business":
#             query = query.filter(TIMBusinessRecharge.business_user_id == user_id)
#         else:
#             query = query.filter(TIMBusinessRecharge.beneficiary_user_id == user_id)
        
#         total = query.count()
#         recharges = query.order_by(TIMBusinessRecharge.created_at.desc()).limit(limit).offset(offset).all()
        
#         return {
#             "success": True,
#             "total": total,
#             "limit": limit,
#             "offset": offset,
#             "data": [
#                 {
#                     "id": r.id,
#                     "reference": r.reference,
#                     "amount": r.amount,
#                     "total_commission": r.total_commission,
#                     "business_commission": r.business_commission,
#                     "timcash_commission": r.timcash_commission,
#                     "total_amount": r.total_amount,
#                     "status": r.status.value,
#                     "beneficiary_phone": r.beneficiary_phone,
#                     "created_at": r.created_at.isoformat(),
#                     "completed_at": r.completed_at.isoformat() if r.completed_at else None
#                 }
#                 for r in recharges
#             ]
#         }
    
#     def get_commission_stats(self, business_user_id: str) -> Dict[str, Any]:
#         """
#         Récupérer les statistiques de commission pour un compte TIM BUSINESS
        
#         Args:
#             business_user_id: ID du compte TIM BUSINESS
            
#         Returns:
#             Dict avec les statistiques
#         """
#         # Total des commissions gagnées
#         total_commissions = self.db.query(
#             RechargeCommission
#         ).join(
#             TIMBusinessRecharge
#         ).filter(
#             TIMBusinessRecharge.business_user_id == business_user_id,
#             RechargeCommission.commission_type == CommissionType.TIM_BUSINESS,
#             RechargeCommission.status == "credited"
#         ).all()
        
#         total_earned = sum(c.amount for c in total_commissions)
#         total_recharges = len(set(c.recharge_id for c in total_commissions))
        
#         return {
#             "success": True,
#             "data": {
#                 "total_commissions_earned": round(total_earned, 2),
#                 "total_recharges_count": total_recharges,
#                 "average_commission_per_recharge": round(total_earned / total_recharges, 2) if total_recharges > 0 else 0,
#                 "commission_rate": f"{self.BUSINESS_COMMISSION_RATE * 100}%"
#             }
#         }

async def prelevement_compte_client(current_user: User,request_data: WalletTransactionRequest, db : Session ):
    
    try:
        # 1. Trouver le bénéficiaire
        recipient = db.query(User).filter(User.phone == request_data.phone).first()
        if not recipient:
            raise HTTPException(status_code=404, detail="Client destinataire introuvable")
        if recipient.id == current_user.id:
            raise HTTPException(status_code=400, detail="Impossible d'envoyer de l'argent à soi-même")
        
        prelev_id = str(uuid.uuid4())
        
        demand = PrelevementRequest(
        id=prelev_id,
        merchant_id=current_user.id,
        client_id=recipient.id,
        amount=request_data.amount,
        description="Demande de prélèvement",
        status="pending"
     )
        db.add(demand)
        db.commit()

        # 7. Notifications
        notification = Notification(
                id=str(uuid.uuid4()),
                user_id=recipient.id,
                title="Nouvelle demande de prélèvement",
                message=f"{current_user.full_name} demande un prélèvement de {request_data.amount} XOF",
                type="prelevement_request",
                priority=NotificationPriority.HIGH,
                amount=request_data.amount,
                merchant=current_user.full_name,
                created_at=datetime.utcnow(),
                prelevement_id=prelev_id
            )
        db.add(notification)

        # 8. Commit final
        db.commit()

        # 9. Réponse
        return {
        "message": "Demande de prélèvement envoyée",
        "prelevement_id": demand.id,
        "status": demand.status
    }

    except Exception as e:
        db.rollback()
        logger.error(f"Erreur transfert client-client: {str(e)}")
        raise HTTPException(status_code=500, detail="Erreur interne lors du transfert")
    
