import pandas as pd
from docx import Document
from docx.shared import RGBColor, Pt
import os
from docx.oxml.ns import qn
import streamlit as st

# Hardcoded paths for the Word templates
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Iflr_Yes.docx"  # Template for Yes rows
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Iflr_No.docx"  # Template for No rows

def populate_chambers(excel_path, output_path):
    try:
        print("Loading Excel data...")
        df = pd.read_excel(excel_path)
        print(f"Excel data loaded: {len(df)} rows")
        
        # Variables to keep track of counts of documents
        confidential_count = 0
        non_confidential_count = 0
        
        # Create directories for temporary files if they don't exist
        temp_dir = os.path.join(os.path.dirname(output_path), "temp")
        os.makedirs(temp_dir, exist_ok=True)
        
        yes_files = []
        no_files = []
        
        # Iterate through each row of the DataFrame
        for i, row in df.iterrows():
            # Determine which document to use based on the Confidential/Publishable column
            confidential_val = str(row.get('Confidential / Publishable ', '')).strip()
            
            if confidential_val.lower() == 'yes' and confidential_count < 10:
                confidential_count += 1
                # Create a new document from the template for each row
                doc = Document(TEMPLATE_PATH_YES)
                if doc.tables:
                    table = doc.tables[0]  # Use the first table in the template
                    fill_table_with_data(row, table, True, confidential_count)
                    
                    # Save as temporary file
                    temp_file = os.path.join(temp_dir, f"yes_{i}.docx")
                    doc.save(temp_file)
                    yes_files.append(temp_file)
                    print(f"Created 'Yes' document for row {confidential_count}")
                else:
                    print(f"Warning: No tables found in the 'Yes' template.")
                    
            elif confidential_val.lower() == 'no' and non_confidential_count < 10:
                non_confidential_count += 1
                # Create a new document from the template for each row
                doc = Document(TEMPLATE_PATH_NO)
                if doc.tables:
                    table = doc.tables[0]  # Use the first table in the template
                    fill_table_with_data(row, table, False, non_confidential_count)
                    
                    # Save as temporary file
                    temp_file = os.path.join(temp_dir, f"no_{i}.docx")
                    doc.save(temp_file)
                    no_files.append(temp_file)
                    print(f"Created 'No' document for row {non_confidential_count}")
                else:
                    print(f"Warning: No tables found in the 'No' template.")
            else:
                print(f"Warning: Maximum limit reached for {'confidential' if confidential_val.lower() == 'yes' else 'non-confidential'} documents or unexpected value in the 'Confidential / Publishable ' column: {confidential_val}.")
        
        # Combine all documents: 'No' files followed by 'Yes' files
        combine_word_documents(no_files + yes_files, output_path)
        print(f"All documents combined successfully to {output_path}!")
        
        # Clean up temporary files
        for file in no_files + yes_files:
            try:
                os.remove(file)
            except Exception as e:
                print(f"Warning: Could not delete temporary file {file}: {e}")
        
    except Exception as e:
        print(f"Unexpected error: {e}")

def fill_table_with_data(row, table, is_confidential, count):
    try:
        if len(table.rows) >= 25:  # Make sure the table has enough rows
            # Fill cell 0 with the format "Example x/10"
            fill_cell(table.cell(0, 0), f"Example {min(count, 10)}/10", is_confidential, style='special')
            fill_cell(table.cell(2, 0), 'Y' if is_confidential else 'N', is_confidential)  # Cell 2 filled with 'Y' or 'N'
            fill_cell(table.cell(4, 0), str(row['Client Name ']), is_confidential)  # Client Name
            fill_cell(table.cell(14, 0), str(row['Value ']), is_confidential)  # Matter/Case Overview
            fill_cell(table.cell(20, 0), str(row['Lead partners']), is_confidential)  # Lead Partner
            fill_cell(table.cell(22, 0), str(row['Other Firms/counsels Involved']), is_confidential)  # Other Involved Firms
            fill_cell(table.cell(24, 0), str(row['Description  (in 500 words)']), is_confidential)  # Description
            
            print(f"Table filled with {'Yes' if is_confidential else 'No'} form data.")
        else:
            print(f"Warning: Table has only {len(table.rows)} rows. Expected at least 25.")
    except IndexError as e:
        print(f"Error: Unable to fill the table. {e}")

def fill_cell(cell, text, is_confidential, style=None):
    # Clear existing content by deleting each paragraph
    for paragraph in cell.paragraphs:
        cell._element.remove(paragraph._element)

    # Adding a new paragraph to the cell
    p = cell.add_paragraph()
    run = p.add_run(text)

    if style == 'special':
        # Applying the special style
        run.font.size = Pt(14)  # Font size 14
        run.bold = True  # Bold
        run.font.name = 'Cambria'  # Font family
        run.font.color.rgb = RGBColor(255, 255, 255)  # White color
        p.alignment = 1  # Centre alignment
    else:
        if is_confidential:
            run.font.color.rgb = RGBColor(255, 0, 0)  # Set the font color to red
        else:
            run.font.color.rgb = RGBColor(0, 0, 0)  # Default font color
    
    # Set font name for all text in the cell
    for run in p.runs:
        run.font.name = 'Cambria'

def combine_word_documents(files, output_path):
    """
    Combines multiple Word documents into one.
    First file becomes the base document, and each subsequent file's content is added to it.
    """
    if not files:
        print("No files to combine.")
        return
    
    print(f"Combining {len(files)} documents...")

    # Create a new document
    merged_document = Document()
    
    # Remove the blank paragraph that's created by default, if it exists
    if merged_document.paragraphs:
        p = merged_document.paragraphs[0]._element
        p.getparent().remove(p)
        p._p = p._element = None
    
    for i, file in enumerate(files):
        print(f"Adding content from {file}")
        try:
            sub_doc = Document(file)
            
            # Check if the document is not empty (has paragraphs)
            if len(sub_doc.paragraphs) > 0:
                # Add a page break before adding content, except for the first document
                if i > 0:
                    merged_document.add_page_break()

                # Copy all elements from the subdocument
                for element in sub_doc.element.body:
                    # Don't copy the section break
                    if element.tag != qn('w:sectPr'):
                        merged_document.element.body.append(element)
            else:
                print(f"Warning: Document {file} is empty and will not be added.")
        
        except Exception as e:
            print(f"Warning: Could not add content from {file}: {e}")
    
    # Save the combined document
    merged_document.save(output_path)
    print(f"Combined document saved to {output_path}")

# Streamlit application
def main():
    st.title("IFLR 1000 Form Generator")

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

    if st.button("Fill the Template"):
        if excel_file:
            with st.spinner("Processing..."):
                # Save the uploaded Excel file temporarily
                temp_excel_path = "temp_uploaded_file.xlsx"
                with open(temp_excel_path, "wb") as f:
                    f.write(excel_file.getbuffer())
                
                # Output path
                output_file = r"C:\Users\Administrator\Desktop\output.docx"
                
                # Call the populate_chambers function
                populate_chambers(temp_excel_path, output_file)

                # Provide a link to download the output file
                if os.path.exists(output_file):
                    st.success("Forms filled successfully! You can download it below.")
                    with open(output_file, "rb") as f:
                        st.download_button(
                            "Download Filled Form",
                            f,
                            file_name="IFLR_Output.docx",
                            mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        )
                else:
                    st.error("Failed to create the output file.")
                
                # Clean up the temporary file
                os.remove(temp_excel_path)
        else:
            st.error("Please upload the Excel file.")

if __name__ == "__main__":
    main()    in this we are getting  some empty white pGES IN the starting before downloDING reove those extar empty pages from the front