from fastapi import HTTPException
import httpx
import asyncio

class WhatsAppManager:
    def __init__(self, app_integration, app_details):
        self.app_integration = app_integration
        self.client_id = app_integration['auth_config']['credentials']['client_id']
        self.client_secret = app_integration['auth_config']['credentials']['client_secret']
        self.phone_number_id = app_integration['configurations']['phone_number_id']
        self.token_url = 'https://graph.facebook.com/v18.0/oauth/access_token'
        self.base_url = f"https://graph.facebook.com/v18.0/{self.phone_number_id}/messages"
        self.access_token = None

    async def fetch_token(self):
        async with httpx.AsyncClient() as client:
            payload = {
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "grant_type": "client_credentials"
            }
            response = await client.post(self.token_url, data=payload)
            if response.status_code == 200:
                self.access_token = response.json().get('access_token')
            else:
                raise HTTPException(status_code=response.status_code, detail="Failed to obtain access token")

    async def get_user_details(self, request):
        if isinstance(request, dict):
            name = request.get("name")
            mobile = request.get("mobile")
        else:
            name = request.query_params.get("name")
            mobile = request.query_params.get("mobile")
        return name, mobile

    async def send_message(self, request):
        name, mobile = await self.get_user_details(request)
        if not self.access_token:
            #await self.fetch_token()
            self.access_token = self.client_id # Just for testing purpose.
        
        # Determine message content based on configuration
        template_name = self.app_integration['configurations'].get('template')
        message = self.app_integration['configurations'].get('message')
        message_content = {
            "type": "text",
            "text": {"body": f"Hello {name}, this is a default message from our team!"}
        }
        if template_name:
            
            message_content = {
                "type": "template",
                "template": {
                    "name": self.app_integration['configurations']['template'],
                    "language": {
                        "code": "en_US"  # Assuming default language; adjust as necessary
                    }
                }
            }
        elif message:
            message_body = self.app_integration['configurations']['message'].replace("{name}", name)
            message_content = {
                "type": "text",
                "text": {"body": message_body}
            }

        headers = {"Authorization": f"Bearer {self.access_token}", "Content-Type": "application/json"}
        payload = {
            "messaging_product": "whatsapp",
            "to": mobile,
            **message_content
        }

        async with httpx.AsyncClient() as client:
            response = await client.post(self.base_url, headers=headers, json=payload)
            if response.status_code != 200:
                raise HTTPException(status_code=response.status_code, detail="Failed to send WhatsApp message")
        
        return {"status": "success", "message": f"WhatsApp message sent to {mobile}"}

# Example usage
# app_integration = {
#     "auth_config": {
#         "credentials": {"client_id": "...", "client_secret": "..."},
#         "token_url": "https://graph.facebook.com/v18.0/oauth/access_token"
#     },
#     "configurations": {
#         "phone_number_id": "..."
#     }
# }
# whatsapp_manager = WhatsAppManager(app_integration)
# await whatsapp_manager.send_message(request)
