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
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

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)
    
    # Determine if using "Yes" or "No" template for identifier text
    if "Confidential" in template_path:  # For the Yes template
        identifier_text = f"Confidential Matter {matter_count}"
    else:  # For the No template
        identifier_text = f"Publishable Matter {matter_count}"

    existing_text = doc.tables[0].cell(1, 0).text  # Get existing text from cell [1, 0]

    # Replace or append the numeric identifier
    if "Matter" in existing_text:
        parts = existing_text.split(" ")
        parts[-1] = str(matter_count)  # Update the number
        doc.tables[0].cell(1, 0).text = " ".join(parts)
    else:
        doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}"  # Append if not found

    cell = doc.tables[0].cell(1, 0)

    # Apply the specified 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 rest of the document with the provided 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 )']}"
    
    doc.save(output_path)
    print(f"Saved individual document: {output_path}")

def combine_documents(document_paths, output_path):
    """Combine multiple documents into a single document."""
    combined_doc = Document()
    
    for doc_path in document_paths:
        sub_doc = Document(doc_path)
        for element in sub_doc.element.body:
            combined_doc.element.body.append(element)

    combined_doc.save(output_path)
    print(f"Combined document saved: {output_path}")

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"
            create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path)
            individual_docs_no.append(temporary_output_path)

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

        # Combine all individual documents into one
        combine_documents(individual_docs_no + individual_docs_yes, output_path)

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

        print("Temporary documents cleaned up.")

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

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

    # User uploads
    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)
            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="combined_confidential_publishable.docx",
                    mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                )
        else:
            st.error("Please upload the Excel file.")

if __name__ == "__main__":
    main()    in this before publishable pdf means Tempalte_path_NO and after that before tempalte_pathyes i want to add some pages which i will append in two pdfs one is before.pdf and other is after.pdf