from twilio.rest import Client
import os
import httpx
from fastapi import HTTPException
from typing import List, Optional

twilio_client = Client(os.getenv("TWILIO_ACCOUNT_SID"), os.getenv("TWILIO_AUTH_TOKEN"))


async def send_sms(to_number: str, message: str, from_number: str):
    try:
        twilio_client.messages.create(body=message, from_=from_number, to=to_number)
    except Exception as e:
        raise Exception(f"Failed to send SMS: {str(e)}")


async def fetch_twilio_numbers(
    country: str,
    number_type: str,
    contains: Optional[str] = None,
    page: Optional[int] = None,
    state: Optional[str] = None,
):
    sid = os.getenv("TWILIO_ACCOUNT_SID")
    token = os.getenv("TWILIO_AUTH_TOKEN")

    if not sid or not token:
        raise HTTPException(
            status_code=500, detail="Twilio credentials not configured."
        )

    params = {
        "VoiceEnabled": "true",
        "ExcludeAllAddressRequired": "true",
        "PageSize": "20",
    }

    if contains:
        params["Contains"] = contains
    if page is not None:
        params["Page"] = str(page)
    if state and number_type != "tollfree":
        params["InRegion"] = state

    url = (
        f"https://api.twilio.com/2010-04-01/Accounts/{sid}/AvailablePhoneNumbers/{country}/"
        + ("TollFree" if number_type == "tollfree" else "Local")
        + ".json"
    )

    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(url, params=params, auth=(sid, token))

        if response.status_code != 200:
            raise HTTPException(
                status_code=response.status_code,
                detail="Failed to fetch numbers from Twilio.",
            )

        data = response.json()

        if "available_phone_numbers" not in data:
            raise HTTPException(
                status_code=404, detail="No available phone numbers found."
            )

        final_numbers = [
            {
                "friendly_name": item.get("friendly_name"),
                "phone_number": item["phone_number"],
                "locality": item.get("locality"),
                "postal_code": item.get("postal_code"),
                "state": item.get("region"),
            }
            for item in data["available_phone_numbers"]
        ]

        # Placeholder for orphan numbers (you can fetch from DB here)
        offer_numbers = []

        return {
            "OfferNumbers": offer_numbers,
            "FinalNumbersList": final_numbers,
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
