from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select, func
from typing import Optional, List

from app.core.deps import DB, CurrentUser, require_teacher
from app.models.user import User, TeacherProfile
from app.models.school import School, SchoolTeacherAssignment, SchoolStudentEnrollment
from app.models.academic import TeacherQuestionSubmission, Subject, Grade
from app.models.progress import PlayerProgress, AcademicProgressSummary
from app.schemas.academic import TeacherSubmissionCreateRequest

router = APIRouter(
    prefix="/teachers", tags=["Teachers"], dependencies=[Depends(require_teacher)]
)


@router.get("/profile", summary="Get Teacher Profile")
async def get_teacher_profile(current_user: CurrentUser, db: DB):
    result = await db.execute(
        select(TeacherProfile).where(TeacherProfile.user_id == current_user.id)
    )
    profile = result.scalar_one_or_none()
    return {
        "user": current_user,
        "profile": profile,
        "teacher_code": profile.teacher_code if profile else None,
    }


@router.get("/assignments", summary="Get My School Assignments")
async def get_assignments(current_user: CurrentUser, db: DB):
    """Get all school assignments for this teacher."""
    result = await db.execute(
        select(SchoolTeacherAssignment, School)
        .join(School, SchoolTeacherAssignment.school_id == School.id)
        .where(
            SchoolTeacherAssignment.teacher_user_id == current_user.id,
            SchoolTeacherAssignment.is_active == True,
        )
    )
    rows = result.all()
    return [
        {
            "school_name": row.School.school_name,
            "school_code": row.School.school_code,
            "subject_ids": row.SchoolTeacherAssignment.subject_ids,
            "grade_ids": row.SchoolTeacherAssignment.grade_ids,
            "assignment_date": row.SchoolTeacherAssignment.assignment_date,
        }
        for row in rows
    ]


@router.get("/students", summary="Get Students in My Classes")
async def get_my_students(
    current_user: CurrentUser,
    db: DB,
    school_id: Optional[int] = None,
):
    """Get all students enrolled in the schools where this teacher is assigned."""
    # Get teacher's school assignments
    assignments = await db.execute(
        select(SchoolTeacherAssignment.school_id).where(
            SchoolTeacherAssignment.teacher_user_id == current_user.id,
            SchoolTeacherAssignment.is_active == True,
        )
    )
    school_ids = [row[0] for row in assignments.all()]
    if school_id and school_id not in school_ids:
        raise HTTPException(status_code=403, detail="Not assigned to that school")
    if school_id:
        school_ids = [school_id]

    if not school_ids:
        return []

    result = await db.execute(
        select(User, SchoolStudentEnrollment)
        .join(SchoolStudentEnrollment, User.id == SchoolStudentEnrollment.student_user_id)
        .where(
            SchoolStudentEnrollment.school_id.in_(school_ids),
            SchoolStudentEnrollment.is_active == True,
        )
    )
    rows = result.all()
    return [
        {
            "stem_id": row.User.stem_id,
            "full_name": row.User.full_name,
            "school_id": row.SchoolStudentEnrollment.school_id,
            "enrollment_date": row.SchoolStudentEnrollment.enrollment_date,
        }
        for row in rows
    ]


@router.get("/students/{student_stem_id}/progress", summary="View Student Progress")
async def view_student_progress(student_stem_id: str, current_user: CurrentUser, db: DB):
    """View a student's academic progress (must be in same school)."""
    student = await db.execute(select(User).where(User.stem_id == student_stem_id))
    student_user = student.scalar_one_or_none()
    if not student_user:
        raise HTTPException(status_code=404, detail="Student not found")

    # Verify teacher has access to this student
    assignments = await db.execute(
        select(SchoolTeacherAssignment.school_id).where(
            SchoolTeacherAssignment.teacher_user_id == current_user.id,
            SchoolTeacherAssignment.is_active == True,
        )
    )
    school_ids = [row[0] for row in assignments.all()]

    enrollment = await db.execute(
        select(SchoolStudentEnrollment).where(
            SchoolStudentEnrollment.student_user_id == student_user.id,
            SchoolStudentEnrollment.school_id.in_(school_ids),
            SchoolStudentEnrollment.is_active == True,
        )
    )
    if not enrollment.scalar_one_or_none():
        raise HTTPException(status_code=403, detail="Student not in your school")

    progress = await db.execute(
        select(AcademicProgressSummary).where(
            AcademicProgressSummary.student_user_id == student_user.id
        )
    )

    return {
        "student": {"stem_id": student_user.stem_id, "full_name": student_user.full_name},
        "progress": progress.scalars().all(),
    }


@router.post("/submit-question", summary="Submit a Question for Review", status_code=201)
async def submit_question(data: TeacherSubmissionCreateRequest, current_user: CurrentUser, db: DB):
    """
    Submit a new question for admin review.
    Approved questions are added to the question bank.
    """
    profile = await db.execute(
        select(TeacherProfile).where(TeacherProfile.user_id == current_user.id)
    )
    teacher_profile = profile.scalar_one_or_none()
    if not teacher_profile:
        raise HTTPException(status_code=400, detail="Teacher profile not found")

    submission = TeacherQuestionSubmission(
        teacher_user_id=current_user.id,
        topic_level_id=data.topic_level_id,
        question_text=data.question_text,
        question_type=data.question_type,
        difficulty=data.difficulty,
        hint_text=data.hint_text,
        explanation=data.explanation,
        answers_json=data.answers_json,
    )
    db.add(submission)
    await db.commit()
    await db.refresh(submission)
    return {"message": "Question submitted for review", "submission_id": submission.id}


@router.get("/my-submissions", summary="Get My Question Submissions")
async def get_my_submissions(current_user: CurrentUser, db: DB, status: Optional[str] = None):
    query = select(TeacherQuestionSubmission).where(
        TeacherQuestionSubmission.teacher_user_id == current_user.id
    )
    if status:
        query = query.where(TeacherQuestionSubmission.status == status)
    result = await db.execute(query.order_by(TeacherQuestionSubmission.created_at.desc()))
    return result.scalars().all()


@router.get("/dashboard", summary="Teacher Dashboard Stats")
async def get_dashboard(current_user: CurrentUser, db: DB):
    """Quick stats for the teacher dashboard."""
    submissions_pending = (await db.execute(
        select(func.count(TeacherQuestionSubmission.id)).where(
            TeacherQuestionSubmission.teacher_user_id == current_user.id,
            TeacherQuestionSubmission.status == "pending",
        )
    )).scalar()
    submissions_approved = (await db.execute(
        select(func.count(TeacherQuestionSubmission.id)).where(
            TeacherQuestionSubmission.teacher_user_id == current_user.id,
            TeacherQuestionSubmission.status == "approved",
        )
    )).scalar()
    schools_count = (await db.execute(
        select(func.count(SchoolTeacherAssignment.id)).where(
            SchoolTeacherAssignment.teacher_user_id == current_user.id,
            SchoolTeacherAssignment.is_active == True,
        )
    )).scalar()

    return {
        "submissions_pending": submissions_pending,
        "submissions_approved": submissions_approved,
        "schools_assigned_to": schools_count,
    }
