import http.client
import urllib.parse
import json
import os

CINETPAY_API_KEY = "27910410466fda66bbc6a87.93656172"
PASSWORD = "Balloloumawa"

# ❗ IMPORTANT : ON NE MET JAMAIS L'URL COMPLÈTE DANS HTTPSConnection
CINETPAY_HOST = "client.cinetpay.com"


class CinetPayServiceTransfert:

    # -----------------------------------------------------
    # 🔑 LOGIN → Générer un token CinetPay
    # -----------------------------------------------------
    def login(self):
        conn = http.client.HTTPSConnection(CINETPAY_HOST)

        payload = urllib.parse.urlencode({
            "apikey": CINETPAY_API_KEY,
            "password": PASSWORD
        })

        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }

        # ✔ L’URL correcte : /v1/auth/login
        conn.request("POST", "/v1/auth/login", payload, headers)

        res = conn.getresponse()
        data = res.read().decode()

        print("LOGIN RESPONSE:", data)

        try:
            json_data = json.loads(data)
        except:
            raise Exception("Erreur : réponse non JSON de CinetPay : " + data)

        if json_data.get("code") != 0:
            raise Exception(f"Login error: {json_data.get('message')}")

        return json_data["data"]["token"]


    # -----------------------------------------------------
    # ENVOI TRANSFERT D'ARGENT
    # -----------------------------------------------------
    async def send_transfer(self, transfer_data: dict, transaction_id: str):
        token = self.login()  # Token valide

        conn = http.client.HTTPSConnection(CINETPAY_HOST)

        # CinetPay exige du x-www-form-urlencoded
        data = urllib.parse.urlencode(transfer_data)
        print(data)

        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }

        endpoint = f"/v1/transfer/money/send/contact?token={token}&transaction_id={transaction_id}"

        conn.request("POST", endpoint, data, headers)

        res = conn.getresponse()
        data = res.read().decode()

        print("SEND TRANSFER RESPONSE:", data)

        try:
            return json.loads(data)
        except:
            return {"error": "Invalid JSON", "raw": data}


    # -----------------------------------------------------
    # CHECK TRANSFERT D’ARGENT
    # -----------------------------------------------------
    async def check_transaction(self, transaction_id: str):
        token = self.login()

        conn = http.client.HTTPSConnection(CINETPAY_HOST)

        endpoint = f"/v1/transfer/check/money?token={token}&client_transaction_id={transaction_id}"

        conn.request("GET", endpoint)

        res = conn.getresponse()
        data = res.read().decode()

        print("🔎 CHECK TRANSFER RESPONSE:", data)

        try:
            return json.loads(data)
        except:
            return {"error": "Invalid JSON", "raw": data}


# -----------------------------------------------------
# INSTANCE À UTILISER PARTOUT
# -----------------------------------------------------
cinetpay_service_transfert = CinetPayServiceTransfert()
