import pandas as pd
import plotly.graph_objects as go
import os
from django.shortcuts import render

def prepare_chart():
    # Get the directory where the script is located
    script_dir = os.path.dirname(os.path.abspath(__file__))

    # Construct the full path to the mutation_summary.txt file
    mutation_summary_file = os.path.join(script_dir, "mutation_summary.csv")

    # Load the mutation data
    mutation_data = pd.read_csv(mutation_summary_file, sep=',')

    # Create bins for Mutation_Count
    bins = [0, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101, 111, 121, 131, float("inf")]
    labels = ["≤10", "10-20", "20-30", "30-40", "40-50", "50-60", "60-70", "70-80", 
            "80-90", "90-100", "100-110", "110-120", "120-130", ">130"]

    # Assign Mutation_Count values to bins
    mutation_data["Range"] = pd.cut(mutation_data["Mutation_Count"], bins=bins, labels=labels, right=False)

    # Count occurrences in each bin
    bin_counts = mutation_data["Range"].value_counts(sort=False).reset_index()
    bin_counts.columns = ["Mutation Range", "Count"]

    # Create the bar chart
    fig = go.Figure(
        data=[
            go.Bar(
                x=bin_counts["Mutation Range"],
                y=bin_counts["Count"],
                marker_color="skyblue",
                text=bin_counts["Count"],
                textposition="outside"
            )
        ]
    )

    # Customize the layout
    fig.update_layout(
        title="Mutation Count Distribution",
        xaxis=dict(title="Mutation Range", tickangle=45),
        yaxis=dict(title="Count"),
        template="plotly_white",
        width=800,
        height=500
    )

    # Save the plot as an HTML file in the same directory as the script
    html_file = os.path.join(script_dir, "../template/mutation_count_chart.html")
    fig.write_html(html_file)
    print(f"Interactive bar chart saved as '{html_file}'.")

    # Display the chart
    fig.show()

def mutationhtml(request, *args, **kwargs):
    prepare_chart()
    return render(request, 'mutation_count_chart.html')