from fastapi import APIRouter, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse
from app.salary_analytics.helpers.response_helpers import AnalysisResponse
from app.salary_analytics.helpers.data_checks import check_data_loaded
from app.salary_analytics.core.state import state
from app.config import OUTPUT_PATHS
from app.utils.logger import logger
import os, time

router = APIRouter()


@router.post("/generate/reports", response_model=AnalysisResponse)
async def generate_reports(background_tasks: BackgroundTasks):
    """Generate salary earner reports."""
    start_time = time.time()
    try:
        check_data_loaded()
        logger.info("Starting report generation...")
        reports = state.pipeline.generate_salary_earner_reports()
        logger.info("Reports generated successfully")
        response = AnalysisResponse(
            message="Reports generated successfully",
            data={
                "verified_salary_earners": len(reports['final_table']),
                "likely_salary_earners": len(reports['likely_salary_earner']),
                "high_earners": reports['total_high_earners']
            }
        )
        logger.info(f"Report generation endpoint completed in {time.time() - start_time:.2f} seconds")
        return response
    except Exception as e:
        logger.error(f"Error in report generation: {str(e)}")
        logger.info(f"Report generation endpoint failed after {time.time() - start_time:.2f} seconds")
        raise HTTPException(status_code=500, detail=str(e))



@router.get("/download/{report_type}")
async def download_report(report_type: str):
    """Download generated reports."""
    start_time = time.time()
    try:
        check_data_loaded()
        logger.info(f"Attempting to download report: {report_type}")
        file_paths = {
            "high_earners": OUTPUT_PATHS["high_earner_details"],
            "likely_earners": OUTPUT_PATHS["likely_salary_earner"],
            "final_table": OUTPUT_PATHS["final_table"],
            "consistent_plot": OUTPUT_PATHS["consistent_earners_plot"],
            "inconsistent_plot": OUTPUT_PATHS["inconsistent_earners_plot"],
            "hypothesis_plot": OUTPUT_PATHS["hypothesis_overlap_plot"]
        }

        if report_type not in file_paths:
            logger.error(f"Report type not found: {report_type}")
            logger.info(f"Download endpoint failed after {time.time() - start_time:.2f} seconds")
            raise HTTPException(status_code=404, detail="Report type not found")

        file_path = file_paths[report_type]
        if not os.path.exists(file_path):
            logger.error(f"Report file not found: {file_path}")
            logger.info(f"Download endpoint failed after {time.time() - start_time:.2f} seconds")
            raise HTTPException(status_code=404, detail="Report file not found")

        logger.info(f"Successfully found report file: {file_path}")
        response = FileResponse(
            path=file_path,
            filename=os.path.basename(file_path),
            media_type="application/octet-stream"
        )
        logger.info(f"Download endpoint completed in {time.time() - start_time:.2f} seconds")
        return response
    except Exception as e:
        logger.error(f"Error downloading report: {str(e)}")
        logger.info(f"Download endpoint failed after {time.time() - start_time:.2f} seconds")
        raise HTTPException(status_code=500, detail=str(e))

