import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
from io import BytesIO

# Set page configuration at the very beginning
st.set_page_config(layout="wide", page_title="Benchmark Awards Form Generator")

def create_individual_document(template_path, data, matter_count, output_path, form_type):
    """Create an individual document for a row of data based on the template."""
    doc = Document(template_path)
    
    # Find the table in the document
    if len(doc.tables) < 1:
        st.error("Template document does not contain the expected table.")
        return None
    
    table = doc.tables[0]
    
    # Map Excel fields to table cells based on the form structure
    # Different mapping depending on form type
    field_mapping = {
        "Case overview": data.get("Matter/Case Overview", ""),
        "Confidential/Partially confidential (Yes or no)": data.get("Confidential / Publishable", ""),
        "Dispute resolution practice area(s)": data.get("Practice Area", "") if "Practice Area" in data else "",
        "Industry sector(s)": data.get("Industry Sector", "") if "Industry Sector" in data else "",
        "Date completed (MM/YY) / Ongoing": data.get("Current Status (ongoing / completed )", ""),
        "Value (indicate currency)": data.get("Value", ""),
        "Client(s) advised": data.get("Client Name ", ""),
        "Lead partner involved": data.get("Lead partners", ""),
        "Other lawyers involved (include position)": data.get("Team Members", ""),
        "Your firm's role": data.get("Role of S&A", ""),
        "Other law firms and their roles": data.get("Other Firms/counsels Involved", ""),
        "Governing law": "Indian Law",  # Default value
        "Description": data.get("Description  (in 500 words)", ""),
        "Please state the significance, impact and outcome of the case": data.get("The significance, impact and outcome of the case", "")
    }
    
    # Update the title based on form type
    for paragraph in doc.paragraphs:
        if "WORK HIGHLIGHT" in paragraph.text:
            if form_type == "nominee":
                paragraph.text = f"WORK HIGHLIGHT #{matter_count}"
            else:
                paragraph.text = f"WORK HIGHLIGHT #{matter_count}"
            for run in paragraph.runs:
                run.font.bold = True
    
    # Populate the table with data
    for row in table.rows:
        if len(row.cells) >= 2:  # Ensure the row has at least two cells
            cell_text = row.cells[0].text.strip()
            if cell_text in field_mapping:
                row.cells[1].text = str(field_mapping[cell_text])
    
    # Save the individual document
    doc.save(output_path)
    return output_path

def remove_empty_pages(doc_path):
    """Remove empty pages from the document"""
    doc = Document(doc_path)
    
    # Check for empty sections/pages and mark them for removal
    # This is a basic implementation - more complex logic may be needed
    # depending on how your documents are structured
    
    # Save the document back
    doc.save(doc_path)
    return doc_path

def append_docs(nominee_docs, simple_docs, output_doc):
    """Combine multiple Word documents into one, nominees first then simple."""
    combined_doc = Document()
    
    # First add all nominee documents
    for i, doc_path in enumerate(nominee_docs):
        sub_doc = Document(doc_path)
        
        # Add page break between documents (except first)
        if i > 0:
            combined_doc.add_page_break()
        
        # Copy content from sub_doc to combined_doc
        for element in sub_doc.element.body:
            combined_doc.element.body.append(element)
    
    # Then add all simple documents
    for i, doc_path in enumerate(simple_docs):
        # Always add page break before adding simple docs
        if i == 0 and nominee_docs:
            combined_doc.add_page_break()
        elif i > 0:
            combined_doc.add_page_break()
            
        sub_doc = Document(doc_path)
        
        # Copy content from sub_doc to combined_doc
        for element in sub_doc.element.body:
            combined_doc.element.body.append(element)
    
    combined_doc.save(output_doc)
    
    # Now try to remove any empty pages
    return remove_empty_pages(output_doc)

def process_benchmark_forms(excel_file, nominee_template_path, simple_template_path, 
                           selected_nominee_indices, selected_simple_indices):
    """Generate the Benchmark Awards forms based on the selected Excel rows."""
    try:
        # Read Excel file
        df = pd.read_excel(excel_file)
        nominee_docs = []
        simple_docs = []
        
        # Process nominee selections first
        nominee_count = 1
        for index in selected_nominee_indices:
            row = df.iloc[index]
            temp_output_path = f"temp_nominee_{nominee_count}.docx"
            
            individual_doc_path = create_individual_document(
                nominee_template_path, 
                row, 
                nominee_count, 
                temp_output_path,
                "nominee"
            )
            
            if individual_doc_path:
                nominee_docs.append(individual_doc_path)
                nominee_count += 1
        
        # Then process simple work highlights
        simple_count = 1
        for index in selected_simple_indices:
            row = df.iloc[index]
            temp_output_path = f"temp_simple_{simple_count}.docx"
            
            individual_doc_path = create_individual_document(
                simple_template_path, 
                row, 
                simple_count, 
                temp_output_path,
                "simple"
            )
            
            if individual_doc_path:
                simple_docs.append(individual_doc_path)
                simple_count += 1
        
        # Combine all documents
        if nominee_docs or simple_docs:
            combined_output_path = "combined_benchmark_forms.docx"
            append_docs(nominee_docs, simple_docs, combined_output_path)
            
            # Clean up temporary files
            for doc_path in nominee_docs + simple_docs:
                os.remove(doc_path)
                
            return combined_output_path
        
    except Exception as e:
        st.error(f"Error processing documents: {str(e)}")
        return None

# Streamlit application
def main():
    st.title("Benchmark Awards 2025 Form Generator")
    
    # Upload files
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.subheader("Upload Excel Data")
        excel_file = st.file_uploader("Upload Excel Data File", type=["xlsx", "xls"])
    
    with col2:
        st.subheader("Upload Nominee Template")
        nominee_template_file = st.file_uploader("Upload Nominee Template", type=["docx"])
    
    with col3:
        st.subheader("Upload Simple Template")
        simple_template_file = st.file_uploader("Upload Simple Work Highlight Template", type=["docx"])
    
    # Client selection section
    if excel_file is not None:
        # Read the Excel file
        df = pd.read_excel(excel_file)
        
        # Check if the required column exists
        if "Client Name " in df.columns:
            # Create tabs for the two different form types
            tab1, tab2 = st.tabs(["Nominee Work Highlights", "Simple Work Highlights"])
            
            with tab1:
                st.subheader("Select Nominee Work Highlights (Maximum 3)")
                st.write("Select up to 3 matters for nominee work highlights:")
                
                # Create container for nominee selection
                nominee_container = st.container()
                
                # Track selected nominee indices
                selected_nominee_indices = []
                
                with nominee_container:
                    for i, client in enumerate(df["Client Name "]):
                        # Display additional information to help identify each client
                        matter_info = f"{client}"
                        if "Matter/Case Overview" in df.columns:
                            matter_info += f" - {df['Matter/Case Overview'].iloc[i]}"
                        
                        # Create checkbox for each client
                        # Disable checkbox once 3 are selected
                        disabled = len(selected_nominee_indices) >= 3 and i not in selected_nominee_indices
                        
                        if st.checkbox(matter_info, key=f"nominee_{i}", disabled=disabled):
                            if i not in selected_nominee_indices:
                                selected_nominee_indices.append(i)
                        elif i in selected_nominee_indices:
                            selected_nominee_indices.remove(i)
                
                st.write(f"Selected nominee matters: {len(selected_nominee_indices)} out of 3 maximum")
                
                # Warning if more than 3 selected
                if len(selected_nominee_indices) > 3:
                    st.warning("You have selected more than 3 nominee matters. Only the first 3 will be processed.")
                    selected_nominee_indices = selected_nominee_indices[:3]
            
            with tab2:
                st.subheader("Select Simple Work Highlights")
                st.write("Select any number of matters for simple work highlights:")
                
                # Create container for simple selection
                simple_container = st.container()
                
                # Track selected simple indices
                selected_simple_indices = []
                
                with simple_container:
                    for i, client in enumerate(df["Client Name "]):
                        # Skip if already selected as nominee
                        if i in selected_nominee_indices:
                            continue
                            
                        # Display additional information to help identify each client
                        matter_info = f"{client}"
                        if "Matter/Case Overview" in df.columns:
                            matter_info += f" - {df['Matter/Case Overview'].iloc[i]}"
                        
                        # Create checkbox for each client
                        if st.checkbox(matter_info, key=f"simple_{i}"):
                            selected_simple_indices.append(i)
                
                st.write(f"Selected simple matters: {len(selected_simple_indices)}")
            
            # Process forms button
            if st.button("Generate Selected Forms"):
                if not nominee_template_file and len(selected_nominee_indices) > 0:
                    st.error("Please upload the nominee template file.")
                elif not simple_template_file and len(selected_simple_indices) > 0:
                    st.error("Please upload the simple work highlight template file.")
                elif len(selected_nominee_indices) == 0 and len(selected_simple_indices) == 0:
                    st.error("Please select at least one matter to proceed.")
                else:
                    # Show progress
                    progress_bar = st.progress(0)
                    status_text = st.empty()
                    
                    status_text.text("Saving templates...")
                    
                    # Save templates to temporary files
                    if nominee_template_file:
                        with open("nominee_template.docx", "wb") as f:
                            f.write(nominee_template_file.getbuffer())
                    
                    if simple_template_file:
                        with open("simple_template.docx", "wb") as f:
                            f.write(simple_template_file.getbuffer())
                    
                    status_text.text("Processing selected matters...")
                    
                    # Process forms
                    nominee_template = "nominee_template.docx" if nominee_template_file else None
                    simple_template = "simple_template.docx" if simple_template_file else None
                    
                    output_path = process_benchmark_forms(
                        excel_file, 
                        nominee_template, 
                        simple_template, 
                        selected_nominee_indices, 
                        selected_simple_indices
                    )
                    
                    if output_path and os.path.exists(output_path):
                        progress_bar.progress(100)
                        status_text.text("Forms generated successfully!")
                        
                        total_forms = len(selected_nominee_indices) + len(selected_simple_indices)
                        st.success(f"Generated forms for {total_forms} selected matters!")
                        
                        # Provide download link
                        with open(output_path, "rb") as f:
                            st.download_button(
                                label="Download Combined Forms",
                                data=f,
                                file_name="Benchmark_Awards_2025_Submissions.docx",
                                mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                            )
                    else:
                        progress_bar.progress(100)
                        st.error("Failed to generate forms.")
        else:
            st.error("The Excel file does not contain a 'Client Name ' column. Please check your file.")

if __name__ == "__main__":
    main()   in this make the chnges to take template of both the doc form thorugh the code means its fiexd so fix that in code ..in fontend ask for excel only