import httpx
import json
import uuid
import hashlib
from datetime import datetime, timezone
from fastapi import HTTPException, Depends, Request
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any
import os
from enum import Enum
from cinetpay_sdk.s_d_k import Cinetpay

# Configuration CinetPay (identique à votre Flutter)
CINETPAY_API_KEY = os.getenv("CINETPAY_API_KEY", "")
CINETPAY_SITE_ID = "5880897"
CINETPAY_BASE_URL = "https://api-checkout.cinetpay.com/v2"
CINETPAY_NOTIFY_URL = "https://yourapp.com/api/cinetpay/notify"
CINETPAY_RETURN_URL = "https://yourapp.com/payment/success"

import logging

logger = logging.getLogger(__name__)

class CinetPayService:
    """Service backend CinetPay pour vos paiements TimCash"""

    def __init__(self):
        self.api_key = CINETPAY_API_KEY
        self.site_id = CINETPAY_SITE_ID
        self.base_url = CINETPAY_BASE_URL
        self.client = Cinetpay(self.api_key, self.site_id)

    # -------------------------
    # 🔹 1. Création URL paiement
    # -------------------------
    async def create_payment_url(self, transfer_data: Dict[str, Any]) -> Dict[str, Any]:
        sdk = Cinetpay(self.api_key, self.site_id)
        api_response = sdk.PaymentInitialization(transfer_data)

        print("Réponse brute CinetPay:", api_response)
        print("Envoie à CinetPay:", transfer_data)

        if not isinstance(api_response, dict):
            raise HTTPException(
                status_code=500,
                detail="Réponse CinetPay invalide (non JSON)"
            )

        if api_response.get("code") == "201":
            data = api_response.get("data", {})
            return {
                "success": True,
                "payment_url": data.get("payment_url"),
                "cinetpay_token": data.get("payment_token"),
                "message": "URL de paiement créée avec succès"
            }

        return {
            "success": False,
            "message": api_response.get("message", "Erreur inconnue CinetPay"),
        }

    # -------------------------
    # 🔹 2. Vérifier une transaction
    # -------------------------
    async def check_transaction(self, transaction_id: str) -> Dict[str, Any]:
        """
        Vérifie une transaction CinetPay via transaction_id.
        """
        try:
            print(f"📡 Vérification CinetPay TRX ID = {transaction_id}")

            response = self.client.TransactionVerfication_trx(transaction_id)

            print("Réponse brute CinetPay:", response)

            if not isinstance(response, dict):
                raise Exception("Réponse CinetPay invalide")

            code = response.get("code")
            message = response.get("message")
            data = response.get("data", {})

            return {
                "success": code == "00",
                "status_code": code,
                "status": self.map_status(code),
                "message": message,
                "transaction": data
            }

        except Exception as e:
            print("Erreur lors de la vérification:", str(e))
            return {
                "success": False,
                "status": "error",
                "message": str(e)
            }

    # -------------------------
    # 🔹 Mapping du statut CinetPay
    # -------------------------
    def map_status(self, code: str) -> str:
        return {
            "00": "ACCEPTED",
            "600": "PENDING",
            "602": "REFUSED",
        }.get(code, "UNKNOWN")


# Instance à importer
cinetpay_service = CinetPayService()