import gradio as gr
import mysql.connector
from mysql.connector import Error
import matplotlib.pyplot as plt

def fetch_data(pr_number, status):
    try:
        connection = mysql.connector.connect(
            host='localhost',
            database='records',
            user='root',
            password='Nikki@1234'  # Use a secure method to store and use passwords
        )

        query = "SELECT * FROM PR_Details WHERE TRUE"
        params = []

        if pr_number:
            query += " AND PR_Number = %s"
            params.append(pr_number)
        if status:
            query += " AND Current_Status = %s"
            params.append(status)

        cursor = connection.cursor(dictionary=True)
        cursor.execute(query, params)
        records = cursor.fetchall()

        details_html = "<div class='pr_record'><table>"
        if records:
            for record in records:
                for column, value in record.items():
                    details_html += f"<tr><td><strong>{column}:</strong></td><td>{value}</td></tr>"
        else:
            details_html = "No matching records found."
        details_html += "</table></div><br>"

    except Error as e:
        print(f"Database Error: {e}")
        details_html = "Failed to fetch data due to a database error."
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

    return details_html

def plot_pie_chart():
    try:
        connection = mysql.connector.connect(
            host='localhost',
            database='records',
            user='root',
            password='Nikki@1234'  # Placeholder for your password
        )

        cursor = connection.cursor()
        cursor.execute("SELECT Current_Status, COUNT(Current_Status) FROM PR_Details GROUP BY Current_Status")
        result = cursor.fetchall()

        labels = [i[0] for i in result]
        sizes = [i[1] for i in result]

        plt.figure(figsize=(8, 6))
        plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
        plt.axis('equal')
        pie_chart = plt.gcf()
        plt.close()  # Close the plot to prevent it from displaying in the background
        return pie_chart
    except Error as e:
        print(f"Database Error: {e}")
        return plt.figure()
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()

def fetch_details(pr_number, status):
    return fetch_data(pr_number, status)

def live_update():
    return plot_pie_chart()

with gr.Blocks() as app:
    with gr.Tabs():
        with gr.Tab("PR Details"):
            pr_number_input = gr.Textbox(label="PR Number", placeholder="Enter PR Number...")
            status_input = gr.Radio(choices=['Submitted', 'Ordered', 'Composing'], label="Status", value='Submitted')  # Default value set
            details_output = gr.HTML(label="Details")

            details_btn = gr.Button("Fetch PR Details")
            details_btn.click(
                fetch_details,  # fetch_details function will be executed when the button is clicked
                inputs=[pr_number_input, status_input],
                outputs=details_output
            )

        with gr.Tab("Live Pie Chart"):
            pie_chart_output = gr.Plot(label="Status Pie Chart")

            gr.update(fn=live_update, output=pie_chart_output, interval=5)

app.launch(share=True)  # Run the Gradio app


This is not fetching any PR details and please provide clear and submit button