import streamlit as st
from codet5_summarizer import CodeT5Summarizer, MODEL_OPTIONS
import textwrap
import os
import base64

st.set_page_config(page_title="Code Summarizer & Report Generator", layout="wide")

st.title("📄 Code Summarizer & Report Generator")
st.markdown("""
Upload a Python code file to get a high-level summary and a report structure with editable sections.
You can choose from various models including Mistral, CodeT5, and Gemini.
""")

# Model selection
model_label = st.selectbox("Select Model", list(MODEL_OPTIONS.keys()), index=0)
summarizer = CodeT5Summarizer(model_name=MODEL_OPTIONS[model_label])

# Upload code file
uploaded_file = st.file_uploader("Upload a .py file", type="py")
if uploaded_file:
    code = uploaded_file.read().decode("utf-8")
    st.code(code, language="python")

    st.markdown("---")
    st.subheader("🔍 Generating Summary...")

    if "Mistral" in model_label or "Gemini" in model_label:
        summary = summarizer.summarize(code)
        function_summaries = None
        class_summaries = None
    else:
        results = summarizer.summarize_code(code)
        summary = results["file_summary"]
        function_summaries = results["function_summaries"]
        class_summaries = results["class_summaries"]

    st.text_area("Summary", summary, height=200)

    if function_summaries:
        st.subheader("🧩 Function Summaries")
        for func, summ in function_summaries.items():
            st.text_area(f"Function: {func}", summ, height=100)

    if class_summaries:
        st.subheader("🏗️ Class Summaries")
        for cls, summ in class_summaries.items():
            st.text_area(f"Class: {cls}", summ, height=100)

    # Report generation section
    st.markdown("---")
    st.subheader("📘 Generate Report")

    default_sections = [
        "Abstract", "Introduction", "Literature Review", "Methodology",
        "Modules", "Software & Hardware Requirements", "Architecture & UML Diagrams",
        "References", "Conclusion"
    ]

    sections = st.multiselect("Select Sections", default_sections, default=default_sections)

    report = ""
    for section in sections:
        content = st.text_area(f"✏️ {section} Content", value=f"{section} description goes here...", height=150)
        report += f"\n## {section}\n\n{textwrap.dedent(content)}\n"

    # Export format
    st.markdown("---")
    st.subheader("📤 Export Report")
    export_format = st.radio("Select Export Format", ["Markdown", "Text", "HTML"])

    def generate_download_link(content, filename):
        b64 = base64.b64encode(content.encode()).decode()
        return f'<a href="data:file/txt;base64,{b64}" download="{filename}">📥 Download {filename}</a>'

    if st.button("Generate Export File"):
        filename = uploaded_file.name.replace(".py", "")
        if export_format == "Markdown":
            st.markdown(generate_download_link(report, f"{filename}_report.md"), unsafe_allow_html=True)
        elif export_format == "Text":
            st.markdown(generate_download_link(report, f"{filename}_report.txt"), unsafe_allow_html=True)
        else:
            html_content = f"<html><body>{report.replace('\n', '<br>')}</body></html>"
            st.markdown(generate_download_link(html_content, f"{filename}_report.html"), unsafe_allow_html=True)