"""
Routes pour la gestion des commissions
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from services.commission_service import CommissionService
from models.models import User, CommissionRate
from core.auth import get_admin_user
from schemas.commission import CommissionRateResponse, UpdateCommissionRequest, UpdateCommissionByIdRequest, RechargeCommissionBreakdown
from typing import List
import uuid
from datetime import datetime

from utility.auth_token import get_current_admin

router = APIRouter()

@router.get("/admin/commission-rates")
async def get_commission_rates(
    include_inactive: bool = True,
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """Récupérer tous les taux de commission (actives et inactives)"""
    query = db.query(CommissionRate)
    
    # Filtrer par statut si demandé
    if not include_inactive:
        query = query.filter(CommissionRate.is_active == True)
    
    rates = query.order_by(
        CommissionRate.is_active.desc(),  # Actives en premier
        CommissionRate.created_at.desc()  # Plus récentes en premier
    ).all()
    
    print(f"📊 [ADMIN] Récupération commissions: {len(rates)} trouvées (include_inactive={include_inactive})")
    
    commission_rates = [
        CommissionRateResponse(
            id=rate.id,
            name=rate.name,
            category=rate.category,
            value=rate.value,
            description=rate.description,
            is_active=rate.is_active,
            updated_by=rate.updated_by,
            created_at=rate.created_at,
            updated_at=rate.updated_at
        )
        for rate in rates
    ]
    
    return {
        "commission_rates": commission_rates,
        "total_count": len(commission_rates),
        "active_count": len([r for r in rates if r.is_active]),
        "inactive_count": len([r for r in rates if not r.is_active])
    }

@router.get("/commission-rates/recharge")
async def get_recharge_commission_rates(
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """Récupérer les taux de commission pour les recharges"""
    rates = CommissionService.get_recharge_commission_rates(db)
    return rates

@router.put("/commission-rates/{category}")
async def update_commission_rate(
    category: str,
    request: UpdateCommissionRequest,
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """Mettre à jour un taux de commission"""
    
    # Vérifier que la catégorie existe
    valid_categories = ["recharge_cinetpay", "loan_interest", "loan_penalty"]
    if category not in valid_categories:
        raise HTTPException(
            status_code=400, 
            detail=f"Catégorie invalide. Catégories valides: {valid_categories}"
        )
    
    # Vérifier que le taux est valide
    if request.value < 0 or request.value > 1:
        raise HTTPException(
            status_code=400,
            detail="Le taux doit être entre 0 et 1 (0% à 100%)"
        )
    
    # Mettre à jour le taux
    updated_rate = CommissionService.update_commission_rate(
        db=db,
        category=category,
        new_rate=request.value,
        updated_by=admin_user.id,
        description=request.description
    )
    
    return {
        "message": f"Taux de commission {category} mis à jour avec succès",
        "new_rate": updated_rate.value,
        "category": category
    }


@router.put("/admin/commission-rates/id/{commission_id}")
async def update_commission_by_id(
    commission_id: str,
    request: UpdateCommissionByIdRequest,
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """Mettre à jour une commission par son ID"""
    
    try:
        print(f"🔄 [ADMIN] Mise à jour commission ID: {commission_id} par {admin_user.email}")
        print(f"📝 Données reçues: {request.dict()}")
        
        # Vérifier que la commission existe
        existing_commission = db.query(CommissionRate).filter(
            CommissionRate.id == commission_id
        ).first()
        
        if not existing_commission:
            raise HTTPException(
                status_code=404,
                detail=f"Commission avec l'ID {commission_id} non trouvée"
            )
        
        # Validation des données
        if request.rate_type == "percentage" and request.value > 1:
            raise HTTPException(
                status_code=422,
                detail="Pour un taux en pourcentage, la valeur doit être entre 0 et 1 (ex: 0.03 pour 3%)"
            )
        
        if request.value < 0:
            raise HTTPException(
                status_code=422,
                detail="La valeur ne peut pas être négative"
            )
        
        # Mettre à jour les champs modifiés
        if request.name is not None:
            existing_commission.name = request.name
        if request.rate_type is not None:
            existing_commission.rate_type = request.rate_type
        if request.value is not None:
            existing_commission.value = request.value
        if request.category is not None:
            existing_commission.category = request.category
        if request.description is not None:
            existing_commission.description = request.description
        if request.min_amount is not None:
            existing_commission.min_amount = request.min_amount
        if request.max_amount is not None:
            existing_commission.max_amount = request.max_amount
        if request.is_active is not None:
            existing_commission.is_active = request.is_active
        
        # Mettre à jour les métadonnées
        existing_commission.updated_by = admin_user.id
        existing_commission.updated_at = datetime.utcnow()
        
        # Sauvegarder
        db.commit()
        db.refresh(existing_commission)
        
        print(f"✅ [ADMIN] Commission mise à jour: {existing_commission.name}")
        
        return {
            "success": True,
            "message": f"Commission '{existing_commission.name}' mise à jour avec succès",
            "commission": {
                "id": existing_commission.id,
                "name": existing_commission.name,
                "rate_type": existing_commission.rate_type,
                "value": existing_commission.value,
                "category": existing_commission.category,
                "description": existing_commission.description,
                "is_active": existing_commission.is_active,
                "updated_at": existing_commission.updated_at.isoformat() if existing_commission.updated_at else None
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"❌ [ADMIN] Erreur mise à jour commission: {str(e)}")
        db.rollback()
        raise HTTPException(
            status_code=500,
            detail=f"Erreur lors de la mise à jour: {str(e)}"
        )

@router.post("/admin/commission-rates")
async def create_commission_rate(
    request: UpdateCommissionByIdRequest,
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """Créer une nouvelle commission"""
    
    try:
        print(f" [ADMIN] Création commission par {admin_user.email}")
        print(f" Données reçues: {request.dict()}")
        
        # Validation des données obligatoires
        if not request.name:
            raise HTTPException(
                status_code=422,
                detail="Le nom de la commission est obligatoire"
            )
        
        if not request.category:
            raise HTTPException(
                status_code=422,
                detail="La catégorie de la commission est obligatoire"
            )
        
        if request.value is None:
            raise HTTPException(
                status_code=422,
                detail="La valeur de la commission est obligatoire"
            )
        
        # Validation des données
        if request.rate_type == "percentage" and request.value > 1:
            raise HTTPException(
                status_code=422,
                detail="Pour un taux en pourcentage, la valeur doit être entre 0 et 1 (ex: 0.03 pour 3%)"
            )
        
        if request.value < 0:
            raise HTTPException(
                status_code=422,
                detail="La valeur ne peut pas être négative"
            )
        
        # Créer la nouvelle commission
        new_commission = CommissionRate(
            id=str(uuid.uuid4()),
            name=request.name,
            rate_type=request.rate_type or "percentage",
            value=request.value,
            category=request.category,
            description=request.description or f"Commission {request.name}",
            min_amount=request.min_amount,
            max_amount=request.max_amount,
            is_active=request.is_active if request.is_active is not None else True,
            updated_by=admin_user.id,
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow()
        )
        
        # Sauvegarder
        db.add(new_commission)
        db.commit()
        db.refresh(new_commission)
        
        print(f" [ADMIN] Commission créée: {new_commission.name}")
        
        return {
            "success": True,
            "message": f"Commission '{new_commission.name}' créée avec succès",
            "commission": {
                "id": new_commission.id,
                "name": new_commission.name,
                "rate_type": new_commission.rate_type,
                "value": new_commission.value,
                "category": new_commission.category,
                "description": new_commission.description,
                "is_active": new_commission.is_active,
                "created_at": new_commission.created_at.isoformat(),
                "updated_at": new_commission.updated_at.isoformat()
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        print(f" [ADMIN] Erreur création commission: {str(e)}")
        db.rollback()
        raise HTTPException(
            status_code=500,
            detail=f"Erreur lors de la création: {str(e)}"
        )


@router.get("/commission-rates/calculate")
async def calculate_commission(
    amount: float,
    category: str = "recharge_cinetpay",
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """Calculer les commissions pour un montant donné"""
    
    if category == "recharge_cinetpay":
        commission_rates = CommissionService.get_recharge_commission_rates(db)
        calculation = CommissionService.calculate_commissions(amount, commission_rates)
    else:
        # Pour les autres catégories, utiliser le taux simple
        rates = CommissionService.get_commission_rates(db)
        if category not in rates:
            raise HTTPException(
                status_code=404,
                detail=f"Aucun taux de commission trouvé pour la catégorie {category}"
            )
        
        rate_value = rates[category]
        calculation = {
            "total_commission": amount * rate_value,
            "net_amount": amount,
            "total_payment": amount + (amount * rate_value)
        }
    
    return {
        "amount": amount,
        "category": category,
        "calculation": calculation
    }


@router.post("/admin/commission-rates/activate-mobile")
async def activate_commissions_mobile(
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """
    Activer les commissions dans l'application mobile
    
    Cette endpoint synchronise les taux de commission configurés
    vers l'application mobile pour qu'ils soient appliqués
    automatiquement lors des transactions.
    """
    try:
        print(f"📱 [ADMIN] Activation des commissions mobile par {admin_user.email}")
        
        # Récupérer toutes les commissions actives
        active_rates = db.query(CommissionRate).filter(
            CommissionRate.is_active == True
        ).all()
        
        if not active_rates:
            raise HTTPException(
                status_code=400,
                detail="Aucune commission active trouvée. Veuillez d'abord configurer des commissions."
            )
        
        # Préparer les données pour l'application mobile
        mobile_commission_config = {
            "commission_rates": {},
            "last_updated": datetime.utcnow().isoformat(),
            "updated_by": admin_user.email,
            "status": "active"
        }
        
        # Organiser les commissions par catégorie
        for rate in active_rates:
            mobile_commission_config["commission_rates"][rate.category] = {
                "id": rate.id,
                "name": rate.name,
                "rate_type": rate.rate_type,
                "value": rate.value,
                "description": rate.description,
                "min_amount": rate.min_amount,
                "max_amount": rate.max_amount,
                "created_at": rate.created_at.isoformat() if rate.created_at else None,
                "updated_at": rate.updated_at.isoformat() if rate.updated_at else None
            }
        
        # TODO: Ici, vous pouvez ajouter la logique pour :
        # 1. Envoyer une notification push aux applications mobiles
        # 2. Mettre à jour un cache Redis pour les apps mobiles
        # 3. Déclencher une synchronisation via WebSocket
        # 4. Enregistrer dans un log d'audit
        
        # Pour l'instant, on simule l'activation
        print(f"✅ [ADMIN] Configuration mobile générée:")
        print(f"   - {len(active_rates)} commissions activées")
        print(f"   - Catégories: {list(mobile_commission_config['commission_rates'].keys())}")
        
        # Retourner la configuration qui sera utilisée par l'app mobile
        return {
            "success": True,
            "message": f"Commissions activées avec succès dans l'application mobile",
            "mobile_config": mobile_commission_config,
            "summary": {
                "total_commissions": len(active_rates),
                "categories": list(mobile_commission_config["commission_rates"].keys()),
                "activated_at": mobile_commission_config["last_updated"],
                "activated_by": admin_user.email
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"❌ [ADMIN] Erreur activation commissions mobile: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"Erreur lors de l'activation des commissions: {str(e)}"
        )


@router.get("/admin/commission-rates/mobile-status")
async def get_mobile_commission_status(
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """
    Récupérer le statut des commissions dans l'application mobile
    """
    try:
        # Récupérer les commissions actives
        active_rates = db.query(CommissionRate).filter(
            CommissionRate.is_active == True
        ).all()
        
        # Calculer les statistiques
        total_active = len(active_rates)
        categories = [rate.category for rate in active_rates]
        
        # TODO: Récupérer le vrai statut depuis l'app mobile
        # Pour l'instant, on simule
        mobile_status = {
            "is_synchronized": total_active > 0,
            "last_sync": datetime.utcnow().isoformat() if total_active > 0 else None,
            "total_commissions": total_active,
            "active_categories": categories,
            "sync_status": "active" if total_active > 0 else "inactive"
        }
        
        # Calculer la dernière mise à jour
        last_updated = None
        if active_rates:
            valid_dates = [rate.updated_at for rate in active_rates if rate.updated_at is not None]
            if valid_dates:
                last_updated = max(valid_dates).isoformat()
        
        return {
            "mobile_status": mobile_status,
            "backend_status": {
                "total_commissions": total_active,
                "categories": categories,
                "last_updated": last_updated
            }
        }
        
    except Exception as e:
        print(f"❌ [ADMIN] Erreur statut commissions mobile: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"Erreur lors de la récupération du statut: {str(e)}"
        )


@router.get("/admin/commission-rates/recharge-breakdown")
async def get_recharge_commission_breakdown(
    amount: float,
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """
    Calculer la répartition des commissions pour une recharge

    FLUX CORRECT:
    1. Client veut recharger X FCFA
    2. TIM CASH ajoute sa commission (2%): +X*0.02
    3. Client paie: X + X*0.02 via Mobile Money
    4. CinetPay déduit SA commission (variable selon opérateur)
    5. TIM CASH reçoit le montant APRÈS déduction CinetPay

    Args:
        amount: Montant que le client veut recharger (en FCFA)

    Returns:
        Détail de la répartition avec le flux correct
    """
    try:
        if amount <= 0:
            raise HTTPException(status_code=400, detail="Le montant doit être positif")

        # Récupérer les taux de commission de recharge
        commission_rates = CommissionService.get_recharge_commission_rates(db)

        if not commission_rates:
            raise HTTPException(
                status_code=404,
                detail="Commission de recharge non configurée"
            )

        timcash_rate = commission_rates.get("timcash_rate", 0.02)  # 2%
        cinetpay_rate = commission_rates.get("cinetpay_rate", 0.01)  # ~1% (variable)

        # CALCUL CORRECT
        # 1. Client veut recharger: amount
        # 2. Commission TIM CASH ajoutée
        timcash_commission = amount * timcash_rate

        # 3. Montant à payer par le client
        amount_to_pay = amount + timcash_commission

        # 4. Commission CinetPay (estimation, variable selon opérateur)
        cinetpay_commission_estimate = amount_to_pay * cinetpay_rate

        # 5. Montant réel reçu par TIM CASH (après déduction CinetPay)
        amount_received_by_timcash = amount_to_pay - cinetpay_commission_estimate

        # Créer le breakdown pour la réponse
        breakdown = RechargeCommissionBreakdown(
            total_amount=round(amount_to_pay, 2),  # Total payé par le client
            total_commission=round(timcash_commission + cinetpay_commission_estimate, 2),  # Total des commissions
            cinetpay_commission=round(cinetpay_commission_estimate, 2),  # Commission CinetPay (estimée)
            timcash_commission=round(timcash_commission, 2),  # Commission TIM CASH
            net_amount=round(amount_received_by_timcash, 2)  # Montant réel reçu par TIM CASH
        )

        print(f"💰 [ADMIN] Calcul répartition recharge:")
        print(f"   • Montant demandé: {amount} FCFA")
        print(f"   • Commission TIM CASH ({timcash_rate*100}%): +{timcash_commission} FCFA")
        print(f"   • Montant à payer: {amount_to_pay} FCFA")
        print(f"   • Commission CinetPay estimée (~{cinetpay_rate*100}%): -{cinetpay_commission_estimate} FCFA")
        print(f"   • Montant reçu par TIM CASH: {amount_received_by_timcash} FCFA")

        return {
            "success": True,
            "message": f"Répartition calculée pour {amount} FCFA",
            "breakdown": breakdown,
            "rates": {
                "total_rate": f"{(timcash_rate + cinetpay_rate) * 100}%",
                "cinetpay_rate": f"~{cinetpay_rate * 100}% (variable selon opérateur)",
                "timcash_rate": f"{timcash_rate * 100}%"
            },
            "flow": {
                "step1": f"Client veut recharger: {amount} FCFA",
                "step2": f"TIM CASH ajoute {timcash_rate*100}%: +{timcash_commission} FCFA",
                "step3": f"Client paie: {amount_to_pay} FCFA",
                "step4": f"CinetPay déduit ~{cinetpay_rate*100}%: -{cinetpay_commission_estimate} FCFA",
                "step5": f"TIM CASH reçoit: {amount_received_by_timcash} FCFA"
            }
        }

    except HTTPException:
        raise
    except Exception as e:
        print(f"❌ [ADMIN] Erreur calcul répartition: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"Erreur lors du calcul: {str(e)}"
        )


@router.post("/admin/commission-rates/activate-all")
async def activate_all_commissions(
    admin_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """Activer toutes les commissions existantes"""
    
    try:
        print(f"🔄 [ADMIN] Activation de toutes les commissions par {admin_user.email}")
        
        # Récupérer toutes les commissions inactives
        inactive_commissions = db.query(CommissionRate).filter(
            CommissionRate.is_active == False
        ).all()
        
        if not inactive_commissions:
            return {
                "success": True,
                "message": "Toutes les commissions sont déjà actives",
                "activated_count": 0
            }
        
        # Activer toutes les commissions inactives
        for commission in inactive_commissions:
            commission.is_active = True
            commission.updated_by = admin_user.id
            commission.updated_at = datetime.utcnow()
        
        db.commit()
        
        print(f"✅ [ADMIN] {len(inactive_commissions)} commissions activées")
        
        return {
            "success": True,
            "message": f"{len(inactive_commissions)} commissions ont été activées avec succès",
            "activated_count": len(inactive_commissions),
            "activated_commissions": [
                {
                    "id": c.id,
                    "name": c.name,
                    "category": c.category,
                    "value": c.value
                }
                for c in inactive_commissions
            ]
        }
        
    except Exception as e:
        print(f"❌ [ADMIN] Erreur activation toutes commissions: {str(e)}")
        db.rollback()
        raise HTTPException(
            status_code=500,
            detail=f"Erreur lors de l'activation des commissions: {str(e)}"
        )

