import io, smtplib, os, csv, pandas as pd
from scripts.core.handler.minmax import add_summary
from fastapi import FastAPI, File, UploadFile
from email.mime.application import MIMEApplication
from scripts.constants import APIEndpoints
from email.mime.multipart import MIMEMultipart

print(os.getcwd())

from fastapi import APIRouter

app = FastAPI()
router = APIRouter(prefix=APIEndpoints.report_base)


@router.post("/uploadfile/")
async def upload_csv_file(file: UploadFile = File(r'C:\Users\vidya.m\Desktop\dataset.csv')):
    contents = await file.read()
    decoded_content = contents.decode('utf-8')
    csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')
    rows = list(csv_reader)
    for row in rows:
        print(row)
    return {"filename": file.filename}


@router.post("/daily_report/")
async def send_daily_report(date: str, sender_email: str, sender_password: str, receiver_email: str):
    # Read entire CSV file into a DataFrame
    df = pd.read_csv(r'C:\Users\vidya.m\Desktop\dataset.csv')
    # Split Date-Time column into separate columns for Date and Time
    df[['Date', 'Time']] = df['Formatted Date'].str.split(' ', n=1, expand=True)
    # Filter rows based on desired date
    filtered_df = df[df['Date'] == date]
    # drop the time column and add summary stats
    filtered_df = add_summary(filtered_df)
    # Convert filtered DataFrame to Excel file buffer
    excel_buffer = io.BytesIO()
    with pd.ExcelWriter(excel_buffer) as writer:
        filtered_df.to_excel(writer, index=False)
    excel_buffer.seek(0)
    # Create email message
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = "Daily weather report"
    # Read the daily report from Excel buffer
    report_content = excel_buffer.read()
    # Create a MIMEApplication object with the report content
    report = MIMEApplication(report_content, _subtype='xlsx')
    report.add_header('content-disposition', 'attachment', filename='daily_report.xlsx')
    # Add the report to the message
    msg.attach(report)
    # Send the message using SMTP
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.login(sender_email, sender_password)
        smtp.send_message(msg)
    # Return a success message
    return {"message": "Daily weather report sent successfully!"}
@router.post("/weekly_report/")
async def send_weekly_report(start_date: str, end_date: str, sender_email: str, sender_password: str,
                             receiver_email: str):
    # Read entire CSV file into a DataFrame
    df = pd.read_csv(r'C:\Users\vidya.m\Desktop\dataset.csv')
    # Split Date-Time column into separate columns for Date and Time
    df[['Date', 'Time']] = df['Formatted Date'].str.split(' ', n=1, expand=True)
    # Convert date columns to datetime objects
    df['Date'] = pd.to_datetime(df['Date'])
    # Filter rows based on desired date range
    filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]
    # drop the time column and add summary stats
    filtered_df = add_summary(filtered_df)
    # Convert filtered DataFrame to Excel file buffer
    excel_buffer = io.BytesIO()
    with pd.ExcelWriter(excel_buffer) as writer:
        filtered_df.to_excel(writer, index=False)
    excel_buffer.seek(0)
    # Create email message
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = "Weekly weather report"
    # Read the weekly report from Excel buffer
    report_content = excel_buffer.read()
    # Create a MIMEApplication object with the report content
    report = MIMEApplication(report_content, _subtype='xlsx')
    report.add_header('content-disposition', 'attachment', filename='weekly_report.xlsx')
    # Add the report to the message
    msg.attach(report)
    # Send the message using SMTP
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.login(sender_email, sender_password)
        smtp.send_message(msg)
    # Return a success message
    return {"message": "Weekly weather report sent successfully!"}


@router.post("/monthly_report/")
async def send_monthly_report(year: int, month: int, sender_email: str, sender_password: str, receiver_email: str):
    # read the CSV file into a pandas DataFrame
    df = pd.read_csv(r'C:\Users\vidya.m\Desktop\dataset.csv')
    # split the date and time into separate columns
    df[["date", "time"]] = df["Formatted Date"].str.split(" ", n=1, expand=True)
    # convert the date column to a datetime object
    df["date"] = pd.to_datetime(df["date"])
    # filter the DataFrame to select only the rows within the specified month and year
    filtered_df = df.loc[(df["date"].dt.year == year) & (df["date"].dt.month == month)]
    # drop the time column and add summary stats
    filtered_df = filtered_df.drop(columns=["time"])
    filtered_df = add_summary(filtered_df)
    # Convert filtered DataFrame to Excel file buffer
    excel_buffer = io.BytesIO()
    with pd.ExcelWriter(excel_buffer) as writer:
        filtered_df.to_excel(writer, index=False)
    excel_buffer.seek(0)
    # Create email message
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = f"Weather report for {month}/{year}"
    # Read the monthly report from Excel buffer
    report_content = excel_buffer.read()
    # Create a MIMEApplication object with the report content
    report = MIMEApplication(report_content, _subtype='xlsx')
    report.add_header('content-disposition', 'attachment', filename=f'monthly_report_{month}_{year}.xlsx')
    # Add the report to the message
    msg.attach(report)
    # Send the message using SMTP
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.login(sender_email, sender_password)
        smtp.send_message(msg)
    # Return a success message
    return {"message": "Monthly weather report sent successfully!"}























