from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
import uuid

from app import models
from app.schemas.user import UserCreate, UserClaim, UserPublic
from app.schemas.auth import Token
from app.database import get_session
from app.auth import current_active_user, get_jwt_strategy, get_refresh_jwt_strategy
from app.core.security import get_password_hash
from app.crud import user as crud_user

router = APIRouter()

@router.post("/guest", response_model=Token)
async def create_guest_user(db: AsyncSession = Depends(get_session)):
    """
    Creates a new guest user.
    """
    guest_email = f"guest_{uuid.uuid4()}@guest.mitlist.app"
    guest_password = uuid.uuid4().hex
    
    user_in = UserCreate(email=guest_email, password=guest_password)
    user = await crud_user.create_user(db, user_in=user_in, is_guest=True)
    
    # Use the same JWT strategy as regular login to generate both access and refresh tokens
    access_strategy = get_jwt_strategy()
    refresh_strategy = get_refresh_jwt_strategy()
    
    access_token = await access_strategy.write_token(user)
    refresh_token = await refresh_strategy.write_token(user)
    
    return {
        "access_token": access_token,
        "refresh_token": refresh_token,
        "token_type": "bearer"
    }

@router.post("/guest/claim", response_model=UserPublic)
async def claim_guest_account(
    claim_in: UserClaim,
    db: AsyncSession = Depends(get_session),
    current_user: models.User = Depends(current_active_user),
):
    """
    Claims a guest account, converting it to a full user.
    """
    if not current_user.is_guest:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Not a guest account.")
        
    existing_user = await crud_user.get_user_by_email(db, email=claim_in.email)
    if existing_user:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered.")
        
    hashed_password = get_password_hash(claim_in.password)
    current_user.email = claim_in.email
    current_user.hashed_password = hashed_password
    current_user.is_guest = False
    current_user.is_verified = False # Require email verification
    
    db.add(current_user)
    await db.commit()
    await db.refresh(current_user)
    
    return current_user 