import httpx
from fastapi import APIRouter, HTTPException, Request
from loguru import logger
from pydantic import BaseModel

router = APIRouter(prefix='/auth')


class HubLoginResponse(BaseModel):
    login_url: str


@router.post('/hub-login-token', response_model=HubLoginResponse)
async def get_hub_login_token(request: Request) -> HubLoginResponse:
    """
    Request a login token from the OptraBot Hub for auto-login.
    Returns a URL that can be opened in a browser to auto-login to the Hub.
    """
    optrabot = request.app.optraBot
    
    # Get hub client and configuration
    if not hasattr(optrabot, 'thc') or not optrabot.thc:
        raise HTTPException(status_code=503, detail='Hub client not available')
    
    thc = optrabot.thc
    
    # Check if hub is connected
    if not thc.isHubConnectionOK():
        raise HTTPException(status_code=503, detail='Hub not connected')
    
    # Get API key
    api_key = thc._apiKey
    if not api_key:
        raise HTTPException(status_code=500, detail='No API key configured')
    
    # Get hub host and convert to HTTPS URL
    hub_host = thc.hub_host
    # Convert websocket URL to HTTPS
    # wss://app.optrabot.io -> https://app.optrabot.io
    # ws://localhost:8000 -> http://localhost:8000
    if hub_host.startswith('wss://'):
        hub_base_url = hub_host.replace('wss://', 'https://')
    elif hub_host.startswith('ws://'):
        hub_base_url = hub_host.replace('ws://', 'http://')
    else:
        hub_base_url = hub_host
    
    # Remove trailing /ws if present
    if hub_base_url.endswith('/ws'):
        hub_base_url = hub_base_url[:-3]
    
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f'{hub_base_url}/api/auth/create-login-token',
                headers={'X-API-Key': api_key},
                timeout=10.0
            )
            
            if response.status_code != 200:
                logger.error(f'Failed to get hub login token: {response.status_code} - {response.text}')
                raise HTTPException(
                    status_code=response.status_code, 
                    detail=f'Hub returned error: {response.text}'
                )
            
            data = response.json()
            login_token = data.get('login_token')
            
            if not login_token:
                raise HTTPException(status_code=500, detail='No login token received from hub')
            
            # Construct the auto-login URL
            login_url = f'{hub_base_url}/auto-login?token={login_token}'
            
            logger.debug(f'Generated hub login URL for auto-login')
            return HubLoginResponse(login_url=login_url)
            
    except httpx.RequestError as e:
        logger.error(f'Failed to connect to hub for login token: {e}')
        raise HTTPException(status_code=503, detail=f'Failed to connect to hub: {str(e)}')


@router.get('/tasty_callback')
async def auth_tasty_callback(code: str) -> None:
    # Handle the callback from Tastytrade authentication
    logger.debug(f'Received Tastytrade auth callback with code: {code}')
