from fastapi import APIRouter, Depends, HTTPException, Body, File, UploadFile
from sqlalchemy.orm import Session
from database import SessionLocal
# from models.models_profile_tables import UserProfile
from models.models_profile_tables import StudentProfile as UserProfile  # Use the correct class name
from models.user_model import User
import os
import shutil

UPLOAD_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "uploads")
os.makedirs(UPLOAD_DIR, exist_ok=True)

router = APIRouter()

USER_QUESTION_MAP = {
    "first_name": [
        "What's your first name?",
        "Please enter your given name.",
        "May I know your first name?",
        "Could you tell me your given name?",
        "Kindly share your first name."
    ],
    "last_name": [
        "What's your last name?",
        "Please provide your surname.",
        "Can you share your family name?",
        "Kindly enter your last name.",
        "What’s your legal last name?"
    ],
    "email": [
        "What's your email address?",
        "Please provide your email.",
        "Can I have your email ID?",
        "Enter your email for contact purposes.",
        "Kindly share your email address."
    ],
    "bio": [
        "Tell us about yourself.",
        "Write a short bio.",
        "Share a brief introduction.",
        "What should we know about you?",
        "Describe yourself in a few lines."
    ],
    "location": [
        "Where are you located?",
        "Which city do you live in?",
        "What’s your current location?",
        "Can you tell us your city and state?",
        "Share your primary location."
    ]
}

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@router.get("/user/chat-questions")
def get_user_chat_questions():
    return [
        {"field": field, "questions": questions}
        for field, questions in USER_QUESTION_MAP.items()
    ]

@router.post("/user/chat-update-profile/{email}")
def chat_update_user_profile(
    email: str,
    field: str = Body(...),
    answer: str = Body(...),
    db: Session = Depends(get_db)
):
    if field not in USER_QUESTION_MAP:
        raise HTTPException(status_code=400, detail="Invalid field name")

    user = db.query(User).filter(User.email == email, User.role == "user").first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    profile = db.query(UserProfile).filter(UserProfile.user_id == user.id).first()

    if not profile:
        if field in ["first_name", "last_name", "email"]:
            profile_data = {"user_id": user.id, field: answer}
            profile = UserProfile(**profile_data)
            db.add(profile)
        else:
            raise HTTPException(
                status_code=400,
                detail="Profile must start with first_name, last_name, or email."
            )
    else:
        setattr(profile, field, answer)

    required_fields = [
        profile.first_name,
        profile.last_name,
        profile.email,
        profile.bio,
        profile.location
    ]

    if all(required_fields):
        user.profile_completed = True

    db.commit()

    return {
        "message": f"Answer for '{field}' saved.",
        "profile_completed": user.profile_completed
    }

@router.get("/user/profile/{email}")
def get_user_profile(email: str, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == email, User.role == "user").first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    profile = db.query(UserProfile).filter(UserProfile.user_id == user.id).first()
    if not profile:
        raise HTTPException(status_code=404, detail="User profile not found")

    return {
        "user_id": profile.user_id,
        "first_name": profile.first_name,
        "last_name": profile.last_name,
        "email": profile.email,
        "bio": profile.bio,
        "location": profile.location
    }

@router.post("/user/upload-avatar/{email}")
async def upload_avatar(
    email: str,
    avatar: UploadFile = File(...),
    db: Session = Depends(get_db)
):
    user = db.query(User).filter(User.email == email, User.role == "user").first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    profile = db.query(UserProfile).filter(UserProfile.user_id == user.id).first()
    if not profile:
        raise HTTPException(status_code=404, detail="Profile not found")

    if not avatar.content_type.startswith('image/'):
        raise HTTPException(status_code=400, detail="File must be an image")

    file_extension = os.path.splitext(avatar.filename)[1]
    filename = f"avatar_{user.id}{file_extension}"
    file_path = os.path.join(UPLOAD_DIR, filename)

    if profile.avatar and os.path.exists(profile.avatar):
        os.remove(profile.avatar)

    try:
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(avatar.file, buffer)

        profile.avatar = f"uploads/{filename}"
        db.commit()

        return {
            "message": "Avatar uploaded successfully",
            "file_url": f"http://127.0.0.1:8000/uploads/{filename}"
        }
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/user/delete-avatar/{email}")
async def delete_avatar(
    email: str,
    db: Session = Depends(get_db)
):
    user = db.query(User).filter(User.email == email, User.role == "user").first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    profile = db.query(UserProfile).filter(UserProfile.user_id == user.id).first()
    if not profile or not profile.avatar:
        raise HTTPException(status_code=404, detail="No avatar found")

    try:
        if os.path.exists(profile.avatar):
            os.remove(profile.avatar)

        profile.avatar = None
        db.commit()

        return {"message": "Avatar deleted successfully"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))