"""Mentorship endpoints for mentor-student relationships."""

from typing import Optional
from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from app.api.deps import get_current_admin, get_current_user, get_db, require_user_type
from app.models.mentorship import (
    Mentor, MentorMentee, MentorStatus, MentorshipSession,
    MentorshipSessionStatus, SectorType
)
from app.models.user import UserType
from app.schemas.common import SuccessResponse
from app.schemas.mentorship import (
    MentorCreate, MentorMenteeCreate, MentorMenteeResponse,
    MentorResponse, MentorshipSessionCreate, MentorshipSessionResponse
)

router = APIRouter(prefix="/mentorship", tags=["mentorship"])


@router.get("/mentors", response_model=SuccessResponse)
async def list_mentors(
    sector: Optional[SectorType] = Query(None),
    status: Optional[MentorStatus] = Query(None),
    db: Session = Depends(get_db),
    current_user_data: dict = Depends(get_current_user),
):
    """List mentors and their mentees."""
    query = db.query(Mentor)
    
    if sector:
        query = query.filter(Mentor.sector == sector)
    if status:
        query = query.filter(Mentor.status == status)
    
    mentors = query.all()
    
    # Include mentee assignments for each mentor
    result = []
    for mentor in mentors:
        assignments = db.query(MentorMentee).filter(
            MentorMentee.mentor_id == mentor.id,
            MentorMentee.is_active == True
        ).all()
        
        mentor_data = MentorResponse.model_validate(mentor).model_dump()
        mentor_data["mentees"] = [
            {
                "id": str(a.id),
                "student_id": str(a.student_id),
                "assigned_date": a.assigned_date.isoformat() if a.assigned_date else None,
            }
            for a in assignments
        ]
        result.append(mentor_data)
    
    return SuccessResponse(
        data=result,
        message="Mentors retrieved successfully",
    )


@router.post("/mentors", response_model=SuccessResponse, status_code=status.HTTP_201_CREATED)
async def create_mentor(
    mentor_data: MentorCreate,
    db: Session = Depends(get_db),
):
    """Create a mentor application (public endpoint for mentor signup)."""
    # Check if mentor with email already exists
    existing = db.query(Mentor).filter(Mentor.email == mentor_data.email).first()
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Mentor with this email already exists",
        )
    
    mentor = Mentor(**mentor_data.model_dump())
    db.add(mentor)
    db.commit()
    db.refresh(mentor)
    
    return SuccessResponse(
        data=MentorResponse.model_validate(mentor).model_dump(),
        message="Mentor application submitted successfully",
    )


@router.put("/mentors/{mentor_id}/approve", response_model=SuccessResponse)
async def approve_mentor(
    mentor_id: UUID,
    db: Session = Depends(get_db),
    current_admin = Depends(get_current_admin),
):
    """Approve a mentor (admin only)."""
    from datetime import datetime
    
    mentor = db.query(Mentor).filter(Mentor.id == mentor_id).first()
    if not mentor:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Mentor not found",
        )
    
    mentor.status = MentorStatus.APPROVED
    mentor.approved_date = datetime.utcnow()
    mentor.approved_by = current_admin.id
    
    db.commit()
    db.refresh(mentor)
    
    return SuccessResponse(
        data=MentorResponse.model_validate(mentor).model_dump(),
        message="Mentor approved successfully",
    )


@router.post("/assignments", response_model=SuccessResponse, status_code=status.HTTP_201_CREATED)
async def create_mentor_mentee_assignment(
    assignment_data: MentorMenteeCreate,
    db: Session = Depends(get_db),
    current_admin = Depends(get_current_admin),
):
    """Assign a mentor to a student (admin only)."""
    # Verify mentor and student exist
    mentor = db.query(Mentor).filter(Mentor.id == assignment_data.mentor_id).first()
    if not mentor:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Mentor not found")
    
    from app.models.user import User
    student = db.query(User).filter(User.id == assignment_data.student_id).first()
    if not student:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Student not found")
    
    # Check if assignment already exists
    existing = db.query(MentorMentee).filter(
        MentorMentee.mentor_id == assignment_data.mentor_id,
        MentorMentee.student_id == assignment_data.student_id,
        MentorMentee.is_active == True
    ).first()
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Active assignment already exists for this mentor-student pair",
        )
    
    assignment = MentorMentee(
        **assignment_data.model_dump(),
        assigned_by=current_admin.id
    )
    db.add(assignment)
    db.commit()
    db.refresh(assignment)
    
    return SuccessResponse(
        data=MentorMenteeResponse.model_validate(assignment).model_dump(),
        message="Mentor-student assignment created successfully",
    )


@router.post("/sessions", response_model=SuccessResponse, status_code=status.HTTP_201_CREATED)
async def create_mentorship_session(
    session_data: MentorshipSessionCreate,
    db: Session = Depends(get_db),
    current_user_data: dict = Depends(get_current_user),
):
    """Log a mentorship session."""
    # Verify assignment exists
    assignment = db.query(MentorMentee).filter(
        MentorMentee.id == session_data.assignment_id
    ).first()
    if not assignment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Mentor-student assignment not found",
        )
    
    # Verify user has permission (mentor, student, or admin)
    user_data = current_user_data
    if user_data.get("type") == "user":
        user = user_data.get("user")
        mentor = db.query(Mentor).filter(Mentor.id == session_data.mentor_id).first()
        if mentor and mentor.user_id and str(mentor.user_id) != str(user.id):
            if user.user_type != UserType.GLOBAL_UNDERGRADUATE or str(assignment.student_id) != str(user.id):
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="You can only log sessions for your own assignments",
                )
    
    session = MentorshipSession(**session_data.model_dump())
    db.add(session)
    db.commit()
    db.refresh(session)
    
    return SuccessResponse(
        data=MentorshipSessionResponse.model_validate(session).model_dump(),
        message="Mentorship session logged successfully",
    )


@router.get("/sessions", response_model=SuccessResponse)
async def list_mentorship_sessions(
    mentor_id: Optional[UUID] = Query(None),
    student_id: Optional[UUID] = Query(None),
    assignment_id: Optional[UUID] = Query(None),
    db: Session = Depends(get_db),
    current_user_data: dict = Depends(get_current_user),
):
    """List mentorship sessions with optional filters."""
    query = db.query(MentorshipSession)
    
    # Students can only see their own sessions
    user_data = current_user_data
    if user_data.get("type") == "user":
        user = user_data.get("user")
        if user.user_type == UserType.GLOBAL_UNDERGRADUATE:
            # Filter by student's assignments
            student_assignments = db.query(MentorMentee).filter(
                MentorMentee.student_id == user.id,
                MentorMentee.is_active == True
            ).all()
            assignment_ids = [a.id for a in student_assignments]
            query = query.filter(MentorshipSession.assignment_id.in_(assignment_ids))
    
    if mentor_id:
        query = query.filter(MentorshipSession.mentor_id == mentor_id)
    if student_id:
        # Join with assignments to filter by student
        query = query.join(MentorMentee).filter(MentorMentee.student_id == student_id)
    if assignment_id:
        query = query.filter(MentorshipSession.assignment_id == assignment_id)
    
    sessions = query.order_by(MentorshipSession.session_date.desc()).all()
    
    return SuccessResponse(
        data=[MentorshipSessionResponse.model_validate(s).model_dump() for s in sessions],
        message="Mentorship sessions retrieved successfully",
    )
