import pandas as pd
from docx import Document

def populate_chambers(excel_path, doc_path, output_path):
    try:
        print("Loading Excel data...")
        df = pd.read_excel(excel_path)
        print(f"Excel data loaded: {len(df)} rows")
        
        print("Loading Word document...")
        doc = Document(doc_path)
        tables = doc.tables
        print(f"Total tables found in document: {len(tables)}")
        
        # Check if tables exist in the document
        if not tables:
            print("Error: No tables found in document.")
            return
        
        # Iterate through each row of the DataFrame
        for i, row in df.iterrows():
            # If we have a table for this row
            if i < len(tables):
                table = tables[i]

                # Ensure that the table has enough rows
                if len(table.rows) >= 18:
                    try:
                        # Fill the cells from the row in the DataFrame
                        table.cell(2, 0).text = str(row['Client Name '])  # Client Name
                        table.cell(4, 0).text = str(row['Description  (in 500 words)'])  # Description
                        table.cell(6, 0).text = str(row['Value '])  # Matter/Case Overview
                        table.cell(10, 0).text = str(row['Lead partners'])  # Lead Partner
                        table.cell(12, 0).text = str(row['Team Members'])  # Team Members
                        table.cell(14, 0).text = str(row['Other Firms/counsels Involved'])  # Other Involved Firms
                        
                        # Directly take the current status or date, treating it as a string
                       # table.cell(16, 0).text = str(row['Date of completion or current status'])  # Directly capture the status or date

                        print(f"Matter {i + 1} populated successfully.")
                    except IndexError as e:
                        print(f"Error: Table {i + 1} has fewer rows than expected. Skipping entry. {e}")
                else:
                    print(f"Warning: Table {i + 1} has only {len(table.rows)} rows. Expected at least 18.")
            else:
                print(f"Warning: No more tables available in the document for extra rows in Excel. Extra rows: {len(df) - len(tables)}")
        
        # Save the updated document
        doc.save(output_path)
        print("Document updated successfully!")
        
    except Exception as e:
        print(f"Unexpected error: {e}")

# File paths
excel_path = r"C:\Users\Administrator\Documents\Submissions- Arbitration (version 1).xlsb.xlsx" 
doc_path = r"C:\Users\Administrator\Desktop\Bd team\Legal Era Law Firm.docx"
output_path = r"C:\Users\Administrator\Desktop\confif.docx" 

populate_chambers(excel_path, doc_path, output_path)    for this add a simple streamlit intrefcae like  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()   dont vhnge any fucnitonality just take refrence of second one for intrafce