"""
Routes API pour les recharges TIM BUSINESS
Commission 10% : 4% TIM BUSINESS + 6% TIM CASH
"""

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any
from datetime import datetime

from core.database import get_db
from services.tim_business_service import TIMBusinessRechargeService
from core.websocket_manager import manager

router = APIRouter()


# ==================== Pydantic Models ====================

class RechargeRequest(BaseModel):
    """Requête de recharge"""
    beneficiary_phone: str = Field(..., description="Numéro de téléphone du bénéficiaire")
    amount: float = Field(..., gt=0, description="Montant de la recharge en FCFA")
    description: Optional[str] = Field(None, description="Description optionnelle")
    
    class Config:
        json_schema_extra = {
            "example": {
                "beneficiary_phone": "+225 07 12 34 56 78",
                "amount": 10000,
                "description": "Recharge compte client"
            }
        }


class RechargeCalculationRequest(BaseModel):
    """Requête de calcul de commission"""
    amount: float = Field(..., gt=0, description="Montant de la recharge")
    
    class Config:
        json_schema_extra = {
            "example": {
                "amount": 10000
            }
        }


# ==================== Endpoints ====================

@router.post("/calculate-commission")
async def calculate_commission(
    request: RechargeCalculationRequest,
    db: Session = Depends(get_db)
):
    """
    Calculer les commissions pour une recharge
    
    **Commission 10% répartie comme suit :**
    - 4% pour le compte TIM BUSINESS (reste sur le wallet)
    - 6% pour TIM CASH (reversé sur CinetPay)
    
    **Exemple :**
    - Montant recharge : 10 000 FCFA
    - Commission totale : 1 000 FCFA (10%)
    - Commission TIM BUSINESS : 400 FCFA (4%)
    - Commission TIM CASH : 600 FCFA (6%)
    - Total à débiter : 11 000 FCFA
    - Bénéficiaire reçoit : 10 000 FCFA
    - TIM BUSINESS reçoit : 400 FCFA en commission
    """
    service = TIMBusinessRechargeService(db)
    calculations = service.calculate_commission(request.amount)
    
    return {
        "success": True,
        "data": {
            **calculations,
            "breakdown": {
                "amount_to_beneficiary": calculations["amount"],
                "total_commission": calculations["total_commission"],
                "business_commission": {
                    "amount": calculations["business_commission"],
                    "percentage": "4%",
                    "description": "Commission créditée sur votre wallet TIM BUSINESS"
                },
                "timcash_commission": {
                    "amount": calculations["timcash_commission"],
                    "percentage": "6%",
                    "description": "Commission TIM CASH reversée sur CinetPay"
                },
                "total_to_debit": calculations["total_amount"]
            }
        }
    }


@router.post("/recharge")
async def create_recharge(
    request: RechargeRequest,
    business_user_id: str,
    db: Session = Depends(get_db)
):
    """
    Effectuer une recharge TIM BUSINESS vers TIM MINI/MAXI
    
    **Processus :**
    1. Validation du compte TIM BUSINESS et du bénéficiaire
    2. Vérification du solde (montant + commission 10%)
    3. Débit du compte TIM BUSINESS (montant + 10%)
    4. Crédit du bénéficiaire (montant sans commission)
    5. Crédit de 4% sur le wallet TIM BUSINESS
    6. Crédit de 6% sur le compte TIM CASH (CinetPay)
    
    **Exemple de transaction :**
    ```
    Recharge de 10 000 FCFA
    ├─ Débit TIM BUSINESS : -11 000 FCFA
    ├─ Crédit bénéficiaire : +10 000 FCFA
    ├─ Commission TIM BUSINESS : +400 FCFA
    └─ Commission TIM CASH : +600 FCFA (CinetPay)
    
    Solde final TIM BUSINESS : -10 600 FCFA
    (10 000 recharge + 600 commission TIM CASH)
    ```
    """
    try:
        # Récupérer le bénéficiaire par téléphone
        from models.user import User
        beneficiary = db.query(User).filter(
            User.phone == request.beneficiary_phone
        ).first()
        
        if not beneficiary:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Bénéficiaire non trouvé avec ce numéro de téléphone"
            )
        
        # Traiter la recharge
        service = TIMBusinessRechargeService(db)
        result = service.process_recharge(
            business_user_id=business_user_id,
            beneficiary_user_id=beneficiary.id,
            beneficiary_phone=request.beneficiary_phone,
            amount=request.amount,
            description=request.description,
            metadata={
                "ip_address": "0.0.0.0",  # TODO: Récupérer l'IP réelle
                "device_info": "Mobile App",
                "location": None
            }
        )
        
        if not result["success"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=result["message"]
            )
        
        # Notifier les applications mobiles de la mise à jour
        await manager.broadcast_to_mobile({
            "type": "balance_update",
            "user_id": business_user_id,
            "new_balance": result["data"]["business_new_balance"],
            "transaction_type": "tim_business_recharge",
            "timestamp": datetime.now().isoformat()
        })
        
        await manager.broadcast_to_mobile({
            "type": "balance_update",
            "user_id": beneficiary.id,
            "new_balance": result["data"]["beneficiary_new_balance"],
            "transaction_type": "recharge_received",
            "timestamp": datetime.now().isoformat()
        })
        
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Erreur lors du traitement de la recharge: {str(e)}"
        )


@router.get("/recharge-history")
async def get_recharge_history(
    business_user_id: str,
    limit: int = 50,
    offset: int = 0,
    db: Session = Depends(get_db)
):
    """
    Récupérer l'historique des recharges effectuées
    
    **Retourne :**
    - Liste des recharges avec détails des commissions
    - Montants débités et crédités
    - Statuts des transactions
    """
    service = TIMBusinessRechargeService(db)
    return service.get_recharge_history(
        user_id=business_user_id,
        user_type="business",
        limit=limit,
        offset=offset
    )


@router.get("/commission-stats")
async def get_commission_stats(
    business_user_id: str,
    db: Session = Depends(get_db)
):
    """
    Récupérer les statistiques de commission
    
    **Retourne :**
    - Total des commissions gagnées (4%)
    - Nombre de recharges effectuées
    - Commission moyenne par recharge
    - Taux de commission actuel
    """
    service = TIMBusinessRechargeService(db)
    return service.get_commission_stats(business_user_id)


@router.get("/received-recharges")
async def get_received_recharges(
    user_id: str,
    limit: int = 50,
    offset: int = 0,
    db: Session = Depends(get_db)
):
    """
    Récupérer l'historique des recharges reçues
    (Pour les comptes TIM MINI/MAXI)
    
    **Retourne :**
    - Liste des recharges reçues
    - Informations sur le rechargeur
    - Montants reçus
    """
    service = TIMBusinessRechargeService(db)
    return service.get_recharge_history(
        user_id=user_id,
        user_type="beneficiary",
        limit=limit,
        offset=offset
    )


@router.get("/commission-config")
async def get_commission_config():
    """
    Récupérer la configuration des commissions
    
    **Configuration actuelle :**
    - Commission totale : 10%
    - Commission TIM BUSINESS : 4%
    - Commission TIM CASH : 6%
    """
    return {
        "success": True,
        "data": {
            "total_commission_rate": 10.0,
            "business_commission_rate": 4.0,
            "timcash_commission_rate": 6.0,
            "breakdown": {
                "tim_business": {
                    "rate": "4%",
                    "description": "Commission créditée sur le wallet TIM BUSINESS",
                    "destination": "Wallet TIM BUSINESS"
                },
                "tim_cash": {
                    "rate": "6%",
                    "description": "Commission reversée sur CinetPay",
                    "destination": "Compte TIM CASH (CinetPay)"
                }
            },
            "example": {
                "recharge_amount": 10000,
                "total_commission": 1000,
                "business_commission": 400,
                "timcash_commission": 600,
                "total_to_debit": 11000,
                "beneficiary_receives": 10000,
                "business_net_cost": 10600
            }
        }
    }


# ==================== Admin Endpoints ====================

@router.get("/admin/timcash-account")
async def get_timcash_account(db: Session = Depends(get_db)):
    """
    [ADMIN] Récupérer les informations du compte TIM CASH
    
    **Retourne :**
    - Solde actuel
    - Total des commissions reçues (6%)
    - Total transféré à CinetPay
    - Nombre de recharges
    """
    from models.tim_business_recharge import TIMCashCompanyAccount
    
    account = db.query(TIMCashCompanyAccount).first()
    
    if not account:
        return {
            "success": True,
            "data": {
                "balance": 0.0,
                "total_commissions_received": 0.0,
                "total_transferred_to_cinetpay": 0.0,
                "total_recharges_count": 0,
                "last_recharge_at": None
            }
        }
    
    return {
        "success": True,
        "data": {
            "balance": account.balance,
            "total_commissions_received": account.total_commissions_received,
            "total_transferred_to_cinetpay": account.total_transferred_to_cinetpay,
            "total_recharges_count": account.total_recharges_count,
            "last_recharge_at": account.last_recharge_at.isoformat() if account.last_recharge_at else None,
            "pending_transfer": account.balance - account.total_transferred_to_cinetpay
        }
    }


@router.post("/admin/transfer-to-cinetpay")
async def transfer_to_cinetpay(
    amount: float,
    db: Session = Depends(get_db)
):
    """
    [ADMIN] Transférer les commissions TIM CASH vers CinetPay
    
    **Processus :**
    1. Vérifier le solde disponible
    2. Créer une transaction de transfert
    3. Mettre à jour le compte TIM CASH
    """
    from models.tim_business_recharge import TIMCashCompanyAccount, CinetPayTransfer
    import uuid
    
    try:
        account = db.query(TIMCashCompanyAccount).first()
        
        if not account or account.balance < amount:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Solde insuffisant pour le transfert"
            )
        
        # Créer le transfert
        transfer = CinetPayTransfer(
            id=str(uuid.uuid4()),
            amount=amount,
            reference=f"CINETPAY-{datetime.now().strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:8].upper()}",
            status="completed",  # TODO: Intégrer avec l'API CinetPay
            completed_at=datetime.utcnow()
        )
        
        # Mettre à jour le compte
        account.balance -= amount
        account.total_transferred_to_cinetpay += amount
        account.updated_at = datetime.utcnow()
        
        db.add(transfer)
        db.commit()
        
        return {
            "success": True,
            "message": "Transfert vers CinetPay effectué avec succès",
            "data": {
                "transfer_id": transfer.id,
                "reference": transfer.reference,
                "amount": amount,
                "new_balance": account.balance
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Erreur lors du transfert: {str(e)}"
        )
