from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from database import get_db
import models, schemas
from core.security import verify_password, get_password_hash, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES
from core.deps import get_current_active_user

router = APIRouter()

@router.post("/register", response_model=schemas.UserResponse)
def register(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.username == user.username).first()
    if db_user:
        raise HTTPException(status_code=400, detail="Username already registered")
    
    db_email = db.query(models.User).filter(models.User.email == user.email).first()
    if db_email:
        raise HTTPException(status_code=400, detail="Email already registered")

    hashed_password = get_password_hash(user.password)
    db_user = models.User(username=user.username, email=user.email, hashed_password=hashed_password)
    
    # 默认第一个注册用户为管理员
    if db.query(models.User).count() == 0:
        db_user.is_admin = True

    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@router.post("/login", response_model=schemas.Token)
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = db.query(models.User).filter(models.User.username == form_data.username).first()
    if not user or not verify_password(form_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

@router.get("/me", response_model=schemas.UserResponse)
def read_users_me(current_user: models.User = Depends(get_current_active_user)):
    return current_user

@router.get("/search", response_model=list[schemas.UserResponse])
def search_users(q: str, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    """搜索用户（支持用户名和邮箱模糊搜索）"""
    if not q or len(q) < 2:
        return []
    
    users = db.query(models.User).filter(
        (models.User.username.contains(q)) | (models.User.email.contains(q))
    ).filter(models.User.id != current_user.id).limit(10).all()
    
    return users

@router.get("/friends", response_model=list[schemas.FriendResponse])
def get_friends(db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    friends = db.query(models.Friend).filter(models.Friend.user_id == current_user.id).all()
    # 填充 friend 信息
    for f in friends:
        f.friend = db.query(models.User).filter(models.User.id == f.friend_id).first()
    return friends

@router.post("/friends/{friend_username}", response_model=schemas.FriendResponse)
def add_friend(friend_username: str, alias: str = None, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    friend_user = db.query(models.User).filter(models.User.username == friend_username).first()
    if not friend_user:
        raise HTTPException(status_code=404, detail="User not found")
    
    if friend_user.id == current_user.id:
        raise HTTPException(status_code=400, detail="Cannot add yourself as a friend")

    existing_friend = db.query(models.Friend).filter(
        models.Friend.user_id == current_user.id,
        models.Friend.friend_id == friend_user.id
    ).first()

    if existing_friend:
        raise HTTPException(status_code=400, detail="Already friends")

    new_friend = models.Friend(user_id=current_user.id, friend_id=friend_user.id, alias=alias)
    db.add(new_friend)
    db.commit()
    db.refresh(new_friend)
    
    # 双向添加好友关系
    reverse_friend = models.Friend(user_id=friend_user.id, friend_id=current_user.id, alias=None)
    db.add(reverse_friend)
    db.commit()

    new_friend.friend = friend_user
    return new_friend

@router.delete("/friends/{friend_id}")
def remove_friend(friend_id: int, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    friend_rel = db.query(models.Friend).filter(
        models.Friend.user_id == current_user.id,
        models.Friend.friend_id == friend_id
    ).first()
    
    if not friend_rel:
        raise HTTPException(status_code=404, detail="Friend not found")
        
    # 删除双向关系
    reverse_rel = db.query(models.Friend).filter(
        models.Friend.user_id == friend_id,
        models.Friend.friend_id == current_user.id
    ).first()

    db.delete(friend_rel)
    if reverse_rel:
        db.delete(reverse_rel)
    db.commit()
    
    return {"message": "Friend removed successfully"}

@router.put("/friends/{friend_id}/alias", response_model=schemas.FriendResponse)
def update_friend_alias(friend_id: int, alias: str, db: Session = Depends(get_db), current_user: models.User = Depends(get_current_active_user)):
    friend_rel = db.query(models.Friend).filter(
        models.Friend.user_id == current_user.id,
        models.Friend.friend_id == friend_id
    ).first()
    
    if not friend_rel:
        raise HTTPException(status_code=404, detail="Friend not found")
        
    friend_rel.alias = alias
    db.commit()
    db.refresh(friend_rel)
    friend_rel.friend = db.query(models.User).filter(models.User.id == friend_id).first()
    
    return friend_rel
