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

# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx"  # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx"  # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"

# Function to append Word documents
def append_docs(doc_list, output_doc):
    combined_doc = Document()

    for doc in doc_list:
        sub_doc = Document(doc)
        for element in sub_doc.element.body:
            combined_doc.element.body.append(element)

    combined_doc.save(output_doc)

def create_individual_document(template_path, data, matter_count, output_path):
    """Create an individual document for a row of data based on a template."""
    doc = Document(template_path)
    
    # Identifying text based on template type
    if "Confidential" in template_path:
        identifier_text = f"Confidential Matter {matter_count}"
    else:
        identifier_text = f"Publishable Matter {matter_count}"

    # Update the table cell with matter count
    existing_text = doc.tables[0].cell(1, 0).text
    if "Matter" in existing_text:
        parts = existing_text.split(" ")
        parts[-1] = str(matter_count)
        doc.tables[0].cell(1, 0).text = " ".join(parts)
    else:
        doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"

    cell = doc.tables[0].cell(1, 0)
    
    # Formatting
    for paragraph in cell.paragraphs:
        for run in paragraph.runs:
            run.font.name = 'Times New Roman'
            run.font.size = Pt(12)
            run.font.bold = True
            
    cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    # Populate the document with data
    doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
    doc.tables[0].cell(3, 0).text = f" {data['Description  (in 500 words)']}"
    doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
    doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
    doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
    doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
    doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
    
    # Save the individual document
    doc.save(output_path)
    print(f"Saved individual document: {output_path}")
    return output_path  # Return path for later combining

def populate_chambers(excel_file, output_path):
    """Generate the documents based on the Excel input."""
    try:
        df = pd.read_excel(excel_file)
        individual_docs_no = []
        individual_docs_yes = []

        # Filter the DataFrame for rows
        df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
        df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']

        # Handle Publishable Matters for 'No' rows
        for index, row in df_no.iterrows():
            temporary_output_path = f"temp_publishable_no_{index}.docx"
            individual_doc_path = create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path)
            individual_docs_no.append(individual_doc_path)

        # Handle Publishable Matters for 'Yes' rows
        for index, row in df_yes.iterrows():
            temporary_output_path = f"temp_publishable_yes_{index}.docx"
            individual_doc_path = create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path)
            individual_docs_yes.append(individual_doc_path)

        # Combine in the desired order: No documents + after + Yes documents
        final_output_path = output_path
        append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, final_output_path)

        print(f"Combined document saved: {final_output_path}")

        # Clean up temporary documents
        for doc_path in individual_docs_no + individual_docs_yes:
            os.remove(doc_path)
            

    except Exception as e:
        print(f"Unexpected error: {e}")

# Streamlit application
def main():
    st.title("Fill Chambers and Partners Form")

    excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])

    if st.button("Fill the Template"):
        if excel_file:
            output_path = "combined_confidential_publishable.docx"
            populate_chambers(excel_file, output_path)

            # Check if the output file was created successfully
            if os.path.exists(output_path):
                st.success("Forms filled successfully!")

                # Provide download link
                with open(output_path, "rb") as f:
                    btn = st.download_button(
                        label="Download Filled Form",
                        data=f,
                        file_name="Chambers.docx",
                        mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                    )
            else:
                st.error("Failed to create the DOCX file.")
        else:
            st.error("Please upload the Excel file.")

if __name__ == "__main__":
    main()   in this i wanted a siebar in which i will place elmnts/compnets like for this i wnated chambers ...after choosing chamber diaply this content on the right of sodebar