from fastapi import APIRouter, HTTPException
from .service import StudentExcelService
from .schema import StudentDataInput, ExcelUpdateResponse
from typing import Dict, Any

stu_router = APIRouter()
service = StudentExcelService()

@stu_router.post("/save-student-data", response_model=ExcelUpdateResponse)
async def save_student_data(data: StudentDataInput):
    """Save student UI form data to database"""
    try:
        result = service.save_student_data(data.student_id, data.form_data)
        return ExcelUpdateResponse(
            status="success",
            message=f"Saved {len(data.form_data)} form fields to database",
            records_saved=len(data.form_data)
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@stu_router.post("/update-excel", response_model=ExcelUpdateResponse)
async def update_excel_file(data: Dict[str, str]):
    """Update existing Excel file with database data"""
    try:
        student_id = data.get("student_id")
        if not student_id:
            raise HTTPException(status_code=400, detail="student_id required")
        
        result = service.update_excel_with_database_data(student_id)
        return ExcelUpdateResponse(
            status="success",
            message=f"Excel updated: {result.get('excel_path', 'File updated')}",
            records_saved=result["updated_cells"]
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))