from fastapi import APIRouter, HTTPException
from models.users import User
from configuration import DBSessionDep
import pandas as pd
from sqlalchemy import text
import os
from datetime import datetime

router = APIRouter(prefix="/api")

@router.get("/study-track-access-log")
def get_study_track_access_log(session: DBSessionDep):
    try:
        
        result = session.execute()
        rows = result.fetchall()
        
        data = []
        for row in rows:
            data.append(dict(row._mapping))
        
        if not data:
            return {"message": "Nenhum dado encontrado"}
        
        df = pd.DataFrame(data)
        
        excel_file = "modelo.xlsx"
        
        if os.path.exists(excel_file):
            with pd.ExcelWriter(excel_file, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
                df.to_excel(writer, sheet_name='Study Track Access Log', index=False)
        else:
            df.to_excel(excel_file, sheet_name='Study Track Access Log', index=False)
        
        update_info = pd.DataFrame({
            'Última Atualização': [datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
            'Total de Registros': [len(data)]
        })
        
        with pd.ExcelWriter(excel_file, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
            update_info.to_excel(writer, sheet_name='Info Atualização', index=False)
        
        return {
            "message": f"Dados inseridos com sucesso na planilha {excel_file}",
            "total_records": len(data),
            "excel_file": excel_file
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erro ao processar dados: {str(e)}")
    finally:
        session.close()