import os
import pandas as pd
from docx import Document
from datetime import datetime
import shutil

def populate_docx_template(excel_file, template_file, temp_dir):
    # Load Excel data
    df = pd.read_excel(excel_file)
    
    # Process each row in the Excel file
    for index, row in df.iterrows():
        # Load the template for each row
        doc = Document(template_file)
        
        # Extract data from the Excel row and handle NaN values
        client_name = row.get('Client Name ', '') if pd.notna(row.get('Client Name ', '')) else ''
        matter_overview = row.get('Matter/Case Overview', '') if pd.notna(row.get('Matter/Case Overview', '')) else ''
        description = row.get('Description  (in 500 words)', '') if pd.notna(row.get('Description  (in 500 words)', '')) else ''
        value = row.get('Value ', '') if pd.notna(row.get('Value ', '')) else ''
        lead_partners = row.get('Lead partners', '') if pd.notna(row.get('Lead partners', '')) else ''
        Team_partners = row.get('Team Members', '') if pd.notna(row.get('Team Members', '')) else ''
        Dates = row.get('Current Status (ongoing / completed )', '') if pd.notna(row.get('Current Status (ongoing / completed )', '')) else ''
        publishable = row.get('Confidential / Publishable', '') if pd.notna(row.get('Confidential / Publishable', '')) else ''

        if len(doc.tables) > 0:
            table = doc.tables[0]

        
            

            # Client Name
            table.cell(3, 0).text = client_name
            
            # Matter description
            matter_text = f"{matter_overview}\n\n{description}"
            table.cell(5, 0).text = matter_text
            
            # Deal value
            table.cell(6, 1).text = str(value)
           
            # Lead partner(s)
            table.cell(9, 0).text = lead_partners
            table.cell(13, 0).text = Team_partners

            
            table.cell(16, 3).text = Dates

        # Create a temporary filename
        clean_client_name = ''.join(c for c in client_name if c.isalnum() or c in [' ', '_']).replace(' ', '_')
        temp_filename = os.path.join(temp_dir, f"{clean_client_name}.docx")

        # Save the populated document to the temporary directory
        doc.save(temp_filename)
        print(f"Created temporary document: {temp_filename}")

def combine_documents(temp_dir, output_file):

    combined_doc = Document()
    
    for filename in os.listdir(temp_dir):
        if filename.endswith('.docx'):
            file_path = os.path.join(temp_dir, filename)
            sub_doc = Document(file_path)
            
            # Loop through each element in the sub-doc and copy it to the combined document
            for element in sub_doc.element.body:
                combined_doc.element.body.append(element)
                
    combined_doc.save(output_file)
    print(f"Combined document created: {output_file}")

def main():
    excel_file = r'c:\Users\Administrator\Documents\Submissions- Arbitration (version 1).xlsb.xlsx'
    template_file = r'c:\Users\Administrator\Desktop\legal500.docx'
    temp_dir = r'c:\Users\Administrator\Documents\temp_docs'
    output_file = r'c:\Users\Administrator\Desktop\combined_output.docx'

    os.makedirs(temp_dir, exist_ok=True)
    
    try:
        populate_docx_template(excel_file, template_file, temp_dir)
        combine_documents(temp_dir, output_file)
       # shutil.rmtree(temp_dir)
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()   in this just like above add steamlit intetrace for excel only and pass tempalte throughcode itslef