"""
Superadmin routes: user management, stats, oversight.
"""

from pydantic import BaseModel
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import func

from backend.database import get_db
from backend.models import User, Chat, Message, KnowledgeBase
from backend.auth import require_superadmin, hash_password

router = APIRouter()


class UpdateUserBody(BaseModel):
    email: Optional[str] = None
    role: Optional[str] = None
    is_active: Optional[bool] = None
    quota_tokens_monthly: Optional[int] = None
    password: Optional[str] = None


class CreateUserBody(BaseModel):
    username: str
    email: str
    password: str
    role: str = "user"
    quota_tokens_monthly: int = 2_000_000


@router.get("/stats")
def get_stats(admin: User = Depends(require_superadmin), db: Session = Depends(get_db)):
    return {
        "total_users": db.query(User).count(),
        "active_users": db.query(User).filter(User.is_active == True).count(),
        "total_chats": db.query(Chat).count(),
        "total_messages": db.query(Message).count(),
        "total_tokens_used": db.query(func.sum(User.tokens_used_this_month)).scalar() or 0,
        "total_knowledge_bases": db.query(KnowledgeBase).count(),
    }


@router.get("/users")
def list_users(admin: User = Depends(require_superadmin), db: Session = Depends(get_db)):
    users = db.query(User).order_by(User.created_at.desc()).all()
    result = []
    for u in users:
        chat_count = db.query(Chat).filter(Chat.user_id == u.id).count()
        result.append({
            "id": u.id,
            "username": u.username,
            "email": u.email,
            "role": u.role,
            "is_active": u.is_active,
            "quota_tokens_monthly": u.quota_tokens_monthly,
            "tokens_used_this_month": u.tokens_used_this_month,
            "chat_count": chat_count,
            "created_at": str(u.created_at),
        })
    return result


@router.post("/users")
def create_user(body: CreateUserBody, admin: User = Depends(require_superadmin), db: Session = Depends(get_db)):
    if db.query(User).filter(
        (User.username == body.username) | (User.email == body.email)
    ).first():
        raise HTTPException(409, "Username or email taken")
    user = User(
        username=body.username,
        email=body.email,
        password_hash=hash_password(body.password),
        role=body.role,
        quota_tokens_monthly=body.quota_tokens_monthly,
    )
    db.add(user)
    db.commit()
    return {"id": user.id, "username": user.username}


@router.put("/users/{user_id}")
def update_user(user_id: str, body: UpdateUserBody, admin: User = Depends(require_superadmin), db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(404)
    if body.email is not None:
        user.email = body.email
    if body.role is not None:
        user.role = body.role
    if body.is_active is not None:
        user.is_active = body.is_active
    if body.quota_tokens_monthly is not None:
        user.quota_tokens_monthly = body.quota_tokens_monthly
    if body.password:
        user.password_hash = hash_password(body.password)
    db.commit()
    return {"ok": True}


@router.delete("/users/{user_id}")
def delete_user(user_id: str, admin: User = Depends(require_superadmin), db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(404)
    if user.role == "superadmin":
        raise HTTPException(400, "Cannot delete superadmin")
    db.delete(user)
    db.commit()
    return {"ok": True}


@router.get("/chats")
def list_all_chats(admin: User = Depends(require_superadmin), db: Session = Depends(get_db)):
    chats = db.query(Chat).order_by(Chat.updated_at.desc()).limit(200).all()
    result = []
    for c in chats:
        user = db.query(User).filter(User.id == c.user_id).first()
        msg_count = db.query(Message).filter(Message.chat_id == c.id).count()
        result.append({
            "id": c.id,
            "title": c.title,
            "username": user.username if user else "?",
            "message_count": msg_count,
            "updated_at": str(c.updated_at),
        })
    return result