import requests

class A1TopupAPI:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.base_url = "https://business.a1topup.com/recharge"
        self.response_format = "json"

    def make_recharge(self, circlecode, operatorcode, number, amount, orderid):
        url = f"{self.base_url}/api"
        # print("+++++++++++++++++++++++++++++++++++++++++++")
        # print(self.username)
        # print(self.password)
        # print(orderid)
        # print(url)

        params = {
            "username": self.username,
            "pwd": self.password,
            "circlecode": circlecode,
            "operatorcode": operatorcode,
            "number": number,
            "amount": amount,
            "orderid": orderid,
            "format": self.response_format
        }
        # print(params)
        response = requests.get(url, params=params)
        # print("HTTP Status:", response.status_code)
        # print("Raw Response:", response.text)  # 👈 ADD THIS LINE
        return self._handle_response(response)

    def check_balance(self):
        url = f"{self.base_url}/balance"
        params = {
            "username": self.username,
            "pwd": self.password,
            "format": self.response_format
        }
        response = requests.get(url, params=params)
        return self._handle_response(response)

    def check_status(self, orderid):
        url = f"{self.base_url}/status"
        params = {
            "username": self.username,
            "pwd": self.password,
            "orderid": orderid,
            "format": self.response_format
        }
        response = requests.get(url, params=params)
        return self._handle_response(response)

    # def _handle_response(self, response):
    #     try:
    #         response.raise_for_status()
    #         # 🧪 Log raw response content
    #         print("🔍 Raw API response text:", response.text.strip())

    #         return response.json()
    #     except requests.exceptions.RequestException as e:
    #         return {"error": f"Request failed: {str(e)}"}
    #     except ValueError:
    #         return {
    #             "error": "Invalid JSON response",
    #             "raw_text": response.text.strip()  # Include it for debugging
    #         }
    def _handle_response(self, response):
        try:
            response.raise_for_status()
            try:
                return response.json()  # Try parsing JSON
            except ValueError:
                # Not JSON? Return plain text for debugging
                text = response.text.strip()
                if text.startswith("Error Code"):
                    return {"error": text}
                return {"raw_text": text}
        except requests.exceptions.RequestException as e:
            return {"error": f"Request failed: {str(e)}"}


# # Example usage
# if __name__ == "__main__":
#     a1 = A1TopupAPI(username="500011", password="123")

#     # Recharge
#     response = a1.make_recharge(circlecode="2", operatorcode="A", number="980000000", amount="10", orderid="ORD123456")
#     print("Recharge:", response)

#     # Balance
#     balance = a1.check_balance()
#     print("Balance:", balance)

#     # Status
#     status = a1.check_status(orderid="ORD123456")
#     print("Status:", status)




# (venv) > python myscript.py
# 🔄 Recharge Response: {'txid': '0', 'status': 'Failure', 'opid': 'Invalid IP 49.42.149.96', 'number': '8096248999', 'amount': '19', 'orderid': 'ORD123456'}
# 💰 Balance: 500.0
# 📦 Status: {'error': 'Expecting value: line 1 column 1 (char 0)'}