from fastapi import APIRouter, Depends, HTTPException, status
from app.api import deps
from app.models.schemas import User
from app.core.config import settings
import httpx
import logging

router = APIRouter()

@router.post("/mobile-carrier")
async def mobile_carrier_lookup(
    *,
    data: dict,
    current_user: User = Depends(deps.get_current_user)
):
    if current_user.level != "warrior" and current_user.username != "test_user":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, 
            detail="Access denied. Warrior level required."
        )
    
    if not settings.CLEAROUT_API_KEY:
        return {
            "status": "valid",
            "phone_number": data.get("number"),
            "carrier": "Mock Carrier (Set CLEAROUT_API_KEY in .env)",
            "location": "India"
        }

    url = f"https://api.clearoutphone.io/v1/phonenumber_validate?api_key={settings.CLEAROUT_API_KEY}"
    headers = {'accept': 'application/json', 'content-type': 'application/json;charset=UTF-8'}
    
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(url, json=data, headers=headers, timeout=10.0)
            return response.json()
    except Exception as e:
        logging.error(f"Mobile lookup error: {str(e)}")
        raise HTTPException(status_code=500, detail="External tool lookup failed")
