import re

with open('backgroundtask/report_generate.py', 'r') as f:
    content = f.read()

# Replace the signature
content = content.replace(
    "def create_new_report(project_id: UUID, requester_email: str, job_id:UUID, db: Session):",
    "def generate_project_report_pdf(project_id: UUID, db: Session):"
)

# Remove the job_id logic near the top of the function
job_logic = """    if not job_id:
        return
    
    get_job_details=db.query(JobService).filter(JobService.job_id==job_id).first()

    get_job_details.status=JobStatus.IN_PROGRESS
    
    db.commit()
    db.refresh(get_job_details)"""

content = content.replace(job_logic, "")

# Replace the end part (from "    # Generate PDF to a temporary file" downwards) with "    return pdf"
end_pattern = r"    # Generate PDF to a temporary file.*"
content = re.sub(end_pattern, "    return pdf\n", content, flags=re.DOTALL)

# Add the new create_new_report function
new_function = """

def create_new_report(project_id: UUID, requester_email: str, job_id: UUID, db: Session):
    try:
        get_job_details = db.query(JobService).filter(JobService.id == job_id).first()
        if not get_job_details:
            return
            
        get_job_details.status = JobStatus.IN_PROGRESS
        db.commit()
        db.refresh(get_job_details)

        pdf = generate_project_report_pdf(project_id, db)
        if not pdf:
            raise Exception("Failed to generate PDF object")
            
        project = db.query(Project).filter(Project.id == project_id).first()
        project_name = project.name if project else "Project"

        with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_pdf:
            pdf_path = tmp_pdf.name
            
        pdf.output(pdf_path)
        
        get_job_details.status = JobStatus.COMPLETED
        get_job_details.message = "Report created successfully!"
        db.commit()
        db.refresh(get_job_details)

        asyncio.run(send_report_email(requester_email, project_name, pdf_path))
    except Exception as e:
        if 'get_job_details' in locals() and get_job_details:
            get_job_details.status = JobStatus.REJECTED
            get_job_details.error_message = str(e)
            db.commit()
    finally:
        if 'pdf_path' in locals() and os.path.exists(pdf_path):
            os.remove(pdf_path)
"""

content += new_function

with open('backgroundtask/report_generate.py', 'w') as f:
    f.write(content)

